Subversion Repositories wimsdev

Rev

Rev 15332 | Rev 16859 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14283 obado 1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: https://codemirror.net/LICENSE
3
 
4
// This is CodeMirror (https://codemirror.net), a code editor
5
// implemented in JavaScript on top of the browser's DOM.
6
//
7
// You can find some technical background for some of the code below
8
// at http://marijnhaverbeke.nl/blog/#cm-internals .
9
 
10
(function (global, factory) {
11
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
12
  typeof define === 'function' && define.amd ? define(factory) :
15152 obado 13
  (global = global || self, global.CodeMirror = factory());
14283 obado 14
}(this, (function () { 'use strict';
15
 
16
  // Kludges for bugs and behavior differences that can't be feature
17
  // detected are enabled based on userAgent etc sniffing.
18
  var userAgent = navigator.userAgent;
19
  var platform = navigator.platform;
20
 
21
  var gecko = /gecko\/\d/i.test(userAgent);
22
  var ie_upto10 = /MSIE \d/.test(userAgent);
23
  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
24
  var edge = /Edge\/(\d+)/.exec(userAgent);
25
  var ie = ie_upto10 || ie_11up || edge;
26
  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
27
  var webkit = !edge && /WebKit\//.test(userAgent);
28
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
29
  var chrome = !edge && /Chrome\//.test(userAgent);
30
  var presto = /Opera\//.test(userAgent);
31
  var safari = /Apple Computer/.test(navigator.vendor);
32
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
33
  var phantom = /PhantomJS/.test(userAgent);
34
 
16493 obado 35
  var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
14283 obado 36
  var android = /Android/.test(userAgent);
37
  // This is woefully incomplete. Suggestions for alternative methods welcome.
38
  var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
39
  var mac = ios || /Mac/.test(platform);
40
  var chromeOS = /\bCrOS\b/.test(userAgent);
41
  var windows = /win/i.test(platform);
42
 
43
  var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
44
  if (presto_version) { presto_version = Number(presto_version[1]); }
45
  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
46
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
47
  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
48
  var captureRightClick = gecko || (ie && ie_version >= 9);
49
 
50
  function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
51
 
52
  var rmClass = function(node, cls) {
53
    var current = node.className;
54
    var match = classTest(cls).exec(current);
55
    if (match) {
56
      var after = current.slice(match.index + match[0].length);
57
      node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
58
    }
59
  };
60
 
61
  function removeChildren(e) {
62
    for (var count = e.childNodes.length; count > 0; --count)
63
      { e.removeChild(e.firstChild); }
64
    return e
65
  }
66
 
67
  function removeChildrenAndAdd(parent, e) {
68
    return removeChildren(parent).appendChild(e)
69
  }
70
 
71
  function elt(tag, content, className, style) {
72
    var e = document.createElement(tag);
73
    if (className) { e.className = className; }
74
    if (style) { e.style.cssText = style; }
75
    if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
76
    else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
77
    return e
78
  }
79
  // wrapper for elt, which removes the elt from the accessibility tree
80
  function eltP(tag, content, className, style) {
81
    var e = elt(tag, content, className, style);
82
    e.setAttribute("role", "presentation");
83
    return e
84
  }
85
 
86
  var range;
87
  if (document.createRange) { range = function(node, start, end, endNode) {
88
    var r = document.createRange();
89
    r.setEnd(endNode || node, end);
90
    r.setStart(node, start);
91
    return r
92
  }; }
93
  else { range = function(node, start, end) {
94
    var r = document.body.createTextRange();
95
    try { r.moveToElementText(node.parentNode); }
96
    catch(e) { return r }
97
    r.collapse(true);
98
    r.moveEnd("character", end);
99
    r.moveStart("character", start);
100
    return r
101
  }; }
102
 
103
  function contains(parent, child) {
104
    if (child.nodeType == 3) // Android browser always returns false when child is a textnode
105
      { child = child.parentNode; }
106
    if (parent.contains)
107
      { return parent.contains(child) }
108
    do {
109
      if (child.nodeType == 11) { child = child.host; }
110
      if (child == parent) { return true }
111
    } while (child = child.parentNode)
112
  }
113
 
114
  function activeElt() {
115
    // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
116
    // IE < 10 will throw when accessed while the page is loading or in an iframe.
117
    // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
118
    var activeElement;
119
    try {
120
      activeElement = document.activeElement;
121
    } catch(e) {
122
      activeElement = document.body || null;
123
    }
124
    while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
125
      { activeElement = activeElement.shadowRoot.activeElement; }
126
    return activeElement
127
  }
128
 
129
  function addClass(node, cls) {
130
    var current = node.className;
131
    if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
132
  }
133
  function joinClasses(a, b) {
134
    var as = a.split(" ");
135
    for (var i = 0; i < as.length; i++)
136
      { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
137
    return b
138
  }
139
 
140
  var selectInput = function(node) { node.select(); };
141
  if (ios) // Mobile Safari apparently has a bug where select() is broken.
142
    { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
143
  else if (ie) // Suppress mysterious IE10 errors
144
    { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
145
 
146
  function bind(f) {
147
    var args = Array.prototype.slice.call(arguments, 1);
148
    return function(){return f.apply(null, args)}
149
  }
150
 
151
  function copyObj(obj, target, overwrite) {
152
    if (!target) { target = {}; }
153
    for (var prop in obj)
154
      { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
155
        { target[prop] = obj[prop]; } }
156
    return target
157
  }
158
 
159
  // Counts the column offset in a string, taking tabs into account.
160
  // Used mostly to find indentation.
161
  function countColumn(string, end, tabSize, startIndex, startValue) {
162
    if (end == null) {
163
      end = string.search(/[^\s\u00a0]/);
164
      if (end == -1) { end = string.length; }
165
    }
166
    for (var i = startIndex || 0, n = startValue || 0;;) {
167
      var nextTab = string.indexOf("\t", i);
168
      if (nextTab < 0 || nextTab >= end)
169
        { return n + (end - i) }
170
      n += nextTab - i;
171
      n += tabSize - (n % tabSize);
172
      i = nextTab + 1;
173
    }
174
  }
175
 
15152 obado 176
  var Delayed = function() {
177
    this.id = null;
178
    this.f = null;
179
    this.time = 0;
180
    this.handler = bind(this.onTimeout, this);
181
  };
182
  Delayed.prototype.onTimeout = function (self) {
183
    self.id = 0;
184
    if (self.time <= +new Date) {
185
      self.f();
186
    } else {
187
      setTimeout(self.handler, self.time - +new Date);
188
    }
189
  };
14283 obado 190
  Delayed.prototype.set = function (ms, f) {
15152 obado 191
    this.f = f;
192
    var time = +new Date + ms;
193
    if (!this.id || time < this.time) {
194
      clearTimeout(this.id);
195
      this.id = setTimeout(this.handler, ms);
196
      this.time = time;
197
    }
14283 obado 198
  };
199
 
200
  function indexOf(array, elt) {
201
    for (var i = 0; i < array.length; ++i)
202
      { if (array[i] == elt) { return i } }
203
    return -1
204
  }
205
 
206
  // Number of pixels added to scroller and sizer to hide scrollbar
15152 obado 207
  var scrollerGap = 50;
14283 obado 208
 
209
  // Returned or thrown by various protocols to signal 'I'm not
210
  // handling this'.
211
  var Pass = {toString: function(){return "CodeMirror.Pass"}};
212
 
213
  // Reused option objects for setSelection & friends
214
  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
215
 
216
  // The inverse of countColumn -- find the offset that corresponds to
217
  // a particular column.
218
  function findColumn(string, goal, tabSize) {
219
    for (var pos = 0, col = 0;;) {
220
      var nextTab = string.indexOf("\t", pos);
221
      if (nextTab == -1) { nextTab = string.length; }
222
      var skipped = nextTab - pos;
223
      if (nextTab == string.length || col + skipped >= goal)
224
        { return pos + Math.min(skipped, goal - col) }
225
      col += nextTab - pos;
226
      col += tabSize - (col % tabSize);
227
      pos = nextTab + 1;
228
      if (col >= goal) { return pos }
229
    }
230
  }
231
 
232
  var spaceStrs = [""];
233
  function spaceStr(n) {
234
    while (spaceStrs.length <= n)
235
      { spaceStrs.push(lst(spaceStrs) + " "); }
236
    return spaceStrs[n]
237
  }
238
 
239
  function lst(arr) { return arr[arr.length-1] }
240
 
241
  function map(array, f) {
242
    var out = [];
243
    for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
244
    return out
245
  }
246
 
247
  function insertSorted(array, value, score) {
248
    var pos = 0, priority = score(value);
249
    while (pos < array.length && score(array[pos]) <= priority) { pos++; }
250
    array.splice(pos, 0, value);
251
  }
252
 
253
  function nothing() {}
254
 
255
  function createObj(base, props) {
256
    var inst;
257
    if (Object.create) {
258
      inst = Object.create(base);
259
    } else {
260
      nothing.prototype = base;
261
      inst = new nothing();
262
    }
263
    if (props) { copyObj(props, inst); }
264
    return inst
265
  }
266
 
267
  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
268
  function isWordCharBasic(ch) {
269
    return /\w/.test(ch) || ch > "\x80" &&
270
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
271
  }
272
  function isWordChar(ch, helper) {
273
    if (!helper) { return isWordCharBasic(ch) }
274
    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
275
    return helper.test(ch)
276
  }
277
 
278
  function isEmpty(obj) {
279
    for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
280
    return true
281
  }
282
 
283
  // Extending unicode characters. A series of a non-extending char +
284
  // any number of extending chars is treated as a single unit as far
285
  // as editing and measuring is concerned. This is not fully correct,
286
  // since some scripts/fonts/browsers also treat other configurations
287
  // of code points as a group.
288
  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]/;
289
  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
290
 
291
  // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
292
  function skipExtendingChars(str, pos, dir) {
293
    while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
294
    return pos
295
  }
296
 
297
  // Returns the value from the range [`from`; `to`] that satisfies
298
  // `pred` and is closest to `from`. Assumes that at least `to`
299
  // satisfies `pred`. Supports `from` being greater than `to`.
300
  function findFirst(pred, from, to) {
301
    // At any point we are certain `to` satisfies `pred`, don't know
302
    // whether `from` does.
303
    var dir = from > to ? -1 : 1;
304
    for (;;) {
305
      if (from == to) { return from }
306
      var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
307
      if (mid == from) { return pred(mid) ? from : to }
308
      if (pred(mid)) { to = mid; }
309
      else { from = mid + dir; }
310
    }
311
  }
312
 
313
  // BIDI HELPERS
314
 
315
  function iterateBidiSections(order, from, to, f) {
316
    if (!order) { return f(from, to, "ltr", 0) }
317
    var found = false;
318
    for (var i = 0; i < order.length; ++i) {
319
      var part = order[i];
320
      if (part.from < to && part.to > from || from == to && part.to == from) {
321
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
322
        found = true;
323
      }
324
    }
325
    if (!found) { f(from, to, "ltr"); }
326
  }
327
 
328
  var bidiOther = null;
329
  function getBidiPartAt(order, ch, sticky) {
330
    var found;
331
    bidiOther = null;
332
    for (var i = 0; i < order.length; ++i) {
333
      var cur = order[i];
334
      if (cur.from < ch && cur.to > ch) { return i }
335
      if (cur.to == ch) {
336
        if (cur.from != cur.to && sticky == "before") { found = i; }
337
        else { bidiOther = i; }
338
      }
339
      if (cur.from == ch) {
340
        if (cur.from != cur.to && sticky != "before") { found = i; }
341
        else { bidiOther = i; }
342
      }
343
    }
344
    return found != null ? found : bidiOther
345
  }
346
 
347
  // Bidirectional ordering algorithm
348
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
349
  // that this (partially) implements.
350
 
351
  // One-char codes used for character types:
352
  // L (L):   Left-to-Right
353
  // R (R):   Right-to-Left
354
  // r (AL):  Right-to-Left Arabic
355
  // 1 (EN):  European Number
356
  // + (ES):  European Number Separator
357
  // % (ET):  European Number Terminator
358
  // n (AN):  Arabic Number
359
  // , (CS):  Common Number Separator
360
  // m (NSM): Non-Spacing Mark
361
  // b (BN):  Boundary Neutral
362
  // s (B):   Paragraph Separator
363
  // t (S):   Segment Separator
364
  // w (WS):  Whitespace
365
  // N (ON):  Other Neutrals
366
 
367
  // Returns null if characters are ordered as they appear
368
  // (left-to-right), or an array of sections ({from, to, level}
369
  // objects) in the order in which they occur visually.
370
  var bidiOrdering = (function() {
371
    // Character types for codepoints 0 to 0xff
372
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
373
    // Character types for codepoints 0x600 to 0x6f9
374
    var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
375
    function charType(code) {
376
      if (code <= 0xf7) { return lowTypes.charAt(code) }
377
      else if (0x590 <= code && code <= 0x5f4) { return "R" }
378
      else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
379
      else if (0x6ee <= code && code <= 0x8ac) { return "r" }
380
      else if (0x2000 <= code && code <= 0x200b) { return "w" }
381
      else if (code == 0x200c) { return "b" }
382
      else { return "L" }
383
    }
384
 
385
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
386
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
387
 
388
    function BidiSpan(level, from, to) {
389
      this.level = level;
390
      this.from = from; this.to = to;
391
    }
392
 
393
    return function(str, direction) {
394
      var outerType = direction == "ltr" ? "L" : "R";
395
 
396
      if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
397
      var len = str.length, types = [];
398
      for (var i = 0; i < len; ++i)
399
        { types.push(charType(str.charCodeAt(i))); }
400
 
401
      // W1. Examine each non-spacing mark (NSM) in the level run, and
402
      // change the type of the NSM to the type of the previous
403
      // character. If the NSM is at the start of the level run, it will
404
      // get the type of sor.
405
      for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
406
        var type = types[i$1];
407
        if (type == "m") { types[i$1] = prev; }
408
        else { prev = type; }
409
      }
410
 
411
      // W2. Search backwards from each instance of a European number
412
      // until the first strong type (R, L, AL, or sor) is found. If an
413
      // AL is found, change the type of the European number to Arabic
414
      // number.
415
      // W3. Change all ALs to R.
416
      for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
417
        var type$1 = types[i$2];
418
        if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
419
        else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
420
      }
421
 
422
      // W4. A single European separator between two European numbers
423
      // changes to a European number. A single common separator between
424
      // two numbers of the same type changes to that type.
425
      for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
426
        var type$2 = types[i$3];
427
        if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
428
        else if (type$2 == "," && prev$1 == types[i$3+1] &&
429
                 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
430
        prev$1 = type$2;
431
      }
432
 
433
      // W5. A sequence of European terminators adjacent to European
434
      // numbers changes to all European numbers.
435
      // W6. Otherwise, separators and terminators change to Other
436
      // Neutral.
437
      for (var i$4 = 0; i$4 < len; ++i$4) {
438
        var type$3 = types[i$4];
439
        if (type$3 == ",") { types[i$4] = "N"; }
440
        else if (type$3 == "%") {
441
          var end = (void 0);
442
          for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
443
          var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
444
          for (var j = i$4; j < end; ++j) { types[j] = replace; }
445
          i$4 = end - 1;
446
        }
447
      }
448
 
449
      // W7. Search backwards from each instance of a European number
450
      // until the first strong type (R, L, or sor) is found. If an L is
451
      // found, then change the type of the European number to L.
452
      for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
453
        var type$4 = types[i$5];
454
        if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
455
        else if (isStrong.test(type$4)) { cur$1 = type$4; }
456
      }
457
 
458
      // N1. A sequence of neutrals takes the direction of the
459
      // surrounding strong text if the text on both sides has the same
460
      // direction. European and Arabic numbers act as if they were R in
461
      // terms of their influence on neutrals. Start-of-level-run (sor)
462
      // and end-of-level-run (eor) are used at level run boundaries.
463
      // N2. Any remaining neutrals take the embedding direction.
464
      for (var i$6 = 0; i$6 < len; ++i$6) {
465
        if (isNeutral.test(types[i$6])) {
466
          var end$1 = (void 0);
467
          for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
468
          var before = (i$6 ? types[i$6-1] : outerType) == "L";
469
          var after = (end$1 < len ? types[end$1] : outerType) == "L";
470
          var replace$1 = before == after ? (before ? "L" : "R") : outerType;
471
          for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
472
          i$6 = end$1 - 1;
473
        }
474
      }
475
 
476
      // Here we depart from the documented algorithm, in order to avoid
477
      // building up an actual levels array. Since there are only three
478
      // levels (0, 1, 2) in an implementation that doesn't take
479
      // explicit embedding into account, we can build up the order on
480
      // the fly, without following the level-based algorithm.
481
      var order = [], m;
482
      for (var i$7 = 0; i$7 < len;) {
483
        if (countsAsLeft.test(types[i$7])) {
484
          var start = i$7;
485
          for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
486
          order.push(new BidiSpan(0, start, i$7));
487
        } else {
15152 obado 488
          var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
14283 obado 489
          for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
490
          for (var j$2 = pos; j$2 < i$7;) {
491
            if (countsAsNum.test(types[j$2])) {
15152 obado 492
              if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
14283 obado 493
              var nstart = j$2;
494
              for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
495
              order.splice(at, 0, new BidiSpan(2, nstart, j$2));
15152 obado 496
              at += isRTL;
14283 obado 497
              pos = j$2;
498
            } else { ++j$2; }
499
          }
500
          if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
501
        }
502
      }
503
      if (direction == "ltr") {
504
        if (order[0].level == 1 && (m = str.match(/^\s+/))) {
505
          order[0].from = m[0].length;
506
          order.unshift(new BidiSpan(0, 0, m[0].length));
507
        }
508
        if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
509
          lst(order).to -= m[0].length;
510
          order.push(new BidiSpan(0, len - m[0].length, len));
511
        }
512
      }
513
 
514
      return direction == "rtl" ? order.reverse() : order
515
    }
516
  })();
517
 
518
  // Get the bidi ordering for the given line (and cache it). Returns
519
  // false for lines that are fully left-to-right, and an array of
520
  // BidiSpan objects otherwise.
521
  function getOrder(line, direction) {
522
    var order = line.order;
523
    if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
524
    return order
525
  }
526
 
527
  // EVENT HANDLING
528
 
529
  // Lightweight event framework. on/off also work on DOM nodes,
530
  // registering native DOM handlers.
531
 
532
  var noHandlers = [];
533
 
534
  var on = function(emitter, type, f) {
535
    if (emitter.addEventListener) {
536
      emitter.addEventListener(type, f, false);
537
    } else if (emitter.attachEvent) {
538
      emitter.attachEvent("on" + type, f);
539
    } else {
15152 obado 540
      var map = emitter._handlers || (emitter._handlers = {});
541
      map[type] = (map[type] || noHandlers).concat(f);
14283 obado 542
    }
543
  };
544
 
545
  function getHandlers(emitter, type) {
546
    return emitter._handlers && emitter._handlers[type] || noHandlers
547
  }
548
 
549
  function off(emitter, type, f) {
550
    if (emitter.removeEventListener) {
551
      emitter.removeEventListener(type, f, false);
552
    } else if (emitter.detachEvent) {
553
      emitter.detachEvent("on" + type, f);
554
    } else {
15152 obado 555
      var map = emitter._handlers, arr = map && map[type];
14283 obado 556
      if (arr) {
557
        var index = indexOf(arr, f);
558
        if (index > -1)
15152 obado 559
          { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
14283 obado 560
      }
561
    }
562
  }
563
 
564
  function signal(emitter, type /*, values...*/) {
565
    var handlers = getHandlers(emitter, type);
566
    if (!handlers.length) { return }
567
    var args = Array.prototype.slice.call(arguments, 2);
568
    for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
569
  }
570
 
571
  // The DOM events that CodeMirror handles can be overridden by
572
  // registering a (non-DOM) handler on the editor for the event name,
573
  // and preventDefault-ing the event in that handler.
574
  function signalDOMEvent(cm, e, override) {
575
    if (typeof e == "string")
576
      { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
577
    signal(cm, override || e.type, cm, e);
578
    return e_defaultPrevented(e) || e.codemirrorIgnore
579
  }
580
 
581
  function signalCursorActivity(cm) {
582
    var arr = cm._handlers && cm._handlers.cursorActivity;
583
    if (!arr) { return }
584
    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
585
    for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
586
      { set.push(arr[i]); } }
587
  }
588
 
589
  function hasHandler(emitter, type) {
590
    return getHandlers(emitter, type).length > 0
591
  }
592
 
593
  // Add on and off methods to a constructor's prototype, to make
594
  // registering events on such objects more convenient.
595
  function eventMixin(ctor) {
596
    ctor.prototype.on = function(type, f) {on(this, type, f);};
597
    ctor.prototype.off = function(type, f) {off(this, type, f);};
598
  }
599
 
600
  // Due to the fact that we still support jurassic IE versions, some
601
  // compatibility wrappers are needed.
602
 
603
  function e_preventDefault(e) {
604
    if (e.preventDefault) { e.preventDefault(); }
605
    else { e.returnValue = false; }
606
  }
607
  function e_stopPropagation(e) {
608
    if (e.stopPropagation) { e.stopPropagation(); }
609
    else { e.cancelBubble = true; }
610
  }
611
  function e_defaultPrevented(e) {
612
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
613
  }
614
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
615
 
616
  function e_target(e) {return e.target || e.srcElement}
617
  function e_button(e) {
618
    var b = e.which;
619
    if (b == null) {
620
      if (e.button & 1) { b = 1; }
621
      else if (e.button & 2) { b = 3; }
622
      else if (e.button & 4) { b = 2; }
623
    }
624
    if (mac && e.ctrlKey && b == 1) { b = 3; }
625
    return b
626
  }
627
 
628
  // Detect drag-and-drop
629
  var dragAndDrop = function() {
630
    // There is *some* kind of drag-and-drop support in IE6-8, but I
631
    // couldn't get it to work yet.
632
    if (ie && ie_version < 9) { return false }
633
    var div = elt('div');
634
    return "draggable" in div || "dragDrop" in div
635
  }();
636
 
637
  var zwspSupported;
638
  function zeroWidthElement(measure) {
639
    if (zwspSupported == null) {
640
      var test = elt("span", "\u200b");
641
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
642
      if (measure.firstChild.offsetHeight != 0)
643
        { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
644
    }
645
    var node = zwspSupported ? elt("span", "\u200b") :
646
      elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
647
    node.setAttribute("cm-text", "");
648
    return node
649
  }
650
 
651
  // Feature-detect IE's crummy client rect reporting for bidi text
652
  var badBidiRects;
653
  function hasBadBidiRects(measure) {
654
    if (badBidiRects != null) { return badBidiRects }
655
    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
656
    var r0 = range(txt, 0, 1).getBoundingClientRect();
657
    var r1 = range(txt, 1, 2).getBoundingClientRect();
658
    removeChildren(measure);
659
    if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
660
    return badBidiRects = (r1.right - r0.right < 3)
661
  }
662
 
663
  // See if "".split is the broken IE version, if so, provide an
664
  // alternative way to split lines.
665
  var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
666
    var pos = 0, result = [], l = string.length;
667
    while (pos <= l) {
668
      var nl = string.indexOf("\n", pos);
669
      if (nl == -1) { nl = string.length; }
670
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
671
      var rt = line.indexOf("\r");
672
      if (rt != -1) {
673
        result.push(line.slice(0, rt));
674
        pos += rt + 1;
675
      } else {
676
        result.push(line);
677
        pos = nl + 1;
678
      }
679
    }
680
    return result
681
  } : function (string) { return string.split(/\r\n?|\n/); };
682
 
683
  var hasSelection = window.getSelection ? function (te) {
684
    try { return te.selectionStart != te.selectionEnd }
685
    catch(e) { return false }
686
  } : function (te) {
15152 obado 687
    var range;
688
    try {range = te.ownerDocument.selection.createRange();}
14283 obado 689
    catch(e) {}
15152 obado 690
    if (!range || range.parentElement() != te) { return false }
691
    return range.compareEndPoints("StartToEnd", range) != 0
14283 obado 692
  };
693
 
694
  var hasCopyEvent = (function () {
695
    var e = elt("div");
696
    if ("oncopy" in e) { return true }
697
    e.setAttribute("oncopy", "return;");
698
    return typeof e.oncopy == "function"
699
  })();
700
 
701
  var badZoomedRects = null;
702
  function hasBadZoomedRects(measure) {
703
    if (badZoomedRects != null) { return badZoomedRects }
704
    var node = removeChildrenAndAdd(measure, elt("span", "x"));
705
    var normal = node.getBoundingClientRect();
706
    var fromRange = range(node, 0, 1).getBoundingClientRect();
707
    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
708
  }
709
 
710
  // Known modes, by name and by MIME
711
  var modes = {}, mimeModes = {};
712
 
713
  // Extra arguments are stored as the mode's dependencies, which is
714
  // used by (legacy) mechanisms like loadmode.js to automatically
715
  // load a mode. (Preferred mechanism is the require/define calls.)
716
  function defineMode(name, mode) {
717
    if (arguments.length > 2)
718
      { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
719
    modes[name] = mode;
720
  }
721
 
722
  function defineMIME(mime, spec) {
723
    mimeModes[mime] = spec;
724
  }
725
 
726
  // Given a MIME type, a {name, ...options} config object, or a name
727
  // string, return a mode config object.
728
  function resolveMode(spec) {
729
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
730
      spec = mimeModes[spec];
731
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
732
      var found = mimeModes[spec.name];
733
      if (typeof found == "string") { found = {name: found}; }
734
      spec = createObj(found, spec);
735
      spec.name = found.name;
736
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
737
      return resolveMode("application/xml")
738
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
739
      return resolveMode("application/json")
740
    }
741
    if (typeof spec == "string") { return {name: spec} }
742
    else { return spec || {name: "null"} }
743
  }
744
 
745
  // Given a mode spec (anything that resolveMode accepts), find and
746
  // initialize an actual mode object.
747
  function getMode(options, spec) {
748
    spec = resolveMode(spec);
749
    var mfactory = modes[spec.name];
750
    if (!mfactory) { return getMode(options, "text/plain") }
751
    var modeObj = mfactory(options, spec);
752
    if (modeExtensions.hasOwnProperty(spec.name)) {
753
      var exts = modeExtensions[spec.name];
754
      for (var prop in exts) {
755
        if (!exts.hasOwnProperty(prop)) { continue }
756
        if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
757
        modeObj[prop] = exts[prop];
758
      }
759
    }
760
    modeObj.name = spec.name;
761
    if (spec.helperType) { modeObj.helperType = spec.helperType; }
762
    if (spec.modeProps) { for (var prop$1 in spec.modeProps)
763
      { modeObj[prop$1] = spec.modeProps[prop$1]; } }
764
 
765
    return modeObj
766
  }
767
 
768
  // This can be used to attach properties to mode objects from
769
  // outside the actual mode definition.
770
  var modeExtensions = {};
771
  function extendMode(mode, properties) {
772
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
773
    copyObj(properties, exts);
774
  }
775
 
776
  function copyState(mode, state) {
777
    if (state === true) { return state }
778
    if (mode.copyState) { return mode.copyState(state) }
779
    var nstate = {};
780
    for (var n in state) {
781
      var val = state[n];
782
      if (val instanceof Array) { val = val.concat([]); }
783
      nstate[n] = val;
784
    }
785
    return nstate
786
  }
787
 
788
  // Given a mode and a state (for that mode), find the inner mode and
789
  // state at the position that the state refers to.
790
  function innerMode(mode, state) {
791
    var info;
792
    while (mode.innerMode) {
793
      info = mode.innerMode(state);
794
      if (!info || info.mode == mode) { break }
795
      state = info.state;
796
      mode = info.mode;
797
    }
798
    return info || {mode: mode, state: state}
799
  }
800
 
801
  function startState(mode, a1, a2) {
802
    return mode.startState ? mode.startState(a1, a2) : true
803
  }
804
 
805
  // STRING STREAM
806
 
807
  // Fed to the mode parsers, provides helper functions to make
808
  // parsers more succinct.
809
 
810
  var StringStream = function(string, tabSize, lineOracle) {
811
    this.pos = this.start = 0;
812
    this.string = string;
813
    this.tabSize = tabSize || 8;
814
    this.lastColumnPos = this.lastColumnValue = 0;
815
    this.lineStart = 0;
816
    this.lineOracle = lineOracle;
817
  };
818
 
819
  StringStream.prototype.eol = function () {return this.pos >= this.string.length};
820
  StringStream.prototype.sol = function () {return this.pos == this.lineStart};
821
  StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
822
  StringStream.prototype.next = function () {
823
    if (this.pos < this.string.length)
824
      { return this.string.charAt(this.pos++) }
825
  };
826
  StringStream.prototype.eat = function (match) {
827
    var ch = this.string.charAt(this.pos);
828
    var ok;
829
    if (typeof match == "string") { ok = ch == match; }
830
    else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
831
    if (ok) {++this.pos; return ch}
832
  };
833
  StringStream.prototype.eatWhile = function (match) {
834
    var start = this.pos;
835
    while (this.eat(match)){}
836
    return this.pos > start
837
  };
838
  StringStream.prototype.eatSpace = function () {
839
    var start = this.pos;
15152 obado 840
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
14283 obado 841
    return this.pos > start
842
  };
843
  StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
844
  StringStream.prototype.skipTo = function (ch) {
845
    var found = this.string.indexOf(ch, this.pos);
846
    if (found > -1) {this.pos = found; return true}
847
  };
848
  StringStream.prototype.backUp = function (n) {this.pos -= n;};
849
  StringStream.prototype.column = function () {
850
    if (this.lastColumnPos < this.start) {
851
      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
852
      this.lastColumnPos = this.start;
853
    }
854
    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
855
  };
856
  StringStream.prototype.indentation = function () {
857
    return countColumn(this.string, null, this.tabSize) -
858
      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
859
  };
860
  StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
861
    if (typeof pattern == "string") {
862
      var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
863
      var substr = this.string.substr(this.pos, pattern.length);
864
      if (cased(substr) == cased(pattern)) {
865
        if (consume !== false) { this.pos += pattern.length; }
866
        return true
867
      }
868
    } else {
869
      var match = this.string.slice(this.pos).match(pattern);
870
      if (match && match.index > 0) { return null }
871
      if (match && consume !== false) { this.pos += match[0].length; }
872
      return match
873
    }
874
  };
875
  StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
876
  StringStream.prototype.hideFirstChars = function (n, inner) {
877
    this.lineStart += n;
878
    try { return inner() }
879
    finally { this.lineStart -= n; }
880
  };
881
  StringStream.prototype.lookAhead = function (n) {
882
    var oracle = this.lineOracle;
883
    return oracle && oracle.lookAhead(n)
884
  };
885
  StringStream.prototype.baseToken = function () {
886
    var oracle = this.lineOracle;
887
    return oracle && oracle.baseToken(this.pos)
888
  };
889
 
890
  // Find the line object corresponding to the given line number.
891
  function getLine(doc, n) {
892
    n -= doc.first;
893
    if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
894
    var chunk = doc;
895
    while (!chunk.lines) {
896
      for (var i = 0;; ++i) {
897
        var child = chunk.children[i], sz = child.chunkSize();
898
        if (n < sz) { chunk = child; break }
899
        n -= sz;
900
      }
901
    }
902
    return chunk.lines[n]
903
  }
904
 
905
  // Get the part of a document between two positions, as an array of
906
  // strings.
907
  function getBetween(doc, start, end) {
908
    var out = [], n = start.line;
909
    doc.iter(start.line, end.line + 1, function (line) {
910
      var text = line.text;
911
      if (n == end.line) { text = text.slice(0, end.ch); }
912
      if (n == start.line) { text = text.slice(start.ch); }
913
      out.push(text);
914
      ++n;
915
    });
916
    return out
917
  }
918
  // Get the lines between from and to, as array of strings.
919
  function getLines(doc, from, to) {
920
    var out = [];
921
    doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
922
    return out
923
  }
924
 
925
  // Update the height of a line, propagating the height change
926
  // upwards to parent nodes.
927
  function updateLineHeight(line, height) {
928
    var diff = height - line.height;
929
    if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
930
  }
931
 
932
  // Given a line object, find its line number by walking up through
933
  // its parent links.
934
  function lineNo(line) {
935
    if (line.parent == null) { return null }
936
    var cur = line.parent, no = indexOf(cur.lines, line);
937
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
938
      for (var i = 0;; ++i) {
939
        if (chunk.children[i] == cur) { break }
940
        no += chunk.children[i].chunkSize();
941
      }
942
    }
943
    return no + cur.first
944
  }
945
 
946
  // Find the line at the given vertical position, using the height
947
  // information in the document tree.
948
  function lineAtHeight(chunk, h) {
949
    var n = chunk.first;
950
    outer: do {
951
      for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
952
        var child = chunk.children[i$1], ch = child.height;
953
        if (h < ch) { chunk = child; continue outer }
954
        h -= ch;
955
        n += child.chunkSize();
956
      }
957
      return n
958
    } while (!chunk.lines)
959
    var i = 0;
960
    for (; i < chunk.lines.length; ++i) {
961
      var line = chunk.lines[i], lh = line.height;
962
      if (h < lh) { break }
963
      h -= lh;
964
    }
965
    return n + i
966
  }
967
 
968
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
969
 
970
  function lineNumberFor(options, i) {
971
    return String(options.lineNumberFormatter(i + options.firstLineNumber))
972
  }
973
 
974
  // A Pos instance represents a position within the text.
975
  function Pos(line, ch, sticky) {
976
    if ( sticky === void 0 ) sticky = null;
977
 
978
    if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
979
    this.line = line;
980
    this.ch = ch;
981
    this.sticky = sticky;
982
  }
983
 
984
  // Compare two positions, return 0 if they are the same, a negative
985
  // number when a is less, and a positive number otherwise.
986
  function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
987
 
988
  function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
989
 
990
  function copyPos(x) {return Pos(x.line, x.ch)}
991
  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
992
  function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
993
 
994
  // Most of the external API clips given positions to make sure they
995
  // actually exist within the document.
996
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
997
  function clipPos(doc, pos) {
998
    if (pos.line < doc.first) { return Pos(doc.first, 0) }
999
    var last = doc.first + doc.size - 1;
1000
    if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
1001
    return clipToLen(pos, getLine(doc, pos.line).text.length)
1002
  }
1003
  function clipToLen(pos, linelen) {
1004
    var ch = pos.ch;
1005
    if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
1006
    else if (ch < 0) { return Pos(pos.line, 0) }
1007
    else { return pos }
1008
  }
1009
  function clipPosArray(doc, array) {
1010
    var out = [];
1011
    for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
1012
    return out
1013
  }
1014
 
1015
  var SavedContext = function(state, lookAhead) {
1016
    this.state = state;
1017
    this.lookAhead = lookAhead;
1018
  };
1019
 
1020
  var Context = function(doc, state, line, lookAhead) {
1021
    this.state = state;
1022
    this.doc = doc;
1023
    this.line = line;
1024
    this.maxLookAhead = lookAhead || 0;
1025
    this.baseTokens = null;
1026
    this.baseTokenPos = 1;
1027
  };
1028
 
1029
  Context.prototype.lookAhead = function (n) {
1030
    var line = this.doc.getLine(this.line + n);
1031
    if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
1032
    return line
1033
  };
1034
 
1035
  Context.prototype.baseToken = function (n) {
1036
    if (!this.baseTokens) { return null }
1037
    while (this.baseTokens[this.baseTokenPos] <= n)
15152 obado 1038
      { this.baseTokenPos += 2; }
14283 obado 1039
    var type = this.baseTokens[this.baseTokenPos + 1];
1040
    return {type: type && type.replace(/( |^)overlay .*/, ""),
1041
            size: this.baseTokens[this.baseTokenPos] - n}
1042
  };
1043
 
1044
  Context.prototype.nextLine = function () {
1045
    this.line++;
1046
    if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1047
  };
1048
 
1049
  Context.fromSaved = function (doc, saved, line) {
1050
    if (saved instanceof SavedContext)
1051
      { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
1052
    else
1053
      { return new Context(doc, copyState(doc.mode, saved), line) }
1054
  };
1055
 
1056
  Context.prototype.save = function (copy) {
1057
    var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
1058
    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
1059
  };
1060
 
1061
 
1062
  // Compute a style array (an array starting with a mode generation
1063
  // -- for invalidation -- followed by pairs of end positions and
1064
  // style strings), which is used to highlight the tokens on the
1065
  // line.
1066
  function highlightLine(cm, line, context, forceToEnd) {
1067
    // A styles array always starts with a number identifying the
1068
    // mode/overlays that it is based on (for easy invalidation).
1069
    var st = [cm.state.modeGen], lineClasses = {};
1070
    // Compute the base array of styles
1071
    runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
1072
            lineClasses, forceToEnd);
1073
    var state = context.state;
1074
 
1075
    // Run overlays, adjust style array.
1076
    var loop = function ( o ) {
1077
      context.baseTokens = st;
1078
      var overlay = cm.state.overlays[o], i = 1, at = 0;
1079
      context.state = true;
1080
      runMode(cm, line.text, overlay.mode, context, function (end, style) {
1081
        var start = i;
1082
        // Ensure there's a token end at the current position, and that i points at it
1083
        while (at < end) {
1084
          var i_end = st[i];
1085
          if (i_end > end)
1086
            { st.splice(i, 1, end, st[i+1], i_end); }
1087
          i += 2;
1088
          at = Math.min(end, i_end);
1089
        }
1090
        if (!style) { return }
1091
        if (overlay.opaque) {
1092
          st.splice(start, i - start, end, "overlay " + style);
1093
          i = start + 2;
1094
        } else {
1095
          for (; start < i; start += 2) {
1096
            var cur = st[start+1];
1097
            st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
1098
          }
1099
        }
1100
      }, lineClasses);
1101
      context.state = state;
1102
      context.baseTokens = null;
1103
      context.baseTokenPos = 1;
1104
    };
1105
 
1106
    for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1107
 
1108
    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
1109
  }
1110
 
1111
  function getLineStyles(cm, line, updateFrontier) {
1112
    if (!line.styles || line.styles[0] != cm.state.modeGen) {
1113
      var context = getContextBefore(cm, lineNo(line));
1114
      var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
1115
      var result = highlightLine(cm, line, context);
1116
      if (resetState) { context.state = resetState; }
1117
      line.stateAfter = context.save(!resetState);
1118
      line.styles = result.styles;
1119
      if (result.classes) { line.styleClasses = result.classes; }
1120
      else if (line.styleClasses) { line.styleClasses = null; }
1121
      if (updateFrontier === cm.doc.highlightFrontier)
1122
        { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
1123
    }
1124
    return line.styles
1125
  }
1126
 
1127
  function getContextBefore(cm, n, precise) {
1128
    var doc = cm.doc, display = cm.display;
1129
    if (!doc.mode.startState) { return new Context(doc, true, n) }
1130
    var start = findStartLine(cm, n, precise);
1131
    var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
1132
    var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
1133
 
1134
    doc.iter(start, n, function (line) {
1135
      processLine(cm, line.text, context);
1136
      var pos = context.line;
1137
      line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
1138
      context.nextLine();
1139
    });
1140
    if (precise) { doc.modeFrontier = context.line; }
1141
    return context
1142
  }
1143
 
1144
  // Lightweight form of highlight -- proceed over this line and
1145
  // update state, but don't save a style array. Used for lines that
1146
  // aren't currently visible.
1147
  function processLine(cm, text, context, startAt) {
1148
    var mode = cm.doc.mode;
1149
    var stream = new StringStream(text, cm.options.tabSize, context);
1150
    stream.start = stream.pos = startAt || 0;
1151
    if (text == "") { callBlankLine(mode, context.state); }
1152
    while (!stream.eol()) {
1153
      readToken(mode, stream, context.state);
1154
      stream.start = stream.pos;
1155
    }
1156
  }
1157
 
1158
  function callBlankLine(mode, state) {
1159
    if (mode.blankLine) { return mode.blankLine(state) }
1160
    if (!mode.innerMode) { return }
1161
    var inner = innerMode(mode, state);
1162
    if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
1163
  }
1164
 
1165
  function readToken(mode, stream, state, inner) {
1166
    for (var i = 0; i < 10; i++) {
1167
      if (inner) { inner[0] = innerMode(mode, state).mode; }
1168
      var style = mode.token(stream, state);
1169
      if (stream.pos > stream.start) { return style }
1170
    }
1171
    throw new Error("Mode " + mode.name + " failed to advance stream.")
1172
  }
1173
 
1174
  var Token = function(stream, type, state) {
1175
    this.start = stream.start; this.end = stream.pos;
1176
    this.string = stream.current();
1177
    this.type = type || null;
1178
    this.state = state;
1179
  };
1180
 
1181
  // Utility for getTokenAt and getLineTokens
1182
  function takeToken(cm, pos, precise, asArray) {
1183
    var doc = cm.doc, mode = doc.mode, style;
1184
    pos = clipPos(doc, pos);
1185
    var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
1186
    var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
1187
    if (asArray) { tokens = []; }
1188
    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
1189
      stream.start = stream.pos;
1190
      style = readToken(mode, stream, context.state);
1191
      if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
1192
    }
1193
    return asArray ? tokens : new Token(stream, style, context.state)
1194
  }
1195
 
1196
  function extractLineClasses(type, output) {
1197
    if (type) { for (;;) {
1198
      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
1199
      if (!lineClass) { break }
1200
      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
1201
      var prop = lineClass[1] ? "bgClass" : "textClass";
1202
      if (output[prop] == null)
1203
        { output[prop] = lineClass[2]; }
15152 obado 1204
      else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
14283 obado 1205
        { output[prop] += " " + lineClass[2]; }
1206
    } }
1207
    return type
1208
  }
1209
 
1210
  // Run the given mode's parser over a line, calling f for each token.
1211
  function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
1212
    var flattenSpans = mode.flattenSpans;
1213
    if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
1214
    var curStart = 0, curStyle = null;
1215
    var stream = new StringStream(text, cm.options.tabSize, context), style;
1216
    var inner = cm.options.addModeClass && [null];
1217
    if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
1218
    while (!stream.eol()) {
1219
      if (stream.pos > cm.options.maxHighlightLength) {
1220
        flattenSpans = false;
1221
        if (forceToEnd) { processLine(cm, text, context, stream.pos); }
1222
        stream.pos = text.length;
1223
        style = null;
1224
      } else {
1225
        style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
1226
      }
1227
      if (inner) {
1228
        var mName = inner[0].name;
1229
        if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
1230
      }
1231
      if (!flattenSpans || curStyle != style) {
1232
        while (curStart < stream.start) {
1233
          curStart = Math.min(stream.start, curStart + 5000);
1234
          f(curStart, curStyle);
1235
        }
1236
        curStyle = style;
1237
      }
1238
      stream.start = stream.pos;
1239
    }
1240
    while (curStart < stream.pos) {
1241
      // Webkit seems to refuse to render text nodes longer than 57444
1242
      // characters, and returns inaccurate measurements in nodes
1243
      // starting around 5000 chars.
1244
      var pos = Math.min(stream.pos, curStart + 5000);
1245
      f(pos, curStyle);
1246
      curStart = pos;
1247
    }
1248
  }
1249
 
1250
  // Finds the line to start with when starting a parse. Tries to
1251
  // find a line with a stateAfter, so that it can start with a
1252
  // valid state. If that fails, it returns the line with the
1253
  // smallest indentation, which tends to need the least context to
1254
  // parse correctly.
1255
  function findStartLine(cm, n, precise) {
1256
    var minindent, minline, doc = cm.doc;
1257
    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1258
    for (var search = n; search > lim; --search) {
1259
      if (search <= doc.first) { return doc.first }
1260
      var line = getLine(doc, search - 1), after = line.stateAfter;
1261
      if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
1262
        { return search }
1263
      var indented = countColumn(line.text, null, cm.options.tabSize);
1264
      if (minline == null || minindent > indented) {
1265
        minline = search - 1;
1266
        minindent = indented;
1267
      }
1268
    }
1269
    return minline
1270
  }
1271
 
1272
  function retreatFrontier(doc, n) {
1273
    doc.modeFrontier = Math.min(doc.modeFrontier, n);
1274
    if (doc.highlightFrontier < n - 10) { return }
1275
    var start = doc.first;
1276
    for (var line = n - 1; line > start; line--) {
1277
      var saved = getLine(doc, line).stateAfter;
1278
      // change is on 3
1279
      // state on line 1 looked ahead 2 -- so saw 3
1280
      // test 1 + 2 < 3 should cover this
1281
      if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
1282
        start = line + 1;
1283
        break
1284
      }
1285
    }
1286
    doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1287
  }
1288
 
1289
  // Optimize some code when these features are not used.
1290
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
1291
 
1292
  function seeReadOnlySpans() {
1293
    sawReadOnlySpans = true;
1294
  }
1295
 
1296
  function seeCollapsedSpans() {
1297
    sawCollapsedSpans = true;
1298
  }
1299
 
1300
  // TEXTMARKER SPANS
1301
 
1302
  function MarkedSpan(marker, from, to) {
1303
    this.marker = marker;
1304
    this.from = from; this.to = to;
1305
  }
1306
 
1307
  // Search an array of spans for a span matching the given marker.
1308
  function getMarkedSpanFor(spans, marker) {
1309
    if (spans) { for (var i = 0; i < spans.length; ++i) {
1310
      var span = spans[i];
1311
      if (span.marker == marker) { return span }
1312
    } }
1313
  }
16493 obado 1314
 
14283 obado 1315
  // Remove a span from an array, returning undefined if no spans are
1316
  // left (we don't store arrays for lines without spans).
1317
  function removeMarkedSpan(spans, span) {
1318
    var r;
1319
    for (var i = 0; i < spans.length; ++i)
1320
      { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
1321
    return r
1322
  }
16493 obado 1323
 
14283 obado 1324
  // Add a span to a line.
16493 obado 1325
  function addMarkedSpan(line, span, op) {
1326
    var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
1327
    if (inThisOp && inThisOp.has(line.markedSpans)) {
1328
      line.markedSpans.push(span);
1329
    } else {
1330
      line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
1331
      if (inThisOp) { inThisOp.add(line.markedSpans); }
1332
    }
14283 obado 1333
    span.marker.attachLine(line);
1334
  }
1335
 
1336
  // Used for the algorithm that adjusts markers for a change in the
1337
  // document. These functions cut an array of spans at a given
1338
  // character position, returning an array of remaining chunks (or
1339
  // undefined if nothing remains).
1340
  function markedSpansBefore(old, startCh, isInsert) {
1341
    var nw;
1342
    if (old) { for (var i = 0; i < old.length; ++i) {
1343
      var span = old[i], marker = span.marker;
1344
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
1345
      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
1346
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
1347
        ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
1348
      }
1349
    } }
1350
    return nw
1351
  }
1352
  function markedSpansAfter(old, endCh, isInsert) {
1353
    var nw;
1354
    if (old) { for (var i = 0; i < old.length; ++i) {
1355
      var span = old[i], marker = span.marker;
1356
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
1357
      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
1358
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
1359
        ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
1360
                                              span.to == null ? null : span.to - endCh));
1361
      }
1362
    } }
1363
    return nw
1364
  }
1365
 
1366
  // Given a change object, compute the new set of marker spans that
1367
  // cover the line in which the change took place. Removes spans
1368
  // entirely within the change, reconnects spans belonging to the
1369
  // same marker that appear on both sides of the change, and cuts off
1370
  // spans partially within the change. Returns an array of span
1371
  // arrays with one element for each line in (after) the change.
1372
  function stretchSpansOverChange(doc, change) {
1373
    if (change.full) { return null }
1374
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
1375
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
1376
    if (!oldFirst && !oldLast) { return null }
1377
 
1378
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
1379
    // Get the spans that 'stick out' on both sides
1380
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
1381
    var last = markedSpansAfter(oldLast, endCh, isInsert);
1382
 
1383
    // Next, merge those two ends
1384
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
1385
    if (first) {
1386
      // Fix up .to properties of first
1387
      for (var i = 0; i < first.length; ++i) {
1388
        var span = first[i];
1389
        if (span.to == null) {
1390
          var found = getMarkedSpanFor(last, span.marker);
1391
          if (!found) { span.to = startCh; }
1392
          else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
1393
        }
1394
      }
1395
    }
1396
    if (last) {
1397
      // Fix up .from in last (or move them into first in case of sameLine)
1398
      for (var i$1 = 0; i$1 < last.length; ++i$1) {
1399
        var span$1 = last[i$1];
1400
        if (span$1.to != null) { span$1.to += offset; }
1401
        if (span$1.from == null) {
1402
          var found$1 = getMarkedSpanFor(first, span$1.marker);
1403
          if (!found$1) {
1404
            span$1.from = offset;
1405
            if (sameLine) { (first || (first = [])).push(span$1); }
1406
          }
1407
        } else {
1408
          span$1.from += offset;
1409
          if (sameLine) { (first || (first = [])).push(span$1); }
1410
        }
1411
      }
1412
    }
1413
    // Make sure we didn't create any zero-length spans
1414
    if (first) { first = clearEmptySpans(first); }
1415
    if (last && last != first) { last = clearEmptySpans(last); }
1416
 
1417
    var newMarkers = [first];
1418
    if (!sameLine) {
1419
      // Fill gap with whole-line-spans
1420
      var gap = change.text.length - 2, gapMarkers;
1421
      if (gap > 0 && first)
1422
        { for (var i$2 = 0; i$2 < first.length; ++i$2)
1423
          { if (first[i$2].to == null)
1424
            { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
1425
      for (var i$3 = 0; i$3 < gap; ++i$3)
1426
        { newMarkers.push(gapMarkers); }
1427
      newMarkers.push(last);
1428
    }
1429
    return newMarkers
1430
  }
1431
 
1432
  // Remove spans that are empty and don't have a clearWhenEmpty
1433
  // option of false.
1434
  function clearEmptySpans(spans) {
1435
    for (var i = 0; i < spans.length; ++i) {
1436
      var span = spans[i];
1437
      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
1438
        { spans.splice(i--, 1); }
1439
    }
1440
    if (!spans.length) { return null }
1441
    return spans
1442
  }
1443
 
1444
  // Used to 'clip' out readOnly ranges when making a change.
1445
  function removeReadOnlyRanges(doc, from, to) {
1446
    var markers = null;
1447
    doc.iter(from.line, to.line + 1, function (line) {
1448
      if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
1449
        var mark = line.markedSpans[i].marker;
1450
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
1451
          { (markers || (markers = [])).push(mark); }
1452
      } }
1453
    });
1454
    if (!markers) { return null }
1455
    var parts = [{from: from, to: to}];
1456
    for (var i = 0; i < markers.length; ++i) {
1457
      var mk = markers[i], m = mk.find(0);
1458
      for (var j = 0; j < parts.length; ++j) {
1459
        var p = parts[j];
1460
        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
1461
        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
1462
        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
1463
          { newParts.push({from: p.from, to: m.from}); }
1464
        if (dto > 0 || !mk.inclusiveRight && !dto)
1465
          { newParts.push({from: m.to, to: p.to}); }
1466
        parts.splice.apply(parts, newParts);
1467
        j += newParts.length - 3;
1468
      }
1469
    }
1470
    return parts
1471
  }
1472
 
1473
  // Connect or disconnect spans from a line.
1474
  function detachMarkedSpans(line) {
1475
    var spans = line.markedSpans;
1476
    if (!spans) { return }
1477
    for (var i = 0; i < spans.length; ++i)
1478
      { spans[i].marker.detachLine(line); }
1479
    line.markedSpans = null;
1480
  }
1481
  function attachMarkedSpans(line, spans) {
1482
    if (!spans) { return }
1483
    for (var i = 0; i < spans.length; ++i)
1484
      { spans[i].marker.attachLine(line); }
1485
    line.markedSpans = spans;
1486
  }
1487
 
1488
  // Helpers used when computing which overlapping collapsed span
1489
  // counts as the larger one.
1490
  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
1491
  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
1492
 
1493
  // Returns a number indicating which of two overlapping collapsed
1494
  // spans is larger (and thus includes the other). Falls back to
1495
  // comparing ids when the spans cover exactly the same range.
1496
  function compareCollapsedMarkers(a, b) {
1497
    var lenDiff = a.lines.length - b.lines.length;
1498
    if (lenDiff != 0) { return lenDiff }
1499
    var aPos = a.find(), bPos = b.find();
1500
    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
1501
    if (fromCmp) { return -fromCmp }
1502
    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
1503
    if (toCmp) { return toCmp }
1504
    return b.id - a.id
1505
  }
1506
 
1507
  // Find out whether a line ends or starts in a collapsed span. If
1508
  // so, return the marker for that span.
1509
  function collapsedSpanAtSide(line, start) {
1510
    var sps = sawCollapsedSpans && line.markedSpans, found;
1511
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1512
      sp = sps[i];
1513
      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
1514
          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
1515
        { found = sp.marker; }
1516
    } }
1517
    return found
1518
  }
1519
  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
1520
  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
1521
 
1522
  function collapsedSpanAround(line, ch) {
1523
    var sps = sawCollapsedSpans && line.markedSpans, found;
1524
    if (sps) { for (var i = 0; i < sps.length; ++i) {
1525
      var sp = sps[i];
1526
      if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
1527
          (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
1528
    } }
1529
    return found
1530
  }
1531
 
1532
  // Test whether there exists a collapsed span that partially
1533
  // overlaps (covers the start or end, but not both) of a new span.
1534
  // Such overlap is not allowed.
15152 obado 1535
  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
1536
    var line = getLine(doc, lineNo);
14283 obado 1537
    var sps = sawCollapsedSpans && line.markedSpans;
1538
    if (sps) { for (var i = 0; i < sps.length; ++i) {
1539
      var sp = sps[i];
1540
      if (!sp.marker.collapsed) { continue }
1541
      var found = sp.marker.find(0);
1542
      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
1543
      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
1544
      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
1545
      if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
1546
          fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
1547
        { return true }
1548
    } }
1549
  }
1550
 
1551
  // A visual line is a line as drawn on the screen. Folding, for
1552
  // example, can cause multiple logical lines to appear on the same
1553
  // visual line. This finds the start of the visual line that the
1554
  // given line is part of (usually that is the line itself).
1555
  function visualLine(line) {
1556
    var merged;
1557
    while (merged = collapsedSpanAtStart(line))
1558
      { line = merged.find(-1, true).line; }
1559
    return line
1560
  }
1561
 
1562
  function visualLineEnd(line) {
1563
    var merged;
1564
    while (merged = collapsedSpanAtEnd(line))
1565
      { line = merged.find(1, true).line; }
1566
    return line
1567
  }
1568
 
1569
  // Returns an array of logical lines that continue the visual line
1570
  // started by the argument, or undefined if there are no such lines.
1571
  function visualLineContinued(line) {
1572
    var merged, lines;
1573
    while (merged = collapsedSpanAtEnd(line)) {
1574
      line = merged.find(1, true).line
1575
      ;(lines || (lines = [])).push(line);
1576
    }
1577
    return lines
1578
  }
1579
 
1580
  // Get the line number of the start of the visual line that the
1581
  // given line number is part of.
1582
  function visualLineNo(doc, lineN) {
1583
    var line = getLine(doc, lineN), vis = visualLine(line);
1584
    if (line == vis) { return lineN }
1585
    return lineNo(vis)
1586
  }
1587
 
1588
  // Get the line number of the start of the next visual line after
1589
  // the given line.
1590
  function visualLineEndNo(doc, lineN) {
1591
    if (lineN > doc.lastLine()) { return lineN }
1592
    var line = getLine(doc, lineN), merged;
1593
    if (!lineIsHidden(doc, line)) { return lineN }
1594
    while (merged = collapsedSpanAtEnd(line))
1595
      { line = merged.find(1, true).line; }
1596
    return lineNo(line) + 1
1597
  }
1598
 
1599
  // Compute whether a line is hidden. Lines count as hidden when they
1600
  // are part of a visual line that starts with another line, or when
1601
  // they are entirely covered by collapsed, non-widget span.
1602
  function lineIsHidden(doc, line) {
1603
    var sps = sawCollapsedSpans && line.markedSpans;
1604
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1605
      sp = sps[i];
1606
      if (!sp.marker.collapsed) { continue }
1607
      if (sp.from == null) { return true }
1608
      if (sp.marker.widgetNode) { continue }
1609
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
1610
        { return true }
1611
    } }
1612
  }
1613
  function lineIsHiddenInner(doc, line, span) {
1614
    if (span.to == null) {
1615
      var end = span.marker.find(1, true);
1616
      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
1617
    }
1618
    if (span.marker.inclusiveRight && span.to == line.text.length)
1619
      { return true }
1620
    for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
1621
      sp = line.markedSpans[i];
1622
      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
1623
          (sp.to == null || sp.to != span.from) &&
1624
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
1625
          lineIsHiddenInner(doc, line, sp)) { return true }
1626
    }
1627
  }
1628
 
1629
  // Find the height above the given line.
1630
  function heightAtLine(lineObj) {
1631
    lineObj = visualLine(lineObj);
1632
 
1633
    var h = 0, chunk = lineObj.parent;
1634
    for (var i = 0; i < chunk.lines.length; ++i) {
1635
      var line = chunk.lines[i];
1636
      if (line == lineObj) { break }
1637
      else { h += line.height; }
1638
    }
1639
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
1640
      for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
1641
        var cur = p.children[i$1];
1642
        if (cur == chunk) { break }
1643
        else { h += cur.height; }
1644
      }
1645
    }
1646
    return h
1647
  }
1648
 
1649
  // Compute the character length of a line, taking into account
1650
  // collapsed ranges (see markText) that might hide parts, and join
1651
  // other lines onto it.
1652
  function lineLength(line) {
1653
    if (line.height == 0) { return 0 }
1654
    var len = line.text.length, merged, cur = line;
1655
    while (merged = collapsedSpanAtStart(cur)) {
1656
      var found = merged.find(0, true);
1657
      cur = found.from.line;
1658
      len += found.from.ch - found.to.ch;
1659
    }
1660
    cur = line;
1661
    while (merged = collapsedSpanAtEnd(cur)) {
1662
      var found$1 = merged.find(0, true);
1663
      len -= cur.text.length - found$1.from.ch;
1664
      cur = found$1.to.line;
1665
      len += cur.text.length - found$1.to.ch;
1666
    }
1667
    return len
1668
  }
1669
 
1670
  // Find the longest line in the document.
1671
  function findMaxLine(cm) {
1672
    var d = cm.display, doc = cm.doc;
1673
    d.maxLine = getLine(doc, doc.first);
1674
    d.maxLineLength = lineLength(d.maxLine);
1675
    d.maxLineChanged = true;
1676
    doc.iter(function (line) {
1677
      var len = lineLength(line);
1678
      if (len > d.maxLineLength) {
1679
        d.maxLineLength = len;
1680
        d.maxLine = line;
1681
      }
1682
    });
1683
  }
1684
 
1685
  // LINE DATA STRUCTURE
1686
 
1687
  // Line objects. These hold state related to a line, including
1688
  // highlighting info (the styles array).
1689
  var Line = function(text, markedSpans, estimateHeight) {
1690
    this.text = text;
1691
    attachMarkedSpans(this, markedSpans);
1692
    this.height = estimateHeight ? estimateHeight(this) : 1;
1693
  };
1694
 
1695
  Line.prototype.lineNo = function () { return lineNo(this) };
1696
  eventMixin(Line);
1697
 
1698
  // Change the content (text, markers) of a line. Automatically
1699
  // invalidates cached information and tries to re-estimate the
1700
  // line's height.
1701
  function updateLine(line, text, markedSpans, estimateHeight) {
1702
    line.text = text;
1703
    if (line.stateAfter) { line.stateAfter = null; }
1704
    if (line.styles) { line.styles = null; }
1705
    if (line.order != null) { line.order = null; }
1706
    detachMarkedSpans(line);
1707
    attachMarkedSpans(line, markedSpans);
1708
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
1709
    if (estHeight != line.height) { updateLineHeight(line, estHeight); }
1710
  }
1711
 
1712
  // Detach a line from the document tree and its markers.
1713
  function cleanUpLine(line) {
1714
    line.parent = null;
1715
    detachMarkedSpans(line);
1716
  }
1717
 
1718
  // Convert a style as returned by a mode (either null, or a string
1719
  // containing one or more styles) to a CSS style. This is cached,
1720
  // and also looks for line-wide styles.
1721
  var styleToClassCache = {}, styleToClassCacheWithMode = {};
1722
  function interpretTokenStyle(style, options) {
1723
    if (!style || /^\s*$/.test(style)) { return null }
1724
    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
1725
    return cache[style] ||
1726
      (cache[style] = style.replace(/\S+/g, "cm-$&"))
1727
  }
1728
 
1729
  // Render the DOM representation of the text of a line. Also builds
1730
  // up a 'line map', which points at the DOM nodes that represent
1731
  // specific stretches of text, and is used by the measuring code.
1732
  // The returned object contains the DOM node, this map, and
1733
  // information about line-wide styles that were set by the mode.
1734
  function buildLineContent(cm, lineView) {
1735
    // The padding-right forces the element to have a 'border', which
1736
    // is needed on Webkit to be able to get line-level bounding
1737
    // rectangles for it (in measureChar).
1738
    var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
1739
    var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
1740
                   col: 0, pos: 0, cm: cm,
1741
                   trailingSpace: false,
1742
                   splitSpaces: cm.getOption("lineWrapping")};
1743
    lineView.measure = {};
1744
 
1745
    // Iterate over the logical lines that make up this visual line.
1746
    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
1747
      var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
1748
      builder.pos = 0;
1749
      builder.addToken = buildToken;
1750
      // Optionally wire in some hacks into the token-rendering
1751
      // algorithm, to deal with browser quirks.
1752
      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
1753
        { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
1754
      builder.map = [];
1755
      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
1756
      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
1757
      if (line.styleClasses) {
1758
        if (line.styleClasses.bgClass)
1759
          { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
1760
        if (line.styleClasses.textClass)
1761
          { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
1762
      }
1763
 
1764
      // Ensure at least a single node is present, for measuring.
1765
      if (builder.map.length == 0)
1766
        { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
1767
 
1768
      // Store the map and a cache object for the current logical line
1769
      if (i == 0) {
1770
        lineView.measure.map = builder.map;
1771
        lineView.measure.cache = {};
1772
      } else {
1773
  (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
1774
        ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
1775
      }
1776
    }
1777
 
1778
    // See issue #2901
1779
    if (webkit) {
1780
      var last = builder.content.lastChild;
1781
      if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
1782
        { builder.content.className = "cm-tab-wrap-hack"; }
1783
    }
1784
 
1785
    signal(cm, "renderLine", cm, lineView.line, builder.pre);
1786
    if (builder.pre.className)
1787
      { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1788
 
1789
    return builder
1790
  }
1791
 
1792
  function defaultSpecialCharPlaceholder(ch) {
1793
    var token = elt("span", "\u2022", "cm-invalidchar");
1794
    token.title = "\\u" + ch.charCodeAt(0).toString(16);
1795
    token.setAttribute("aria-label", token.title);
1796
    return token
1797
  }
1798
 
1799
  // Build up the DOM representation for a single token, and add it to
1800
  // the line map. Takes care to render special characters separately.
1801
  function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
1802
    if (!text) { return }
1803
    var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
1804
    var special = builder.cm.state.specialChars, mustWrap = false;
1805
    var content;
1806
    if (!special.test(text)) {
1807
      builder.col += text.length;
1808
      content = document.createTextNode(displayText);
1809
      builder.map.push(builder.pos, builder.pos + text.length, content);
1810
      if (ie && ie_version < 9) { mustWrap = true; }
1811
      builder.pos += text.length;
1812
    } else {
1813
      content = document.createDocumentFragment();
1814
      var pos = 0;
1815
      while (true) {
1816
        special.lastIndex = pos;
1817
        var m = special.exec(text);
1818
        var skipped = m ? m.index - pos : text.length - pos;
1819
        if (skipped) {
1820
          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
1821
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
1822
          else { content.appendChild(txt); }
1823
          builder.map.push(builder.pos, builder.pos + skipped, txt);
1824
          builder.col += skipped;
1825
          builder.pos += skipped;
1826
        }
1827
        if (!m) { break }
1828
        pos += skipped + 1;
1829
        var txt$1 = (void 0);
1830
        if (m[0] == "\t") {
1831
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
1832
          txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
1833
          txt$1.setAttribute("role", "presentation");
1834
          txt$1.setAttribute("cm-text", "\t");
1835
          builder.col += tabWidth;
1836
        } else if (m[0] == "\r" || m[0] == "\n") {
1837
          txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
1838
          txt$1.setAttribute("cm-text", m[0]);
1839
          builder.col += 1;
1840
        } else {
1841
          txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
1842
          txt$1.setAttribute("cm-text", m[0]);
1843
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
1844
          else { content.appendChild(txt$1); }
1845
          builder.col += 1;
1846
        }
1847
        builder.map.push(builder.pos, builder.pos + 1, txt$1);
1848
        builder.pos++;
1849
      }
1850
    }
1851
    builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
16493 obado 1852
    if (style || startStyle || endStyle || mustWrap || css || attributes) {
14283 obado 1853
      var fullStyle = style || "";
1854
      if (startStyle) { fullStyle += startStyle; }
1855
      if (endStyle) { fullStyle += endStyle; }
1856
      var token = elt("span", [content], fullStyle, css);
1857
      if (attributes) {
1858
        for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
1859
          { token.setAttribute(attr, attributes[attr]); } }
1860
      }
1861
      return builder.content.appendChild(token)
1862
    }
1863
    builder.content.appendChild(content);
1864
  }
1865
 
1866
  // Change some spaces to NBSP to prevent the browser from collapsing
1867
  // trailing spaces at the end of a line when rendering text (issue #1362).
1868
  function splitSpaces(text, trailingBefore) {
1869
    if (text.length > 1 && !/  /.test(text)) { return text }
1870
    var spaceBefore = trailingBefore, result = "";
1871
    for (var i = 0; i < text.length; i++) {
1872
      var ch = text.charAt(i);
1873
      if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
1874
        { ch = "\u00a0"; }
1875
      result += ch;
1876
      spaceBefore = ch == " ";
1877
    }
1878
    return result
1879
  }
1880
 
1881
  // Work around nonsense dimensions being reported for stretches of
1882
  // right-to-left text.
1883
  function buildTokenBadBidi(inner, order) {
1884
    return function (builder, text, style, startStyle, endStyle, css, attributes) {
1885
      style = style ? style + " cm-force-border" : "cm-force-border";
1886
      var start = builder.pos, end = start + text.length;
1887
      for (;;) {
1888
        // Find the part that overlaps with the start of this text
1889
        var part = (void 0);
1890
        for (var i = 0; i < order.length; i++) {
1891
          part = order[i];
1892
          if (part.to > start && part.from <= start) { break }
1893
        }
1894
        if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
1895
        inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
1896
        startStyle = null;
1897
        text = text.slice(part.to - start);
1898
        start = part.to;
1899
      }
1900
    }
1901
  }
1902
 
1903
  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
1904
    var widget = !ignoreWidget && marker.widgetNode;
1905
    if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
1906
    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
1907
      if (!widget)
1908
        { widget = builder.content.appendChild(document.createElement("span")); }
1909
      widget.setAttribute("cm-marker", marker.id);
1910
    }
1911
    if (widget) {
1912
      builder.cm.display.input.setUneditable(widget);
1913
      builder.content.appendChild(widget);
1914
    }
1915
    builder.pos += size;
1916
    builder.trailingSpace = false;
1917
  }
1918
 
1919
  // Outputs a number of spans to make up a line, taking highlighting
1920
  // and marked text into account.
1921
  function insertLineContent(line, builder, styles) {
1922
    var spans = line.markedSpans, allText = line.text, at = 0;
1923
    if (!spans) {
1924
      for (var i$1 = 1; i$1 < styles.length; i$1+=2)
1925
        { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
1926
      return
1927
    }
1928
 
1929
    var len = allText.length, pos = 0, i = 1, text = "", style, css;
1930
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
1931
    for (;;) {
1932
      if (nextChange == pos) { // Update current marker set
1933
        spanStyle = spanEndStyle = spanStartStyle = css = "";
1934
        attributes = null;
1935
        collapsed = null; nextChange = Infinity;
1936
        var foundBookmarks = [], endStyles = (void 0);
1937
        for (var j = 0; j < spans.length; ++j) {
1938
          var sp = spans[j], m = sp.marker;
1939
          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
1940
            foundBookmarks.push(m);
1941
          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
1942
            if (sp.to != null && sp.to != pos && nextChange > sp.to) {
1943
              nextChange = sp.to;
1944
              spanEndStyle = "";
1945
            }
1946
            if (m.className) { spanStyle += " " + m.className; }
1947
            if (m.css) { css = (css ? css + ";" : "") + m.css; }
1948
            if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
1949
            if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
1950
            // support for the old title property
1951
            // https://github.com/codemirror/CodeMirror/pull/5673
1952
            if (m.title) { (attributes || (attributes = {})).title = m.title; }
1953
            if (m.attributes) {
1954
              for (var attr in m.attributes)
1955
                { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
1956
            }
1957
            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
1958
              { collapsed = sp; }
1959
          } else if (sp.from > pos && nextChange > sp.from) {
1960
            nextChange = sp.from;
1961
          }
1962
        }
1963
        if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
1964
          { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
1965
 
1966
        if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
1967
          { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
1968
        if (collapsed && (collapsed.from || 0) == pos) {
1969
          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
1970
                             collapsed.marker, collapsed.from == null);
1971
          if (collapsed.to == null) { return }
1972
          if (collapsed.to == pos) { collapsed = false; }
1973
        }
1974
      }
1975
      if (pos >= len) { break }
1976
 
1977
      var upto = Math.min(len, nextChange);
1978
      while (true) {
1979
        if (text) {
1980
          var end = pos + text.length;
1981
          if (!collapsed) {
1982
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
1983
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
1984
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
1985
          }
1986
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
1987
          pos = end;
1988
          spanStartStyle = "";
1989
        }
1990
        text = allText.slice(at, at = styles[i++]);
1991
        style = interpretTokenStyle(styles[i++], builder.cm.options);
1992
      }
1993
    }
1994
  }
1995
 
1996
 
1997
  // These objects are used to represent the visible (currently drawn)
1998
  // part of the document. A LineView may correspond to multiple
1999
  // logical lines, if those are connected by collapsed ranges.
2000
  function LineView(doc, line, lineN) {
2001
    // The starting line
2002
    this.line = line;
2003
    // Continuing lines, if any
2004
    this.rest = visualLineContinued(line);
2005
    // Number of logical lines in this visual line
2006
    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
2007
    this.node = this.text = null;
2008
    this.hidden = lineIsHidden(doc, line);
2009
  }
2010
 
2011
  // Create a range of LineView objects for the given lines.
2012
  function buildViewArray(cm, from, to) {
2013
    var array = [], nextPos;
2014
    for (var pos = from; pos < to; pos = nextPos) {
2015
      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2016
      nextPos = pos + view.size;
2017
      array.push(view);
2018
    }
2019
    return array
2020
  }
2021
 
2022
  var operationGroup = null;
2023
 
2024
  function pushOperation(op) {
2025
    if (operationGroup) {
2026
      operationGroup.ops.push(op);
2027
    } else {
2028
      op.ownsGroup = operationGroup = {
2029
        ops: [op],
2030
        delayedCallbacks: []
2031
      };
2032
    }
2033
  }
2034
 
2035
  function fireCallbacksForOps(group) {
2036
    // Calls delayed callbacks and cursorActivity handlers until no
2037
    // new ones appear
2038
    var callbacks = group.delayedCallbacks, i = 0;
2039
    do {
2040
      for (; i < callbacks.length; i++)
2041
        { callbacks[i].call(null); }
2042
      for (var j = 0; j < group.ops.length; j++) {
2043
        var op = group.ops[j];
2044
        if (op.cursorActivityHandlers)
2045
          { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2046
            { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
2047
      }
2048
    } while (i < callbacks.length)
2049
  }
2050
 
2051
  function finishOperation(op, endCb) {
2052
    var group = op.ownsGroup;
2053
    if (!group) { return }
2054
 
2055
    try { fireCallbacksForOps(group); }
2056
    finally {
2057
      operationGroup = null;
2058
      endCb(group);
2059
    }
2060
  }
2061
 
2062
  var orphanDelayedCallbacks = null;
2063
 
2064
  // Often, we want to signal events at a point where we are in the
2065
  // middle of some work, but don't want the handler to start calling
2066
  // other methods on the editor, which might be in an inconsistent
2067
  // state or simply not expect any other events to happen.
2068
  // signalLater looks whether there are any handlers, and schedules
2069
  // them to be executed when the last operation ends, or, if no
2070
  // operation is active, when a timeout fires.
2071
  function signalLater(emitter, type /*, values...*/) {
2072
    var arr = getHandlers(emitter, type);
2073
    if (!arr.length) { return }
2074
    var args = Array.prototype.slice.call(arguments, 2), list;
2075
    if (operationGroup) {
2076
      list = operationGroup.delayedCallbacks;
2077
    } else if (orphanDelayedCallbacks) {
2078
      list = orphanDelayedCallbacks;
2079
    } else {
2080
      list = orphanDelayedCallbacks = [];
2081
      setTimeout(fireOrphanDelayed, 0);
2082
    }
2083
    var loop = function ( i ) {
2084
      list.push(function () { return arr[i].apply(null, args); });
2085
    };
2086
 
2087
    for (var i = 0; i < arr.length; ++i)
2088
      loop( i );
2089
  }
2090
 
2091
  function fireOrphanDelayed() {
2092
    var delayed = orphanDelayedCallbacks;
2093
    orphanDelayedCallbacks = null;
2094
    for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
2095
  }
2096
 
2097
  // When an aspect of a line changes, a string is added to
2098
  // lineView.changes. This updates the relevant part of the line's
2099
  // DOM structure.
2100
  function updateLineForChanges(cm, lineView, lineN, dims) {
2101
    for (var j = 0; j < lineView.changes.length; j++) {
2102
      var type = lineView.changes[j];
2103
      if (type == "text") { updateLineText(cm, lineView); }
2104
      else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
2105
      else if (type == "class") { updateLineClasses(cm, lineView); }
2106
      else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
2107
    }
2108
    lineView.changes = null;
2109
  }
2110
 
2111
  // Lines with gutter elements, widgets or a background class need to
2112
  // be wrapped, and have the extra elements added to the wrapper div
2113
  function ensureLineWrapped(lineView) {
2114
    if (lineView.node == lineView.text) {
2115
      lineView.node = elt("div", null, null, "position: relative");
2116
      if (lineView.text.parentNode)
2117
        { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
2118
      lineView.node.appendChild(lineView.text);
2119
      if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
2120
    }
2121
    return lineView.node
2122
  }
2123
 
2124
  function updateLineBackground(cm, lineView) {
2125
    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
2126
    if (cls) { cls += " CodeMirror-linebackground"; }
2127
    if (lineView.background) {
2128
      if (cls) { lineView.background.className = cls; }
2129
      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
2130
    } else if (cls) {
2131
      var wrap = ensureLineWrapped(lineView);
2132
      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
2133
      cm.display.input.setUneditable(lineView.background);
2134
    }
2135
  }
2136
 
2137
  // Wrapper around buildLineContent which will reuse the structure
2138
  // in display.externalMeasured when possible.
2139
  function getLineContent(cm, lineView) {
2140
    var ext = cm.display.externalMeasured;
2141
    if (ext && ext.line == lineView.line) {
2142
      cm.display.externalMeasured = null;
2143
      lineView.measure = ext.measure;
2144
      return ext.built
2145
    }
2146
    return buildLineContent(cm, lineView)
2147
  }
2148
 
2149
  // Redraw the line's text. Interacts with the background and text
2150
  // classes because the mode may output tokens that influence these
2151
  // classes.
2152
  function updateLineText(cm, lineView) {
2153
    var cls = lineView.text.className;
2154
    var built = getLineContent(cm, lineView);
2155
    if (lineView.text == lineView.node) { lineView.node = built.pre; }
2156
    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
2157
    lineView.text = built.pre;
2158
    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
2159
      lineView.bgClass = built.bgClass;
2160
      lineView.textClass = built.textClass;
2161
      updateLineClasses(cm, lineView);
2162
    } else if (cls) {
2163
      lineView.text.className = cls;
2164
    }
2165
  }
2166
 
2167
  function updateLineClasses(cm, lineView) {
2168
    updateLineBackground(cm, lineView);
2169
    if (lineView.line.wrapClass)
2170
      { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
2171
    else if (lineView.node != lineView.text)
2172
      { lineView.node.className = ""; }
2173
    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
2174
    lineView.text.className = textClass || "";
2175
  }
2176
 
2177
  function updateLineGutter(cm, lineView, lineN, dims) {
2178
    if (lineView.gutter) {
2179
      lineView.node.removeChild(lineView.gutter);
2180
      lineView.gutter = null;
2181
    }
2182
    if (lineView.gutterBackground) {
2183
      lineView.node.removeChild(lineView.gutterBackground);
2184
      lineView.gutterBackground = null;
2185
    }
2186
    if (lineView.line.gutterClass) {
2187
      var wrap = ensureLineWrapped(lineView);
2188
      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
2189
                                      ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
2190
      cm.display.input.setUneditable(lineView.gutterBackground);
2191
      wrap.insertBefore(lineView.gutterBackground, lineView.text);
2192
    }
2193
    var markers = lineView.line.gutterMarkers;
2194
    if (cm.options.lineNumbers || markers) {
2195
      var wrap$1 = ensureLineWrapped(lineView);
2196
      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
16493 obado 2197
      gutterWrap.setAttribute("aria-hidden", "true");
14283 obado 2198
      cm.display.input.setUneditable(gutterWrap);
2199
      wrap$1.insertBefore(gutterWrap, lineView.text);
2200
      if (lineView.line.gutterClass)
2201
        { gutterWrap.className += " " + lineView.line.gutterClass; }
2202
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
2203
        { lineView.lineNumber = gutterWrap.appendChild(
2204
          elt("div", lineNumberFor(cm.options, lineN),
2205
              "CodeMirror-linenumber CodeMirror-gutter-elt",
2206
              ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
2207
      if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
2208
        var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
2209
        if (found)
2210
          { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
2211
                                     ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
2212
      } }
2213
    }
2214
  }
2215
 
2216
  function updateLineWidgets(cm, lineView, dims) {
2217
    if (lineView.alignable) { lineView.alignable = null; }
15152 obado 2218
    var isWidget = classTest("CodeMirror-linewidget");
14283 obado 2219
    for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
2220
      next = node.nextSibling;
15152 obado 2221
      if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
14283 obado 2222
    }
2223
    insertLineWidgets(cm, lineView, dims);
2224
  }
2225
 
2226
  // Build a line's DOM representation from scratch
2227
  function buildLineElement(cm, lineView, lineN, dims) {
2228
    var built = getLineContent(cm, lineView);
2229
    lineView.text = lineView.node = built.pre;
2230
    if (built.bgClass) { lineView.bgClass = built.bgClass; }
2231
    if (built.textClass) { lineView.textClass = built.textClass; }
2232
 
2233
    updateLineClasses(cm, lineView);
2234
    updateLineGutter(cm, lineView, lineN, dims);
2235
    insertLineWidgets(cm, lineView, dims);
2236
    return lineView.node
2237
  }
2238
 
2239
  // A lineView may contain multiple logical lines (when merged by
2240
  // collapsed spans). The widgets for all of them need to be drawn.
2241
  function insertLineWidgets(cm, lineView, dims) {
2242
    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
2243
    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2244
      { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
2245
  }
2246
 
2247
  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
2248
    if (!line.widgets) { return }
2249
    var wrap = ensureLineWrapped(lineView);
2250
    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
15152 obado 2251
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
14283 obado 2252
      if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
2253
      positionLineWidget(widget, node, lineView, dims);
2254
      cm.display.input.setUneditable(node);
2255
      if (allowAbove && widget.above)
2256
        { wrap.insertBefore(node, lineView.gutter || lineView.text); }
2257
      else
2258
        { wrap.appendChild(node); }
2259
      signalLater(widget, "redraw");
2260
    }
2261
  }
2262
 
2263
  function positionLineWidget(widget, node, lineView, dims) {
2264
    if (widget.noHScroll) {
2265
  (lineView.alignable || (lineView.alignable = [])).push(node);
2266
      var width = dims.wrapperWidth;
2267
      node.style.left = dims.fixedPos + "px";
2268
      if (!widget.coverGutter) {
2269
        width -= dims.gutterTotalWidth;
2270
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
2271
      }
2272
      node.style.width = width + "px";
2273
    }
2274
    if (widget.coverGutter) {
2275
      node.style.zIndex = 5;
2276
      node.style.position = "relative";
2277
      if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2278
    }
2279
  }
2280
 
2281
  function widgetHeight(widget) {
2282
    if (widget.height != null) { return widget.height }
2283
    var cm = widget.doc.cm;
2284
    if (!cm) { return 0 }
2285
    if (!contains(document.body, widget.node)) {
2286
      var parentStyle = "position: relative;";
2287
      if (widget.coverGutter)
2288
        { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
2289
      if (widget.noHScroll)
2290
        { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
2291
      removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
2292
    }
2293
    return widget.height = widget.node.parentNode.offsetHeight
2294
  }
2295
 
2296
  // Return true when the given mouse event happened in a widget
2297
  function eventInWidget(display, e) {
2298
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2299
      if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
2300
          (n.parentNode == display.sizer && n != display.mover))
2301
        { return true }
2302
    }
2303
  }
2304
 
2305
  // POSITION MEASUREMENT
2306
 
2307
  function paddingTop(display) {return display.lineSpace.offsetTop}
2308
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
2309
  function paddingH(display) {
2310
    if (display.cachedPaddingH) { return display.cachedPaddingH }
2311
    var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
2312
    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2313
    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2314
    if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
2315
    return data
2316
  }
2317
 
2318
  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
2319
  function displayWidth(cm) {
2320
    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
2321
  }
2322
  function displayHeight(cm) {
2323
    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
2324
  }
2325
 
2326
  // Ensure the lineView.wrapping.heights array is populated. This is
2327
  // an array of bottom offsets for the lines that make up a drawn
2328
  // line. When lineWrapping is on, there might be more than one
2329
  // height.
2330
  function ensureLineHeights(cm, lineView, rect) {
2331
    var wrapping = cm.options.lineWrapping;
2332
    var curWidth = wrapping && displayWidth(cm);
2333
    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2334
      var heights = lineView.measure.heights = [];
2335
      if (wrapping) {
2336
        lineView.measure.width = curWidth;
2337
        var rects = lineView.text.firstChild.getClientRects();
2338
        for (var i = 0; i < rects.length - 1; i++) {
2339
          var cur = rects[i], next = rects[i + 1];
2340
          if (Math.abs(cur.bottom - next.bottom) > 2)
2341
            { heights.push((cur.bottom + next.top) / 2 - rect.top); }
2342
        }
2343
      }
2344
      heights.push(rect.bottom - rect.top);
2345
    }
2346
  }
2347
 
2348
  // Find a line map (mapping character offsets to text nodes) and a
2349
  // measurement cache for the given line number. (A line view might
2350
  // contain multiple lines when collapsed ranges are present.)
2351
  function mapFromLineView(lineView, line, lineN) {
2352
    if (lineView.line == line)
2353
      { return {map: lineView.measure.map, cache: lineView.measure.cache} }
16493 obado 2354
    if (lineView.rest) {
2355
      for (var i = 0; i < lineView.rest.length; i++)
2356
        { if (lineView.rest[i] == line)
2357
          { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
2358
      for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
2359
        { if (lineNo(lineView.rest[i$1]) > lineN)
2360
          { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
2361
    }
14283 obado 2362
  }
2363
 
2364
  // Render a line into the hidden node display.externalMeasured. Used
2365
  // when measurement is needed for a line that's not in the viewport.
2366
  function updateExternalMeasurement(cm, line) {
2367
    line = visualLine(line);
2368
    var lineN = lineNo(line);
2369
    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2370
    view.lineN = lineN;
2371
    var built = view.built = buildLineContent(cm, view);
2372
    view.text = built.pre;
2373
    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2374
    return view
2375
  }
2376
 
2377
  // Get a {top, bottom, left, right} box (in line-local coordinates)
2378
  // for a given character.
2379
  function measureChar(cm, line, ch, bias) {
2380
    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
2381
  }
2382
 
2383
  // Find a line view that corresponds to the given line number.
2384
  function findViewForLine(cm, lineN) {
2385
    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2386
      { return cm.display.view[findViewIndex(cm, lineN)] }
2387
    var ext = cm.display.externalMeasured;
2388
    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2389
      { return ext }
2390
  }
2391
 
2392
  // Measurement can be split in two steps, the set-up work that
2393
  // applies to the whole line, and the measurement of the actual
2394
  // character. Functions like coordsChar, that need to do a lot of
2395
  // measurements in a row, can thus ensure that the set-up work is
2396
  // only done once.
2397
  function prepareMeasureForLine(cm, line) {
2398
    var lineN = lineNo(line);
2399
    var view = findViewForLine(cm, lineN);
2400
    if (view && !view.text) {
2401
      view = null;
2402
    } else if (view && view.changes) {
2403
      updateLineForChanges(cm, view, lineN, getDimensions(cm));
2404
      cm.curOp.forceUpdate = true;
2405
    }
2406
    if (!view)
2407
      { view = updateExternalMeasurement(cm, line); }
2408
 
2409
    var info = mapFromLineView(view, line, lineN);
2410
    return {
2411
      line: line, view: view, rect: null,
2412
      map: info.map, cache: info.cache, before: info.before,
2413
      hasHeights: false
2414
    }
2415
  }
2416
 
2417
  // Given a prepared measurement object, measures the position of an
2418
  // actual character (or fetches it from the cache).
2419
  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2420
    if (prepared.before) { ch = -1; }
2421
    var key = ch + (bias || ""), found;
2422
    if (prepared.cache.hasOwnProperty(key)) {
2423
      found = prepared.cache[key];
2424
    } else {
2425
      if (!prepared.rect)
2426
        { prepared.rect = prepared.view.text.getBoundingClientRect(); }
2427
      if (!prepared.hasHeights) {
2428
        ensureLineHeights(cm, prepared.view, prepared.rect);
2429
        prepared.hasHeights = true;
2430
      }
2431
      found = measureCharInner(cm, prepared, ch, bias);
2432
      if (!found.bogus) { prepared.cache[key] = found; }
2433
    }
2434
    return {left: found.left, right: found.right,
2435
            top: varHeight ? found.rtop : found.top,
2436
            bottom: varHeight ? found.rbottom : found.bottom}
2437
  }
2438
 
2439
  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2440
 
15152 obado 2441
  function nodeAndOffsetInLineMap(map, ch, bias) {
14283 obado 2442
    var node, start, end, collapse, mStart, mEnd;
2443
    // First, search the line map for the text node corresponding to,
2444
    // or closest to, the target character.
15152 obado 2445
    for (var i = 0; i < map.length; i += 3) {
2446
      mStart = map[i];
2447
      mEnd = map[i + 1];
14283 obado 2448
      if (ch < mStart) {
2449
        start = 0; end = 1;
2450
        collapse = "left";
2451
      } else if (ch < mEnd) {
2452
        start = ch - mStart;
2453
        end = start + 1;
15152 obado 2454
      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
14283 obado 2455
        end = mEnd - mStart;
2456
        start = end - 1;
2457
        if (ch >= mEnd) { collapse = "right"; }
2458
      }
2459
      if (start != null) {
15152 obado 2460
        node = map[i + 2];
14283 obado 2461
        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2462
          { collapse = bias; }
2463
        if (bias == "left" && start == 0)
15152 obado 2464
          { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2465
            node = map[(i -= 3) + 2];
14283 obado 2466
            collapse = "left";
2467
          } }
2468
        if (bias == "right" && start == mEnd - mStart)
15152 obado 2469
          { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2470
            node = map[(i += 3) + 2];
14283 obado 2471
            collapse = "right";
2472
          } }
2473
        break
2474
      }
2475
    }
2476
    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
2477
  }
2478
 
2479
  function getUsefulRect(rects, bias) {
2480
    var rect = nullRect;
2481
    if (bias == "left") { for (var i = 0; i < rects.length; i++) {
2482
      if ((rect = rects[i]).left != rect.right) { break }
2483
    } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
2484
      if ((rect = rects[i$1]).left != rect.right) { break }
2485
    } }
2486
    return rect
2487
  }
2488
 
2489
  function measureCharInner(cm, prepared, ch, bias) {
2490
    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2491
    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2492
 
2493
    var rect;
2494
    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2495
      for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2496
        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
2497
        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
2498
        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2499
          { rect = node.parentNode.getBoundingClientRect(); }
2500
        else
2501
          { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
2502
        if (rect.left || rect.right || start == 0) { break }
2503
        end = start;
2504
        start = start - 1;
2505
        collapse = "right";
2506
      }
2507
      if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
2508
    } else { // If it is a widget, simply get the box for the whole widget.
2509
      if (start > 0) { collapse = bias = "right"; }
2510
      var rects;
2511
      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2512
        { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
2513
      else
2514
        { rect = node.getBoundingClientRect(); }
2515
    }
2516
    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2517
      var rSpan = node.parentNode.getClientRects()[0];
2518
      if (rSpan)
2519
        { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
2520
      else
2521
        { rect = nullRect; }
2522
    }
2523
 
2524
    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2525
    var mid = (rtop + rbot) / 2;
2526
    var heights = prepared.view.measure.heights;
2527
    var i = 0;
2528
    for (; i < heights.length - 1; i++)
2529
      { if (mid < heights[i]) { break } }
2530
    var top = i ? heights[i - 1] : 0, bot = heights[i];
2531
    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2532
                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2533
                  top: top, bottom: bot};
2534
    if (!rect.left && !rect.right) { result.bogus = true; }
2535
    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2536
 
2537
    return result
2538
  }
2539
 
2540
  // Work around problem with bounding client rects on ranges being
2541
  // returned incorrectly when zoomed on IE10 and below.
2542
  function maybeUpdateRectForZooming(measure, rect) {
2543
    if (!window.screen || screen.logicalXDPI == null ||
2544
        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2545
      { return rect }
2546
    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2547
    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2548
    return {left: rect.left * scaleX, right: rect.right * scaleX,
2549
            top: rect.top * scaleY, bottom: rect.bottom * scaleY}
2550
  }
2551
 
2552
  function clearLineMeasurementCacheFor(lineView) {
2553
    if (lineView.measure) {
2554
      lineView.measure.cache = {};
2555
      lineView.measure.heights = null;
2556
      if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2557
        { lineView.measure.caches[i] = {}; } }
2558
    }
2559
  }
2560
 
2561
  function clearLineMeasurementCache(cm) {
2562
    cm.display.externalMeasure = null;
2563
    removeChildren(cm.display.lineMeasure);
2564
    for (var i = 0; i < cm.display.view.length; i++)
2565
      { clearLineMeasurementCacheFor(cm.display.view[i]); }
2566
  }
2567
 
2568
  function clearCaches(cm) {
2569
    clearLineMeasurementCache(cm);
2570
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2571
    if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
2572
    cm.display.lineNumChars = null;
2573
  }
2574
 
2575
  function pageScrollX() {
2576
    // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
2577
    // which causes page_Offset and bounding client rects to use
2578
    // different reference viewports and invalidate our calculations.
2579
    if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
2580
    return window.pageXOffset || (document.documentElement || document.body).scrollLeft
2581
  }
2582
  function pageScrollY() {
2583
    if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
2584
    return window.pageYOffset || (document.documentElement || document.body).scrollTop
2585
  }
2586
 
2587
  function widgetTopHeight(lineObj) {
16493 obado 2588
    var ref = visualLine(lineObj);
2589
    var widgets = ref.widgets;
14283 obado 2590
    var height = 0;
16493 obado 2591
    if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
2592
      { height += widgetHeight(widgets[i]); } } }
14283 obado 2593
    return height
2594
  }
2595
 
2596
  // Converts a {top, bottom, left, right} box from line-local
2597
  // coordinates into another coordinate system. Context may be one of
2598
  // "line", "div" (display.lineDiv), "local"./null (editor), "window",
2599
  // or "page".
2600
  function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
2601
    if (!includeWidgets) {
2602
      var height = widgetTopHeight(lineObj);
2603
      rect.top += height; rect.bottom += height;
2604
    }
2605
    if (context == "line") { return rect }
2606
    if (!context) { context = "local"; }
2607
    var yOff = heightAtLine(lineObj);
2608
    if (context == "local") { yOff += paddingTop(cm.display); }
2609
    else { yOff -= cm.display.viewOffset; }
2610
    if (context == "page" || context == "window") {
2611
      var lOff = cm.display.lineSpace.getBoundingClientRect();
2612
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2613
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2614
      rect.left += xOff; rect.right += xOff;
2615
    }
2616
    rect.top += yOff; rect.bottom += yOff;
2617
    return rect
2618
  }
2619
 
2620
  // Coverts a box from "div" coords to another coordinate system.
2621
  // Context may be "window", "page", "div", or "local"./null.
2622
  function fromCoordSystem(cm, coords, context) {
2623
    if (context == "div") { return coords }
2624
    var left = coords.left, top = coords.top;
2625
    // First move into "page" coordinate system
2626
    if (context == "page") {
2627
      left -= pageScrollX();
2628
      top -= pageScrollY();
2629
    } else if (context == "local" || !context) {
2630
      var localBox = cm.display.sizer.getBoundingClientRect();
2631
      left += localBox.left;
2632
      top += localBox.top;
2633
    }
2634
 
2635
    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2636
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
2637
  }
2638
 
2639
  function charCoords(cm, pos, context, lineObj, bias) {
2640
    if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
2641
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
2642
  }
2643
 
2644
  // Returns a box for a given cursor position, which may have an
2645
  // 'other' property containing the position of the secondary cursor
2646
  // on a bidi boundary.
2647
  // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
2648
  // and after `char - 1` in writing order of `char - 1`
2649
  // A cursor Pos(line, char, "after") is on the same visual line as `char`
2650
  // and before `char` in writing order of `char`
2651
  // Examples (upper-case letters are RTL, lower-case are LTR):
2652
  //     Pos(0, 1, ...)
2653
  //     before   after
2654
  // ab     a|b     a|b
2655
  // aB     a|B     aB|
2656
  // Ab     |Ab     A|b
2657
  // AB     B|A     B|A
2658
  // Every position after the last character on a line is considered to stick
2659
  // to the last character on the line.
2660
  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2661
    lineObj = lineObj || getLine(cm.doc, pos.line);
2662
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2663
    function get(ch, right) {
2664
      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2665
      if (right) { m.left = m.right; } else { m.right = m.left; }
2666
      return intoCoordSystem(cm, lineObj, m, context)
2667
    }
2668
    var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
2669
    if (ch >= lineObj.text.length) {
2670
      ch = lineObj.text.length;
2671
      sticky = "before";
2672
    } else if (ch <= 0) {
2673
      ch = 0;
2674
      sticky = "after";
2675
    }
2676
    if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
2677
 
2678
    function getBidi(ch, partPos, invert) {
2679
      var part = order[partPos], right = part.level == 1;
2680
      return get(invert ? ch - 1 : ch, right != invert)
2681
    }
2682
    var partPos = getBidiPartAt(order, ch, sticky);
2683
    var other = bidiOther;
2684
    var val = getBidi(ch, partPos, sticky == "before");
2685
    if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
2686
    return val
2687
  }
2688
 
2689
  // Used to cheaply estimate the coordinates for a position. Used for
2690
  // intermediate scroll updates.
2691
  function estimateCoords(cm, pos) {
2692
    var left = 0;
2693
    pos = clipPos(cm.doc, pos);
2694
    if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
2695
    var lineObj = getLine(cm.doc, pos.line);
2696
    var top = heightAtLine(lineObj) + paddingTop(cm.display);
2697
    return {left: left, right: left, top: top, bottom: top + lineObj.height}
2698
  }
2699
 
2700
  // Positions returned by coordsChar contain some extra information.
2701
  // xRel is the relative x position of the input coordinates compared
2702
  // to the found position (so xRel > 0 means the coordinates are to
2703
  // the right of the character position, for example). When outside
2704
  // is true, that means the coordinates lie outside the line's
2705
  // vertical range.
2706
  function PosWithInfo(line, ch, sticky, outside, xRel) {
2707
    var pos = Pos(line, ch, sticky);
2708
    pos.xRel = xRel;
2709
    if (outside) { pos.outside = outside; }
2710
    return pos
2711
  }
2712
 
2713
  // Compute the character position closest to the given coordinates.
2714
  // Input must be lineSpace-local ("div" coordinate system).
2715
  function coordsChar(cm, x, y) {
2716
    var doc = cm.doc;
2717
    y += cm.display.viewOffset;
2718
    if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
2719
    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2720
    if (lineN > last)
2721
      { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
2722
    if (x < 0) { x = 0; }
2723
 
2724
    var lineObj = getLine(doc, lineN);
2725
    for (;;) {
2726
      var found = coordsCharInner(cm, lineObj, lineN, x, y);
2727
      var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
2728
      if (!collapsed) { return found }
2729
      var rangeEnd = collapsed.find(1);
2730
      if (rangeEnd.line == lineN) { return rangeEnd }
2731
      lineObj = getLine(doc, lineN = rangeEnd.line);
2732
    }
2733
  }
2734
 
2735
  function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
2736
    y -= widgetTopHeight(lineObj);
2737
    var end = lineObj.text.length;
2738
    var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
2739
    end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
2740
    return {begin: begin, end: end}
2741
  }
2742
 
2743
  function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
2744
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2745
    var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
2746
    return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
2747
  }
2748
 
2749
  // Returns true if the given side of a box is after the given
2750
  // coordinates, in top-to-bottom, left-to-right order.
2751
  function boxIsAfter(box, x, y, left) {
2752
    return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
2753
  }
2754
 
15152 obado 2755
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
14283 obado 2756
    // Move y into line-local coordinate space
2757
    y -= heightAtLine(lineObj);
2758
    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2759
    // When directly calling `measureCharPrepared`, we have to adjust
2760
    // for the widgets at this line.
15152 obado 2761
    var widgetHeight = widgetTopHeight(lineObj);
14283 obado 2762
    var begin = 0, end = lineObj.text.length, ltr = true;
2763
 
2764
    var order = getOrder(lineObj, cm.doc.direction);
2765
    // If the line isn't plain left-to-right text, first figure out
2766
    // which bidi section the coordinates fall into.
2767
    if (order) {
2768
      var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
15152 obado 2769
                   (cm, lineObj, lineNo, preparedMeasure, order, x, y);
14283 obado 2770
      ltr = part.level != 1;
2771
      // The awkward -1 offsets are needed because findFirst (called
2772
      // on these below) will treat its first bound as inclusive,
2773
      // second as exclusive, but we want to actually address the
2774
      // characters in the part's range
2775
      begin = ltr ? part.from : part.to - 1;
2776
      end = ltr ? part.to : part.from - 1;
2777
    }
2778
 
2779
    // A binary search to find the first character whose bounding box
2780
    // starts after the coordinates. If we run across any whose box wrap
2781
    // the coordinates, store that.
2782
    var chAround = null, boxAround = null;
2783
    var ch = findFirst(function (ch) {
2784
      var box = measureCharPrepared(cm, preparedMeasure, ch);
15152 obado 2785
      box.top += widgetHeight; box.bottom += widgetHeight;
14283 obado 2786
      if (!boxIsAfter(box, x, y, false)) { return false }
2787
      if (box.top <= y && box.left <= x) {
2788
        chAround = ch;
2789
        boxAround = box;
2790
      }
2791
      return true
2792
    }, begin, end);
2793
 
2794
    var baseX, sticky, outside = false;
2795
    // If a box around the coordinates was found, use that
2796
    if (boxAround) {
2797
      // Distinguish coordinates nearer to the left or right side of the box
2798
      var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
2799
      ch = chAround + (atStart ? 0 : 1);
2800
      sticky = atStart ? "after" : "before";
2801
      baseX = atLeft ? boxAround.left : boxAround.right;
2802
    } else {
2803
      // (Adjust for extended bound, if necessary.)
2804
      if (!ltr && (ch == end || ch == begin)) { ch++; }
2805
      // To determine which side to associate with, get the box to the
2806
      // left of the character and compare it's vertical position to the
2807
      // coordinates
2808
      sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
15152 obado 2809
        (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
14283 obado 2810
        "after" : "before";
2811
      // Now get accurate coordinates for this place, in order to get a
2812
      // base X position
15152 obado 2813
      var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
14283 obado 2814
      baseX = coords.left;
2815
      outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
2816
    }
2817
 
2818
    ch = skipExtendingChars(lineObj.text, ch, 1);
15152 obado 2819
    return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
14283 obado 2820
  }
2821
 
15152 obado 2822
  function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
14283 obado 2823
    // Bidi parts are sorted left-to-right, and in a non-line-wrapping
2824
    // situation, we can take this ordering to correspond to the visual
2825
    // ordering. This finds the first part whose end is after the given
2826
    // coordinates.
2827
    var index = findFirst(function (i) {
2828
      var part = order[i], ltr = part.level != 1;
15152 obado 2829
      return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
14283 obado 2830
                                     "line", lineObj, preparedMeasure), x, y, true)
2831
    }, 0, order.length - 1);
2832
    var part = order[index];
2833
    // If this isn't the first part, the part's start is also after
2834
    // the coordinates, and the coordinates aren't on the same line as
2835
    // that start, move one part back.
2836
    if (index > 0) {
2837
      var ltr = part.level != 1;
15152 obado 2838
      var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
14283 obado 2839
                               "line", lineObj, preparedMeasure);
2840
      if (boxIsAfter(start, x, y, true) && start.top > y)
2841
        { part = order[index - 1]; }
2842
    }
2843
    return part
2844
  }
2845
 
2846
  function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
2847
    // In a wrapped line, rtl text on wrapping boundaries can do things
2848
    // that don't correspond to the ordering in our `order` array at
2849
    // all, so a binary search doesn't work, and we want to return a
2850
    // part that only spans one line so that the binary search in
2851
    // coordsCharInner is safe. As such, we first find the extent of the
2852
    // wrapped line, and then do a flat search in which we discard any
2853
    // spans that aren't on the line.
2854
    var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
2855
    var begin = ref.begin;
2856
    var end = ref.end;
2857
    if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
2858
    var part = null, closestDist = null;
2859
    for (var i = 0; i < order.length; i++) {
2860
      var p = order[i];
2861
      if (p.from >= end || p.to <= begin) { continue }
2862
      var ltr = p.level != 1;
2863
      var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
2864
      // Weigh against spans ending before this, so that they are only
2865
      // picked if nothing ends after
2866
      var dist = endX < x ? x - endX + 1e9 : endX - x;
2867
      if (!part || closestDist > dist) {
2868
        part = p;
2869
        closestDist = dist;
2870
      }
2871
    }
2872
    if (!part) { part = order[order.length - 1]; }
2873
    // Clip the part to the wrapped line.
2874
    if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
2875
    if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
2876
    return part
2877
  }
2878
 
2879
  var measureText;
2880
  // Compute the default text height.
2881
  function textHeight(display) {
2882
    if (display.cachedTextHeight != null) { return display.cachedTextHeight }
2883
    if (measureText == null) {
2884
      measureText = elt("pre", null, "CodeMirror-line-like");
2885
      // Measure a bunch of lines, for browsers that compute
2886
      // fractional heights.
2887
      for (var i = 0; i < 49; ++i) {
2888
        measureText.appendChild(document.createTextNode("x"));
2889
        measureText.appendChild(elt("br"));
2890
      }
2891
      measureText.appendChild(document.createTextNode("x"));
2892
    }
2893
    removeChildrenAndAdd(display.measure, measureText);
2894
    var height = measureText.offsetHeight / 50;
2895
    if (height > 3) { display.cachedTextHeight = height; }
2896
    removeChildren(display.measure);
2897
    return height || 1
2898
  }
2899
 
2900
  // Compute the default character width.
2901
  function charWidth(display) {
2902
    if (display.cachedCharWidth != null) { return display.cachedCharWidth }
2903
    var anchor = elt("span", "xxxxxxxxxx");
2904
    var pre = elt("pre", [anchor], "CodeMirror-line-like");
2905
    removeChildrenAndAdd(display.measure, pre);
2906
    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2907
    if (width > 2) { display.cachedCharWidth = width; }
2908
    return width || 10
2909
  }
2910
 
2911
  // Do a bulk-read of the DOM positions and sizes needed to draw the
2912
  // view, so that we don't interleave reading and writing to the DOM.
2913
  function getDimensions(cm) {
2914
    var d = cm.display, left = {}, width = {};
2915
    var gutterLeft = d.gutters.clientLeft;
2916
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
2917
      var id = cm.display.gutterSpecs[i].className;
2918
      left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
2919
      width[id] = n.clientWidth;
2920
    }
2921
    return {fixedPos: compensateForHScroll(d),
2922
            gutterTotalWidth: d.gutters.offsetWidth,
2923
            gutterLeft: left,
2924
            gutterWidth: width,
2925
            wrapperWidth: d.wrapper.clientWidth}
2926
  }
2927
 
2928
  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
2929
  // but using getBoundingClientRect to get a sub-pixel-accurate
2930
  // result.
2931
  function compensateForHScroll(display) {
2932
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
2933
  }
2934
 
2935
  // Returns a function that estimates the height of a line, to use as
2936
  // first approximation until the line becomes visible (and is thus
2937
  // properly measurable).
2938
  function estimateHeight(cm) {
2939
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
2940
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
2941
    return function (line) {
2942
      if (lineIsHidden(cm.doc, line)) { return 0 }
2943
 
2944
      var widgetsHeight = 0;
2945
      if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
2946
        if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
2947
      } }
2948
 
2949
      if (wrapping)
2950
        { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
2951
      else
2952
        { return widgetsHeight + th }
2953
    }
2954
  }
2955
 
2956
  function estimateLineHeights(cm) {
2957
    var doc = cm.doc, est = estimateHeight(cm);
2958
    doc.iter(function (line) {
2959
      var estHeight = est(line);
2960
      if (estHeight != line.height) { updateLineHeight(line, estHeight); }
2961
    });
2962
  }
2963
 
2964
  // Given a mouse event, find the corresponding position. If liberal
2965
  // is false, it checks whether a gutter or scrollbar was clicked,
2966
  // and returns null if it was. forRect is used by rectangular
2967
  // selections, and tries to estimate a character position even for
2968
  // coordinates beyond the right of the text.
2969
  function posFromMouse(cm, e, liberal, forRect) {
2970
    var display = cm.display;
2971
    if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
2972
 
2973
    var x, y, space = display.lineSpace.getBoundingClientRect();
2974
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
2975
    try { x = e.clientX - space.left; y = e.clientY - space.top; }
15332 obado 2976
    catch (e$1) { return null }
14283 obado 2977
    var coords = coordsChar(cm, x, y), line;
15152 obado 2978
    if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
14283 obado 2979
      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
2980
      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
2981
    }
2982
    return coords
2983
  }
2984
 
2985
  // Find the view element corresponding to a given line. Return null
2986
  // when the line isn't visible.
2987
  function findViewIndex(cm, n) {
2988
    if (n >= cm.display.viewTo) { return null }
2989
    n -= cm.display.viewFrom;
2990
    if (n < 0) { return null }
2991
    var view = cm.display.view;
2992
    for (var i = 0; i < view.length; i++) {
2993
      n -= view[i].size;
2994
      if (n < 0) { return i }
2995
    }
2996
  }
2997
 
2998
  // Updates the display.view data structure for a given change to the
2999
  // document. From and to are in pre-change coordinates. Lendiff is
3000
  // the amount of lines added or subtracted by the change. This is
3001
  // used for changes that span multiple lines, or change the way
3002
  // lines are divided into visual lines. regLineChange (below)
3003
  // registers single-line changes.
3004
  function regChange(cm, from, to, lendiff) {
3005
    if (from == null) { from = cm.doc.first; }
3006
    if (to == null) { to = cm.doc.first + cm.doc.size; }
3007
    if (!lendiff) { lendiff = 0; }
3008
 
3009
    var display = cm.display;
3010
    if (lendiff && to < display.viewTo &&
3011
        (display.updateLineNumbers == null || display.updateLineNumbers > from))
3012
      { display.updateLineNumbers = from; }
3013
 
3014
    cm.curOp.viewChanged = true;
3015
 
3016
    if (from >= display.viewTo) { // Change after
3017
      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3018
        { resetView(cm); }
3019
    } else if (to <= display.viewFrom) { // Change before
3020
      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3021
        resetView(cm);
3022
      } else {
3023
        display.viewFrom += lendiff;
3024
        display.viewTo += lendiff;
3025
      }
3026
    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3027
      resetView(cm);
3028
    } else if (from <= display.viewFrom) { // Top overlap
3029
      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3030
      if (cut) {
3031
        display.view = display.view.slice(cut.index);
3032
        display.viewFrom = cut.lineN;
3033
        display.viewTo += lendiff;
3034
      } else {
3035
        resetView(cm);
3036
      }
3037
    } else if (to >= display.viewTo) { // Bottom overlap
3038
      var cut$1 = viewCuttingPoint(cm, from, from, -1);
3039
      if (cut$1) {
3040
        display.view = display.view.slice(0, cut$1.index);
3041
        display.viewTo = cut$1.lineN;
3042
      } else {
3043
        resetView(cm);
3044
      }
3045
    } else { // Gap in the middle
3046
      var cutTop = viewCuttingPoint(cm, from, from, -1);
3047
      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3048
      if (cutTop && cutBot) {
3049
        display.view = display.view.slice(0, cutTop.index)
3050
          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3051
          .concat(display.view.slice(cutBot.index));
3052
        display.viewTo += lendiff;
3053
      } else {
3054
        resetView(cm);
3055
      }
3056
    }
3057
 
3058
    var ext = display.externalMeasured;
3059
    if (ext) {
3060
      if (to < ext.lineN)
3061
        { ext.lineN += lendiff; }
3062
      else if (from < ext.lineN + ext.size)
3063
        { display.externalMeasured = null; }
3064
    }
3065
  }
3066
 
3067
  // Register a change to a single line. Type must be one of "text",
3068
  // "gutter", "class", "widget"
3069
  function regLineChange(cm, line, type) {
3070
    cm.curOp.viewChanged = true;
3071
    var display = cm.display, ext = cm.display.externalMeasured;
3072
    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3073
      { display.externalMeasured = null; }
3074
 
3075
    if (line < display.viewFrom || line >= display.viewTo) { return }
3076
    var lineView = display.view[findViewIndex(cm, line)];
3077
    if (lineView.node == null) { return }
3078
    var arr = lineView.changes || (lineView.changes = []);
3079
    if (indexOf(arr, type) == -1) { arr.push(type); }
3080
  }
3081
 
3082
  // Clear the view.
3083
  function resetView(cm) {
3084
    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3085
    cm.display.view = [];
3086
    cm.display.viewOffset = 0;
3087
  }
3088
 
3089
  function viewCuttingPoint(cm, oldN, newN, dir) {
3090
    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3091
    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3092
      { return {index: index, lineN: newN} }
3093
    var n = cm.display.viewFrom;
3094
    for (var i = 0; i < index; i++)
3095
      { n += view[i].size; }
3096
    if (n != oldN) {
3097
      if (dir > 0) {
3098
        if (index == view.length - 1) { return null }
3099
        diff = (n + view[index].size) - oldN;
3100
        index++;
3101
      } else {
3102
        diff = n - oldN;
3103
      }
3104
      oldN += diff; newN += diff;
3105
    }
3106
    while (visualLineNo(cm.doc, newN) != newN) {
3107
      if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
3108
      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3109
      index += dir;
3110
    }
3111
    return {index: index, lineN: newN}
3112
  }
3113
 
3114
  // Force the view to cover a given range, adding empty view element
3115
  // or clipping off existing ones as needed.
3116
  function adjustView(cm, from, to) {
3117
    var display = cm.display, view = display.view;
3118
    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3119
      display.view = buildViewArray(cm, from, to);
3120
      display.viewFrom = from;
3121
    } else {
3122
      if (display.viewFrom > from)
3123
        { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
3124
      else if (display.viewFrom < from)
3125
        { display.view = display.view.slice(findViewIndex(cm, from)); }
3126
      display.viewFrom = from;
3127
      if (display.viewTo < to)
3128
        { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
3129
      else if (display.viewTo > to)
3130
        { display.view = display.view.slice(0, findViewIndex(cm, to)); }
3131
    }
3132
    display.viewTo = to;
3133
  }
3134
 
3135
  // Count the number of lines in the view whose DOM representation is
3136
  // out of date (or nonexistent).
3137
  function countDirtyView(cm) {
3138
    var view = cm.display.view, dirty = 0;
3139
    for (var i = 0; i < view.length; i++) {
3140
      var lineView = view[i];
3141
      if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
3142
    }
3143
    return dirty
3144
  }
3145
 
3146
  function updateSelection(cm) {
3147
    cm.display.input.showSelection(cm.display.input.prepareSelection());
3148
  }
3149
 
3150
  function prepareSelection(cm, primary) {
3151
    if ( primary === void 0 ) primary = true;
3152
 
3153
    var doc = cm.doc, result = {};
3154
    var curFragment = result.cursors = document.createDocumentFragment();
3155
    var selFragment = result.selection = document.createDocumentFragment();
3156
 
16493 obado 3157
    var customCursor = cm.options.$customCursor;
3158
    if (customCursor) { primary = true; }
14283 obado 3159
    for (var i = 0; i < doc.sel.ranges.length; i++) {
3160
      if (!primary && i == doc.sel.primIndex) { continue }
15152 obado 3161
      var range = doc.sel.ranges[i];
3162
      if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
3163
      var collapsed = range.empty();
16493 obado 3164
      if (customCursor) {
3165
        var head = customCursor(cm, range);
3166
        if (head) { drawSelectionCursor(cm, head, curFragment); }
3167
      } else if (collapsed || cm.options.showCursorWhenSelecting) {
3168
        drawSelectionCursor(cm, range.head, curFragment);
3169
      }
14283 obado 3170
      if (!collapsed)
15152 obado 3171
        { drawSelectionRange(cm, range, selFragment); }
14283 obado 3172
    }
3173
    return result
3174
  }
3175
 
3176
  // Draws a cursor for the given range
3177
  function drawSelectionCursor(cm, head, output) {
3178
    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
3179
 
3180
    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
3181
    cursor.style.left = pos.left + "px";
3182
    cursor.style.top = pos.top + "px";
3183
    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
3184
 
16493 obado 3185
    if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
3186
      var charPos = charCoords(cm, head, "div", null, null);
3187
      var width = charPos.right - charPos.left;
3188
      cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
3189
    }
3190
 
14283 obado 3191
    if (pos.other) {
3192
      // Secondary cursor, shown when on a 'jump' in bi-directional text
3193
      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
3194
      otherCursor.style.display = "";
3195
      otherCursor.style.left = pos.other.left + "px";
3196
      otherCursor.style.top = pos.other.top + "px";
3197
      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
3198
    }
3199
  }
3200
 
3201
  function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3202
 
3203
  // Draws the given range as a highlighted selection
15152 obado 3204
  function drawSelectionRange(cm, range, output) {
14283 obado 3205
    var display = cm.display, doc = cm.doc;
3206
    var fragment = document.createDocumentFragment();
3207
    var padding = paddingH(cm.display), leftSide = padding.left;
3208
    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
3209
    var docLTR = doc.direction == "ltr";
3210
 
3211
    function add(left, top, width, bottom) {
3212
      if (top < 0) { top = 0; }
3213
      top = Math.round(top);
3214
      bottom = Math.round(bottom);
3215
      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")));
3216
    }
3217
 
3218
    function drawForLine(line, fromArg, toArg) {
3219
      var lineObj = getLine(doc, line);
3220
      var lineLen = lineObj.text.length;
3221
      var start, end;
3222
      function coords(ch, bias) {
3223
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
3224
      }
3225
 
3226
      function wrapX(pos, dir, side) {
3227
        var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
3228
        var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
3229
        var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
3230
        return coords(ch, prop)[prop]
3231
      }
3232
 
3233
      var order = getOrder(lineObj, doc.direction);
3234
      iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
3235
        var ltr = dir == "ltr";
3236
        var fromPos = coords(from, ltr ? "left" : "right");
3237
        var toPos = coords(to - 1, ltr ? "right" : "left");
3238
 
3239
        var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
3240
        var first = i == 0, last = !order || i == order.length - 1;
3241
        if (toPos.top - fromPos.top <= 3) { // Single line
3242
          var openLeft = (docLTR ? openStart : openEnd) && first;
3243
          var openRight = (docLTR ? openEnd : openStart) && last;
3244
          var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
3245
          var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
3246
          add(left, fromPos.top, right - left, fromPos.bottom);
3247
        } else { // Multiple lines
3248
          var topLeft, topRight, botLeft, botRight;
3249
          if (ltr) {
3250
            topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
3251
            topRight = docLTR ? rightSide : wrapX(from, dir, "before");
3252
            botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
3253
            botRight = docLTR && openEnd && last ? rightSide : toPos.right;
3254
          } else {
3255
            topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
3256
            topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
3257
            botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
3258
            botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
3259
          }
3260
          add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
3261
          if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
3262
          add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
3263
        }
3264
 
3265
        if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
3266
        if (cmpCoords(toPos, start) < 0) { start = toPos; }
3267
        if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
3268
        if (cmpCoords(toPos, end) < 0) { end = toPos; }
3269
      });
3270
      return {start: start, end: end}
3271
    }
3272
 
15152 obado 3273
    var sFrom = range.from(), sTo = range.to();
14283 obado 3274
    if (sFrom.line == sTo.line) {
3275
      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
3276
    } else {
3277
      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3278
      var singleVLine = visualLine(fromLine) == visualLine(toLine);
3279
      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
3280
      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
3281
      if (singleVLine) {
3282
        if (leftEnd.top < rightStart.top - 2) {
3283
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
3284
          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
3285
        } else {
3286
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
3287
        }
3288
      }
3289
      if (leftEnd.bottom < rightStart.top)
3290
        { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3291
    }
3292
 
3293
    output.appendChild(fragment);
3294
  }
3295
 
3296
  // Cursor-blinking
3297
  function restartBlink(cm) {
3298
    if (!cm.state.focused) { return }
3299
    var display = cm.display;
3300
    clearInterval(display.blinker);
3301
    var on = true;
3302
    display.cursorDiv.style.visibility = "";
3303
    if (cm.options.cursorBlinkRate > 0)
16493 obado 3304
      { display.blinker = setInterval(function () {
3305
        if (!cm.hasFocus()) { onBlur(cm); }
3306
        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
3307
      }, cm.options.cursorBlinkRate); }
14283 obado 3308
    else if (cm.options.cursorBlinkRate < 0)
3309
      { display.cursorDiv.style.visibility = "hidden"; }
3310
  }
3311
 
3312
  function ensureFocus(cm) {
16493 obado 3313
    if (!cm.hasFocus()) {
3314
      cm.display.input.focus();
3315
      if (!cm.state.focused) { onFocus(cm); }
3316
    }
14283 obado 3317
  }
3318
 
3319
  function delayBlurEvent(cm) {
3320
    cm.state.delayingBlurEvent = true;
3321
    setTimeout(function () { if (cm.state.delayingBlurEvent) {
3322
      cm.state.delayingBlurEvent = false;
16493 obado 3323
      if (cm.state.focused) { onBlur(cm); }
14283 obado 3324
    } }, 100);
3325
  }
3326
 
3327
  function onFocus(cm, e) {
16493 obado 3328
    if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
14283 obado 3329
 
3330
    if (cm.options.readOnly == "nocursor") { return }
3331
    if (!cm.state.focused) {
3332
      signal(cm, "focus", cm, e);
3333
      cm.state.focused = true;
3334
      addClass(cm.display.wrapper, "CodeMirror-focused");
3335
      // This test prevents this from firing when a context
3336
      // menu is closed (since the input reset would kill the
3337
      // select-all detection hack)
3338
      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3339
        cm.display.input.reset();
3340
        if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
3341
      }
3342
      cm.display.input.receivedFocus();
3343
    }
3344
    restartBlink(cm);
3345
  }
3346
  function onBlur(cm, e) {
3347
    if (cm.state.delayingBlurEvent) { return }
3348
 
3349
    if (cm.state.focused) {
3350
      signal(cm, "blur", cm, e);
3351
      cm.state.focused = false;
3352
      rmClass(cm.display.wrapper, "CodeMirror-focused");
3353
    }
3354
    clearInterval(cm.display.blinker);
3355
    setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3356
  }
3357
 
3358
  // Read the actual heights of the rendered lines, and update their
3359
  // stored heights to match.
3360
  function updateHeightsInViewport(cm) {
3361
    var display = cm.display;
3362
    var prevBottom = display.lineDiv.offsetTop;
16493 obado 3363
    var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
3364
    var oldHeight = display.lineDiv.getBoundingClientRect().top;
3365
    var mustScroll = 0;
14283 obado 3366
    for (var i = 0; i < display.view.length; i++) {
3367
      var cur = display.view[i], wrapping = cm.options.lineWrapping;
3368
      var height = (void 0), width = 0;
3369
      if (cur.hidden) { continue }
16493 obado 3370
      oldHeight += cur.line.height;
14283 obado 3371
      if (ie && ie_version < 8) {
3372
        var bot = cur.node.offsetTop + cur.node.offsetHeight;
3373
        height = bot - prevBottom;
3374
        prevBottom = bot;
3375
      } else {
3376
        var box = cur.node.getBoundingClientRect();
3377
        height = box.bottom - box.top;
3378
        // Check that lines don't extend past the right of the current
3379
        // editor width
3380
        if (!wrapping && cur.text.firstChild)
3381
          { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
3382
      }
3383
      var diff = cur.line.height - height;
3384
      if (diff > .005 || diff < -.005) {
16493 obado 3385
        if (oldHeight < viewTop) { mustScroll -= diff; }
14283 obado 3386
        updateLineHeight(cur.line, height);
3387
        updateWidgetHeight(cur.line);
3388
        if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
3389
          { updateWidgetHeight(cur.rest[j]); } }
3390
      }
3391
      if (width > cm.display.sizerWidth) {
3392
        var chWidth = Math.ceil(width / charWidth(cm.display));
3393
        if (chWidth > cm.display.maxLineLength) {
3394
          cm.display.maxLineLength = chWidth;
3395
          cm.display.maxLine = cur.line;
3396
          cm.display.maxLineChanged = true;
3397
        }
3398
      }
3399
    }
16493 obado 3400
    if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
14283 obado 3401
  }
3402
 
3403
  // Read and store the height of line widgets associated with the
3404
  // given line.
3405
  function updateWidgetHeight(line) {
3406
    if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
3407
      var w = line.widgets[i], parent = w.node.parentNode;
3408
      if (parent) { w.height = parent.offsetHeight; }
3409
    } }
3410
  }
3411
 
3412
  // Compute the lines that are visible in a given viewport (defaults
3413
  // the the current scroll position). viewport may contain top,
3414
  // height, and ensure (see op.scrollToPos) properties.
3415
  function visibleLines(display, doc, viewport) {
3416
    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
3417
    top = Math.floor(top - paddingTop(display));
3418
    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
3419
 
3420
    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
3421
    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
3422
    // forces those lines into the viewport (if possible).
3423
    if (viewport && viewport.ensure) {
3424
      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
3425
      if (ensureFrom < from) {
3426
        from = ensureFrom;
3427
        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
3428
      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
3429
        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
3430
        to = ensureTo;
3431
      }
3432
    }
3433
    return {from: from, to: Math.max(to, from + 1)}
3434
  }
3435
 
3436
  // SCROLLING THINGS INTO VIEW
3437
 
3438
  // If an editor sits on the top or bottom of the window, partially
3439
  // scrolled out of view, this ensures that the cursor is visible.
3440
  function maybeScrollWindow(cm, rect) {
3441
    if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
3442
 
3443
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
3444
    if (rect.top + box.top < 0) { doScroll = true; }
3445
    else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
3446
    if (doScroll != null && !phantom) {
3447
      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;"));
3448
      cm.display.lineSpace.appendChild(scrollNode);
3449
      scrollNode.scrollIntoView(doScroll);
3450
      cm.display.lineSpace.removeChild(scrollNode);
3451
    }
3452
  }
3453
 
3454
  // Scroll a given position into view (immediately), verifying that
3455
  // it actually became visible (as line heights are accurately
3456
  // measured, the position of something may 'drift' during drawing).
3457
  function scrollPosIntoView(cm, pos, end, margin) {
3458
    if (margin == null) { margin = 0; }
3459
    var rect;
3460
    if (!cm.options.lineWrapping && pos == end) {
3461
      // Set pos and end to the cursor positions around the character pos sticks to
3462
      // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
3463
      // If pos == Pos(_, 0, "before"), pos and end are unchanged
16493 obado 3464
      end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
14283 obado 3465
      pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
3466
    }
3467
    for (var limit = 0; limit < 5; limit++) {
3468
      var changed = false;
3469
      var coords = cursorCoords(cm, pos);
3470
      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3471
      rect = {left: Math.min(coords.left, endCoords.left),
3472
              top: Math.min(coords.top, endCoords.top) - margin,
3473
              right: Math.max(coords.left, endCoords.left),
3474
              bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
3475
      var scrollPos = calculateScrollPos(cm, rect);
3476
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3477
      if (scrollPos.scrollTop != null) {
3478
        updateScrollTop(cm, scrollPos.scrollTop);
3479
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
3480
      }
3481
      if (scrollPos.scrollLeft != null) {
3482
        setScrollLeft(cm, scrollPos.scrollLeft);
3483
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3484
      }
3485
      if (!changed) { break }
3486
    }
3487
    return rect
3488
  }
3489
 
3490
  // Scroll a given set of coordinates into view (immediately).
3491
  function scrollIntoView(cm, rect) {
3492
    var scrollPos = calculateScrollPos(cm, rect);
3493
    if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
3494
    if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
3495
  }
3496
 
3497
  // Calculate a new scroll position needed to scroll the given
3498
  // rectangle into view. Returns an object with scrollTop and
3499
  // scrollLeft properties. When these are undefined, the
3500
  // vertical/horizontal position does not need to be adjusted.
3501
  function calculateScrollPos(cm, rect) {
3502
    var display = cm.display, snapMargin = textHeight(cm.display);
3503
    if (rect.top < 0) { rect.top = 0; }
3504
    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3505
    var screen = displayHeight(cm), result = {};
3506
    if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
3507
    var docBottom = cm.doc.height + paddingVert(display);
3508
    var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
3509
    if (rect.top < screentop) {
3510
      result.scrollTop = atTop ? 0 : rect.top;
3511
    } else if (rect.bottom > screentop + screen) {
3512
      var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
3513
      if (newTop != screentop) { result.scrollTop = newTop; }
3514
    }
3515
 
16493 obado 3516
    var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
3517
    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
3518
    var screenw = displayWidth(cm) - display.gutters.offsetWidth;
14283 obado 3519
    var tooWide = rect.right - rect.left > screenw;
3520
    if (tooWide) { rect.right = rect.left + screenw; }
3521
    if (rect.left < 10)
3522
      { result.scrollLeft = 0; }
3523
    else if (rect.left < screenleft)
16493 obado 3524
      { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
14283 obado 3525
    else if (rect.right > screenw + screenleft - 3)
3526
      { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
3527
    return result
3528
  }
3529
 
3530
  // Store a relative adjustment to the scroll position in the current
3531
  // operation (to be applied when the operation finishes).
3532
  function addToScrollTop(cm, top) {
3533
    if (top == null) { return }
3534
    resolveScrollToPos(cm);
3535
    cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3536
  }
3537
 
3538
  // Make sure that at the end of the operation the current cursor is
3539
  // shown.
3540
  function ensureCursorVisible(cm) {
3541
    resolveScrollToPos(cm);
3542
    var cur = cm.getCursor();
3543
    cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
3544
  }
3545
 
3546
  function scrollToCoords(cm, x, y) {
3547
    if (x != null || y != null) { resolveScrollToPos(cm); }
3548
    if (x != null) { cm.curOp.scrollLeft = x; }
3549
    if (y != null) { cm.curOp.scrollTop = y; }
3550
  }
3551
 
15152 obado 3552
  function scrollToRange(cm, range) {
14283 obado 3553
    resolveScrollToPos(cm);
15152 obado 3554
    cm.curOp.scrollToPos = range;
14283 obado 3555
  }
3556
 
3557
  // When an operation has its scrollToPos property set, and another
3558
  // scroll action is applied before the end of the operation, this
3559
  // 'simulates' scrolling that position into view in a cheap way, so
3560
  // that the effect of intermediate scroll commands is not ignored.
3561
  function resolveScrollToPos(cm) {
15152 obado 3562
    var range = cm.curOp.scrollToPos;
3563
    if (range) {
14283 obado 3564
      cm.curOp.scrollToPos = null;
15152 obado 3565
      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
3566
      scrollToCoordsRange(cm, from, to, range.margin);
14283 obado 3567
    }
3568
  }
3569
 
3570
  function scrollToCoordsRange(cm, from, to, margin) {
3571
    var sPos = calculateScrollPos(cm, {
3572
      left: Math.min(from.left, to.left),
3573
      top: Math.min(from.top, to.top) - margin,
3574
      right: Math.max(from.right, to.right),
3575
      bottom: Math.max(from.bottom, to.bottom) + margin
3576
    });
3577
    scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
3578
  }
3579
 
3580
  // Sync the scrollable area and scrollbars, ensure the viewport
3581
  // covers the visible area.
3582
  function updateScrollTop(cm, val) {
3583
    if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
3584
    if (!gecko) { updateDisplaySimple(cm, {top: val}); }
3585
    setScrollTop(cm, val, true);
3586
    if (gecko) { updateDisplaySimple(cm); }
3587
    startWorker(cm, 100);
3588
  }
3589
 
3590
  function setScrollTop(cm, val, forceScroll) {
15152 obado 3591
    val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
14283 obado 3592
    if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
3593
    cm.doc.scrollTop = val;
3594
    cm.display.scrollbars.setScrollTop(val);
3595
    if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
3596
  }
3597
 
3598
  // Sync scroller and scrollbar, ensure the gutter elements are
3599
  // aligned.
3600
  function setScrollLeft(cm, val, isScroller, forceScroll) {
15152 obado 3601
    val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
14283 obado 3602
    if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
3603
    cm.doc.scrollLeft = val;
3604
    alignHorizontally(cm);
3605
    if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
3606
    cm.display.scrollbars.setScrollLeft(val);
3607
  }
3608
 
3609
  // SCROLLBARS
3610
 
3611
  // Prepare DOM reads needed to update the scrollbars. Done in one
3612
  // shot to minimize update/measure roundtrips.
3613
  function measureForScrollbars(cm) {
3614
    var d = cm.display, gutterW = d.gutters.offsetWidth;
3615
    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
3616
    return {
3617
      clientHeight: d.scroller.clientHeight,
3618
      viewHeight: d.wrapper.clientHeight,
3619
      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
3620
      viewWidth: d.wrapper.clientWidth,
3621
      barLeft: cm.options.fixedGutter ? gutterW : 0,
3622
      docHeight: docH,
3623
      scrollHeight: docH + scrollGap(cm) + d.barHeight,
3624
      nativeBarWidth: d.nativeBarWidth,
3625
      gutterWidth: gutterW
3626
    }
3627
  }
3628
 
3629
  var NativeScrollbars = function(place, scroll, cm) {
3630
    this.cm = cm;
3631
    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
3632
    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
3633
    vert.tabIndex = horiz.tabIndex = -1;
3634
    place(vert); place(horiz);
3635
 
3636
    on(vert, "scroll", function () {
3637
      if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
3638
    });
3639
    on(horiz, "scroll", function () {
3640
      if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
3641
    });
3642
 
3643
    this.checkedZeroWidth = false;
3644
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
3645
    if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
3646
  };
3647
 
3648
  NativeScrollbars.prototype.update = function (measure) {
3649
    var needsH = measure.scrollWidth > measure.clientWidth + 1;
3650
    var needsV = measure.scrollHeight > measure.clientHeight + 1;
3651
    var sWidth = measure.nativeBarWidth;
3652
 
3653
    if (needsV) {
3654
      this.vert.style.display = "block";
3655
      this.vert.style.bottom = needsH ? sWidth + "px" : "0";
3656
      var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
3657
      // A bug in IE8 can cause this value to be negative, so guard it.
3658
      this.vert.firstChild.style.height =
3659
        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
3660
    } else {
16493 obado 3661
      this.vert.scrollTop = 0;
14283 obado 3662
      this.vert.style.display = "";
3663
      this.vert.firstChild.style.height = "0";
3664
    }
3665
 
3666
    if (needsH) {
3667
      this.horiz.style.display = "block";
3668
      this.horiz.style.right = needsV ? sWidth + "px" : "0";
3669
      this.horiz.style.left = measure.barLeft + "px";
3670
      var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
3671
      this.horiz.firstChild.style.width =
3672
        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
3673
    } else {
3674
      this.horiz.style.display = "";
3675
      this.horiz.firstChild.style.width = "0";
3676
    }
3677
 
3678
    if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3679
      if (sWidth == 0) { this.zeroWidthHack(); }
3680
      this.checkedZeroWidth = true;
3681
    }
3682
 
3683
    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3684
  };
3685
 
3686
  NativeScrollbars.prototype.setScrollLeft = function (pos) {
3687
    if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
3688
    if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
3689
  };
3690
 
3691
  NativeScrollbars.prototype.setScrollTop = function (pos) {
3692
    if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
3693
    if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
3694
  };
3695
 
3696
  NativeScrollbars.prototype.zeroWidthHack = function () {
3697
    var w = mac && !mac_geMountainLion ? "12px" : "18px";
3698
    this.horiz.style.height = this.vert.style.width = w;
3699
    this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
3700
    this.disableHoriz = new Delayed;
3701
    this.disableVert = new Delayed;
3702
  };
3703
 
3704
  NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
3705
    bar.style.pointerEvents = "auto";
3706
    function maybeDisable() {
3707
      // To find out whether the scrollbar is still visible, we
3708
      // check whether the element under the pixel in the bottom
3709
      // right corner of the scrollbar box is the scrollbar box
3710
      // itself (when the bar is still visible) or its filler child
3711
      // (when the bar is hidden). If it is still visible, we keep
3712
      // it enabled, if it's hidden, we disable pointer events.
3713
      var box = bar.getBoundingClientRect();
15152 obado 3714
      var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
14283 obado 3715
          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
15152 obado 3716
      if (elt != bar) { bar.style.pointerEvents = "none"; }
14283 obado 3717
      else { delay.set(1000, maybeDisable); }
3718
    }
3719
    delay.set(1000, maybeDisable);
3720
  };
3721
 
3722
  NativeScrollbars.prototype.clear = function () {
3723
    var parent = this.horiz.parentNode;
3724
    parent.removeChild(this.horiz);
3725
    parent.removeChild(this.vert);
3726
  };
3727
 
3728
  var NullScrollbars = function () {};
3729
 
3730
  NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
3731
  NullScrollbars.prototype.setScrollLeft = function () {};
3732
  NullScrollbars.prototype.setScrollTop = function () {};
3733
  NullScrollbars.prototype.clear = function () {};
3734
 
3735
  function updateScrollbars(cm, measure) {
3736
    if (!measure) { measure = measureForScrollbars(cm); }
3737
    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
3738
    updateScrollbarsInner(cm, measure);
3739
    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
3740
      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
3741
        { updateHeightsInViewport(cm); }
3742
      updateScrollbarsInner(cm, measureForScrollbars(cm));
3743
      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
3744
    }
3745
  }
3746
 
3747
  // Re-synchronize the fake scrollbars with the actual size of the
3748
  // content.
3749
  function updateScrollbarsInner(cm, measure) {
3750
    var d = cm.display;
3751
    var sizes = d.scrollbars.update(measure);
3752
 
3753
    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
3754
    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
3755
    d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
3756
 
3757
    if (sizes.right && sizes.bottom) {
3758
      d.scrollbarFiller.style.display = "block";
3759
      d.scrollbarFiller.style.height = sizes.bottom + "px";
3760
      d.scrollbarFiller.style.width = sizes.right + "px";
3761
    } else { d.scrollbarFiller.style.display = ""; }
3762
    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
3763
      d.gutterFiller.style.display = "block";
3764
      d.gutterFiller.style.height = sizes.bottom + "px";
3765
      d.gutterFiller.style.width = measure.gutterWidth + "px";
3766
    } else { d.gutterFiller.style.display = ""; }
3767
  }
3768
 
3769
  var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3770
 
3771
  function initScrollbars(cm) {
3772
    if (cm.display.scrollbars) {
3773
      cm.display.scrollbars.clear();
3774
      if (cm.display.scrollbars.addClass)
3775
        { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3776
    }
3777
 
3778
    cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
3779
      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
3780
      // Prevent clicks in the scrollbars from killing focus
3781
      on(node, "mousedown", function () {
3782
        if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
3783
      });
3784
      node.setAttribute("cm-not-content", "true");
3785
    }, function (pos, axis) {
3786
      if (axis == "horizontal") { setScrollLeft(cm, pos); }
3787
      else { updateScrollTop(cm, pos); }
3788
    }, cm);
3789
    if (cm.display.scrollbars.addClass)
3790
      { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3791
  }
3792
 
3793
  // Operations are used to wrap a series of changes to the editor
3794
  // state in such a way that each change won't have to update the
3795
  // cursor and display (which would be awkward, slow, and
3796
  // error-prone). Instead, display updates are batched and then all
3797
  // combined and executed at once.
3798
 
3799
  var nextOpId = 0;
3800
  // Start a new operation.
3801
  function startOperation(cm) {
3802
    cm.curOp = {
3803
      cm: cm,
3804
      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
3805
      startHeight: cm.doc.height, // Used to detect need to update scrollbar
3806
      forceUpdate: false,      // Used to force a redraw
3807
      updateInput: 0,       // Whether to reset the input textarea
3808
      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
3809
      changeObjs: null,        // Accumulated changes, for firing change events
3810
      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3811
      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3812
      selectionChanged: false, // Whether the selection needs to be redrawn
3813
      updateMaxLine: false,    // Set when the widest line needs to be determined anew
3814
      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3815
      scrollToPos: null,       // Used to scroll to a specific position
3816
      focus: false,
16493 obado 3817
      id: ++nextOpId,          // Unique ID
3818
      markArrays: null         // Used by addMarkedSpan
14283 obado 3819
    };
3820
    pushOperation(cm.curOp);
3821
  }
3822
 
3823
  // Finish an operation, updating the display and signalling delayed events
3824
  function endOperation(cm) {
3825
    var op = cm.curOp;
3826
    if (op) { finishOperation(op, function (group) {
3827
      for (var i = 0; i < group.ops.length; i++)
3828
        { group.ops[i].cm.curOp = null; }
3829
      endOperations(group);
3830
    }); }
3831
  }
3832
 
3833
  // The DOM updates done when an operation finishes are batched so
3834
  // that the minimum number of relayouts are required.
3835
  function endOperations(group) {
3836
    var ops = group.ops;
3837
    for (var i = 0; i < ops.length; i++) // Read DOM
3838
      { endOperation_R1(ops[i]); }
3839
    for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
3840
      { endOperation_W1(ops[i$1]); }
3841
    for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
3842
      { endOperation_R2(ops[i$2]); }
3843
    for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
3844
      { endOperation_W2(ops[i$3]); }
3845
    for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
3846
      { endOperation_finish(ops[i$4]); }
3847
  }
3848
 
3849
  function endOperation_R1(op) {
3850
    var cm = op.cm, display = cm.display;
3851
    maybeClipScrollbars(cm);
3852
    if (op.updateMaxLine) { findMaxLine(cm); }
3853
 
3854
    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3855
      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3856
                         op.scrollToPos.to.line >= display.viewTo) ||
3857
      display.maxLineChanged && cm.options.lineWrapping;
3858
    op.update = op.mustUpdate &&
3859
      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3860
  }
3861
 
3862
  function endOperation_W1(op) {
3863
    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3864
  }
3865
 
3866
  function endOperation_R2(op) {
3867
    var cm = op.cm, display = cm.display;
3868
    if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3869
 
3870
    op.barMeasure = measureForScrollbars(cm);
3871
 
3872
    // If the max line changed since it was last measured, measure it,
3873
    // and ensure the document's width matches it.
3874
    // updateDisplay_W2 will use these properties to do the actual resizing
3875
    if (display.maxLineChanged && !cm.options.lineWrapping) {
3876
      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3877
      cm.display.sizerWidth = op.adjustWidthTo;
3878
      op.barMeasure.scrollWidth =
3879
        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3880
      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3881
    }
3882
 
3883
    if (op.updatedDisplay || op.selectionChanged)
3884
      { op.preparedSelection = display.input.prepareSelection(); }
3885
  }
3886
 
3887
  function endOperation_W2(op) {
3888
    var cm = op.cm;
3889
 
3890
    if (op.adjustWidthTo != null) {
3891
      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3892
      if (op.maxScrollLeft < cm.doc.scrollLeft)
3893
        { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
3894
      cm.display.maxLineChanged = false;
3895
    }
3896
 
3897
    var takeFocus = op.focus && op.focus == activeElt();
3898
    if (op.preparedSelection)
3899
      { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
3900
    if (op.updatedDisplay || op.startHeight != cm.doc.height)
3901
      { updateScrollbars(cm, op.barMeasure); }
3902
    if (op.updatedDisplay)
3903
      { setDocumentHeight(cm, op.barMeasure); }
3904
 
3905
    if (op.selectionChanged) { restartBlink(cm); }
3906
 
3907
    if (cm.state.focused && op.updateInput)
3908
      { cm.display.input.reset(op.typing); }
3909
    if (takeFocus) { ensureFocus(op.cm); }
3910
  }
3911
 
3912
  function endOperation_finish(op) {
3913
    var cm = op.cm, display = cm.display, doc = cm.doc;
3914
 
3915
    if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3916
 
3917
    // Abort mouse wheel delta measurement, when scrolling explicitly
3918
    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3919
      { display.wheelStartX = display.wheelStartY = null; }
3920
 
3921
    // Propagate the scroll position to the actual DOM scroller
3922
    if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
3923
 
3924
    if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
3925
    // If we need to scroll a specific position into view, do so.
3926
    if (op.scrollToPos) {
3927
      var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3928
                                   clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3929
      maybeScrollWindow(cm, rect);
3930
    }
3931
 
3932
    // Fire events for markers that are hidden/unidden by editing or
3933
    // undoing
3934
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3935
    if (hidden) { for (var i = 0; i < hidden.length; ++i)
3936
      { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
3937
    if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
3938
      { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
3939
 
3940
    if (display.wrapper.offsetHeight)
3941
      { doc.scrollTop = cm.display.scroller.scrollTop; }
3942
 
3943
    // Fire change events, and delayed event handlers
3944
    if (op.changeObjs)
3945
      { signal(cm, "changes", cm, op.changeObjs); }
3946
    if (op.update)
3947
      { op.update.finish(); }
3948
  }
3949
 
3950
  // Run the given function in an operation
3951
  function runInOp(cm, f) {
3952
    if (cm.curOp) { return f() }
3953
    startOperation(cm);
3954
    try { return f() }
3955
    finally { endOperation(cm); }
3956
  }
3957
  // Wraps a function in an operation. Returns the wrapped function.
3958
  function operation(cm, f) {
3959
    return function() {
3960
      if (cm.curOp) { return f.apply(cm, arguments) }
3961
      startOperation(cm);
3962
      try { return f.apply(cm, arguments) }
3963
      finally { endOperation(cm); }
3964
    }
3965
  }
3966
  // Used to add methods to editor and doc instances, wrapping them in
3967
  // operations.
3968
  function methodOp(f) {
3969
    return function() {
3970
      if (this.curOp) { return f.apply(this, arguments) }
3971
      startOperation(this);
3972
      try { return f.apply(this, arguments) }
3973
      finally { endOperation(this); }
3974
    }
3975
  }
3976
  function docMethodOp(f) {
3977
    return function() {
3978
      var cm = this.cm;
3979
      if (!cm || cm.curOp) { return f.apply(this, arguments) }
3980
      startOperation(cm);
3981
      try { return f.apply(this, arguments) }
3982
      finally { endOperation(cm); }
3983
    }
3984
  }
3985
 
3986
  // HIGHLIGHT WORKER
3987
 
3988
  function startWorker(cm, time) {
3989
    if (cm.doc.highlightFrontier < cm.display.viewTo)
3990
      { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
3991
  }
3992
 
3993
  function highlightWorker(cm) {
3994
    var doc = cm.doc;
3995
    if (doc.highlightFrontier >= cm.display.viewTo) { return }
3996
    var end = +new Date + cm.options.workTime;
3997
    var context = getContextBefore(cm, doc.highlightFrontier);
3998
    var changedLines = [];
3999
 
4000
    doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
4001
      if (context.line >= cm.display.viewFrom) { // Visible
4002
        var oldStyles = line.styles;
4003
        var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
4004
        var highlighted = highlightLine(cm, line, context, true);
4005
        if (resetState) { context.state = resetState; }
4006
        line.styles = highlighted.styles;
4007
        var oldCls = line.styleClasses, newCls = highlighted.classes;
4008
        if (newCls) { line.styleClasses = newCls; }
4009
        else if (oldCls) { line.styleClasses = null; }
4010
        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
4011
          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
4012
        for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
4013
        if (ischange) { changedLines.push(context.line); }
4014
        line.stateAfter = context.save();
4015
        context.nextLine();
4016
      } else {
4017
        if (line.text.length <= cm.options.maxHighlightLength)
4018
          { processLine(cm, line.text, context); }
4019
        line.stateAfter = context.line % 5 == 0 ? context.save() : null;
4020
        context.nextLine();
4021
      }
4022
      if (+new Date > end) {
4023
        startWorker(cm, cm.options.workDelay);
4024
        return true
4025
      }
4026
    });
4027
    doc.highlightFrontier = context.line;
4028
    doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
4029
    if (changedLines.length) { runInOp(cm, function () {
4030
      for (var i = 0; i < changedLines.length; i++)
4031
        { regLineChange(cm, changedLines[i], "text"); }
4032
    }); }
4033
  }
4034
 
4035
  // DISPLAY DRAWING
4036
 
4037
  var DisplayUpdate = function(cm, viewport, force) {
4038
    var display = cm.display;
4039
 
4040
    this.viewport = viewport;
4041
    // Store some values that we'll need later (but don't want to force a relayout for)
4042
    this.visible = visibleLines(display, cm.doc, viewport);
4043
    this.editorIsHidden = !display.wrapper.offsetWidth;
4044
    this.wrapperHeight = display.wrapper.clientHeight;
4045
    this.wrapperWidth = display.wrapper.clientWidth;
4046
    this.oldDisplayWidth = displayWidth(cm);
4047
    this.force = force;
4048
    this.dims = getDimensions(cm);
4049
    this.events = [];
4050
  };
4051
 
4052
  DisplayUpdate.prototype.signal = function (emitter, type) {
4053
    if (hasHandler(emitter, type))
4054
      { this.events.push(arguments); }
4055
  };
4056
  DisplayUpdate.prototype.finish = function () {
4057
    for (var i = 0; i < this.events.length; i++)
15152 obado 4058
      { signal.apply(null, this.events[i]); }
14283 obado 4059
  };
4060
 
4061
  function maybeClipScrollbars(cm) {
4062
    var display = cm.display;
4063
    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
4064
      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
4065
      display.heightForcer.style.height = scrollGap(cm) + "px";
4066
      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
4067
      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
4068
      display.scrollbarsClipped = true;
4069
    }
4070
  }
4071
 
4072
  function selectionSnapshot(cm) {
4073
    if (cm.hasFocus()) { return null }
4074
    var active = activeElt();
4075
    if (!active || !contains(cm.display.lineDiv, active)) { return null }
4076
    var result = {activeElt: active};
4077
    if (window.getSelection) {
4078
      var sel = window.getSelection();
4079
      if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
4080
        result.anchorNode = sel.anchorNode;
4081
        result.anchorOffset = sel.anchorOffset;
4082
        result.focusNode = sel.focusNode;
4083
        result.focusOffset = sel.focusOffset;
4084
      }
4085
    }
4086
    return result
4087
  }
4088
 
4089
  function restoreSelection(snapshot) {
4090
    if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
4091
    snapshot.activeElt.focus();
15152 obado 4092
    if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
4093
        snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
4094
      var sel = window.getSelection(), range = document.createRange();
4095
      range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
4096
      range.collapse(false);
14283 obado 4097
      sel.removeAllRanges();
15152 obado 4098
      sel.addRange(range);
14283 obado 4099
      sel.extend(snapshot.focusNode, snapshot.focusOffset);
4100
    }
4101
  }
4102
 
4103
  // Does the actual updating of the line display. Bails out
4104
  // (returning false) when there is nothing to be done and forced is
4105
  // false.
4106
  function updateDisplayIfNeeded(cm, update) {
4107
    var display = cm.display, doc = cm.doc;
4108
 
4109
    if (update.editorIsHidden) {
4110
      resetView(cm);
4111
      return false
4112
    }
4113
 
4114
    // Bail out if the visible area is already rendered and nothing changed.
4115
    if (!update.force &&
4116
        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
4117
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
4118
        display.renderedView == display.view && countDirtyView(cm) == 0)
4119
      { return false }
4120
 
4121
    if (maybeUpdateLineNumberWidth(cm)) {
4122
      resetView(cm);
4123
      update.dims = getDimensions(cm);
4124
    }
4125
 
4126
    // Compute a suitable new viewport (from & to)
4127
    var end = doc.first + doc.size;
4128
    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
4129
    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
4130
    if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
4131
    if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
4132
    if (sawCollapsedSpans) {
4133
      from = visualLineNo(cm.doc, from);
4134
      to = visualLineEndNo(cm.doc, to);
4135
    }
4136
 
4137
    var different = from != display.viewFrom || to != display.viewTo ||
4138
      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
4139
    adjustView(cm, from, to);
4140
 
4141
    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
4142
    // Position the mover div to align with the current scroll position
4143
    cm.display.mover.style.top = display.viewOffset + "px";
4144
 
4145
    var toUpdate = countDirtyView(cm);
4146
    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
4147
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
4148
      { return false }
4149
 
4150
    // For big changes, we hide the enclosing element during the
4151
    // update, since that speeds up the operations on most browsers.
4152
    var selSnapshot = selectionSnapshot(cm);
4153
    if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
4154
    patchDisplay(cm, display.updateLineNumbers, update.dims);
4155
    if (toUpdate > 4) { display.lineDiv.style.display = ""; }
4156
    display.renderedView = display.view;
4157
    // There might have been a widget with a focused element that got
4158
    // hidden or updated, if so re-focus it.
4159
    restoreSelection(selSnapshot);
4160
 
4161
    // Prevent selection and cursors from interfering with the scroll
4162
    // width and height.
4163
    removeChildren(display.cursorDiv);
4164
    removeChildren(display.selectionDiv);
4165
    display.gutters.style.height = display.sizer.style.minHeight = 0;
4166
 
4167
    if (different) {
4168
      display.lastWrapHeight = update.wrapperHeight;
4169
      display.lastWrapWidth = update.wrapperWidth;
4170
      startWorker(cm, 400);
4171
    }
4172
 
4173
    display.updateLineNumbers = null;
4174
 
4175
    return true
4176
  }
4177
 
4178
  function postUpdateDisplay(cm, update) {
4179
    var viewport = update.viewport;
4180
 
4181
    for (var first = true;; first = false) {
4182
      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
4183
        // Clip forced viewport to actual scrollable area.
4184
        if (viewport && viewport.top != null)
4185
          { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
4186
        // Updated line heights might result in the drawn area not
4187
        // actually covering the viewport. Keep looping until it does.
4188
        update.visible = visibleLines(cm.display, cm.doc, viewport);
4189
        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
4190
          { break }
15152 obado 4191
      } else if (first) {
4192
        update.visible = visibleLines(cm.display, cm.doc, viewport);
14283 obado 4193
      }
4194
      if (!updateDisplayIfNeeded(cm, update)) { break }
4195
      updateHeightsInViewport(cm);
4196
      var barMeasure = measureForScrollbars(cm);
4197
      updateSelection(cm);
4198
      updateScrollbars(cm, barMeasure);
4199
      setDocumentHeight(cm, barMeasure);
4200
      update.force = false;
4201
    }
4202
 
4203
    update.signal(cm, "update", cm);
4204
    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
4205
      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
4206
      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
4207
    }
4208
  }
4209
 
4210
  function updateDisplaySimple(cm, viewport) {
4211
    var update = new DisplayUpdate(cm, viewport);
4212
    if (updateDisplayIfNeeded(cm, update)) {
4213
      updateHeightsInViewport(cm);
4214
      postUpdateDisplay(cm, update);
4215
      var barMeasure = measureForScrollbars(cm);
4216
      updateSelection(cm);
4217
      updateScrollbars(cm, barMeasure);
4218
      setDocumentHeight(cm, barMeasure);
4219
      update.finish();
4220
    }
4221
  }
4222
 
4223
  // Sync the actual display DOM structure with display.view, removing
4224
  // nodes for lines that are no longer in view, and creating the ones
4225
  // that are not there yet, and updating the ones that are out of
4226
  // date.
4227
  function patchDisplay(cm, updateNumbersFrom, dims) {
4228
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
4229
    var container = display.lineDiv, cur = container.firstChild;
4230
 
4231
    function rm(node) {
4232
      var next = node.nextSibling;
4233
      // Works around a throw-scroll bug in OS X Webkit
4234
      if (webkit && mac && cm.display.currentWheelTarget == node)
4235
        { node.style.display = "none"; }
4236
      else
4237
        { node.parentNode.removeChild(node); }
4238
      return next
4239
    }
4240
 
4241
    var view = display.view, lineN = display.viewFrom;
4242
    // Loop over the elements in the view, syncing cur (the DOM nodes
4243
    // in display.lineDiv) with the view as we go.
4244
    for (var i = 0; i < view.length; i++) {
4245
      var lineView = view[i];
4246
      if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
4247
        var node = buildLineElement(cm, lineView, lineN, dims);
4248
        container.insertBefore(node, cur);
4249
      } else { // Already drawn
4250
        while (cur != lineView.node) { cur = rm(cur); }
4251
        var updateNumber = lineNumbers && updateNumbersFrom != null &&
4252
          updateNumbersFrom <= lineN && lineView.lineNumber;
4253
        if (lineView.changes) {
4254
          if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
4255
          updateLineForChanges(cm, lineView, lineN, dims);
4256
        }
4257
        if (updateNumber) {
4258
          removeChildren(lineView.lineNumber);
4259
          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4260
        }
4261
        cur = lineView.node.nextSibling;
4262
      }
4263
      lineN += lineView.size;
4264
    }
4265
    while (cur) { cur = rm(cur); }
4266
  }
4267
 
4268
  function updateGutterSpace(display) {
4269
    var width = display.gutters.offsetWidth;
4270
    display.sizer.style.marginLeft = width + "px";
16493 obado 4271
    // Send an event to consumers responding to changes in gutter width.
4272
    signalLater(display, "gutterChanged", display);
14283 obado 4273
  }
4274
 
4275
  function setDocumentHeight(cm, measure) {
4276
    cm.display.sizer.style.minHeight = measure.docHeight + "px";
4277
    cm.display.heightForcer.style.top = measure.docHeight + "px";
4278
    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
4279
  }
4280
 
4281
  // Re-align line numbers and gutter marks to compensate for
4282
  // horizontal scrolling.
4283
  function alignHorizontally(cm) {
4284
    var display = cm.display, view = display.view;
4285
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
4286
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
4287
    var gutterW = display.gutters.offsetWidth, left = comp + "px";
4288
    for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
4289
      if (cm.options.fixedGutter) {
4290
        if (view[i].gutter)
4291
          { view[i].gutter.style.left = left; }
4292
        if (view[i].gutterBackground)
4293
          { view[i].gutterBackground.style.left = left; }
4294
      }
4295
      var align = view[i].alignable;
4296
      if (align) { for (var j = 0; j < align.length; j++)
4297
        { align[j].style.left = left; } }
4298
    } }
4299
    if (cm.options.fixedGutter)
4300
      { display.gutters.style.left = (comp + gutterW) + "px"; }
4301
  }
4302
 
4303
  // Used to ensure that the line number gutter is still the right
4304
  // size for the current document size. Returns true when an update
4305
  // is needed.
4306
  function maybeUpdateLineNumberWidth(cm) {
4307
    if (!cm.options.lineNumbers) { return false }
4308
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
4309
    if (last.length != display.lineNumChars) {
4310
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
4311
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
4312
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
4313
      display.lineGutter.style.width = "";
4314
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
4315
      display.lineNumWidth = display.lineNumInnerWidth + padding;
4316
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
4317
      display.lineGutter.style.width = display.lineNumWidth + "px";
4318
      updateGutterSpace(cm.display);
4319
      return true
4320
    }
4321
    return false
4322
  }
4323
 
4324
  function getGutters(gutters, lineNumbers) {
4325
    var result = [], sawLineNumbers = false;
4326
    for (var i = 0; i < gutters.length; i++) {
4327
      var name = gutters[i], style = null;
4328
      if (typeof name != "string") { style = name.style; name = name.className; }
4329
      if (name == "CodeMirror-linenumbers") {
4330
        if (!lineNumbers) { continue }
4331
        else { sawLineNumbers = true; }
4332
      }
4333
      result.push({className: name, style: style});
4334
    }
4335
    if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
4336
    return result
4337
  }
4338
 
4339
  // Rebuild the gutter elements, ensure the margin to the left of the
4340
  // code matches their width.
4341
  function renderGutters(display) {
4342
    var gutters = display.gutters, specs = display.gutterSpecs;
4343
    removeChildren(gutters);
4344
    display.lineGutter = null;
4345
    for (var i = 0; i < specs.length; ++i) {
4346
      var ref = specs[i];
4347
      var className = ref.className;
4348
      var style = ref.style;
4349
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
4350
      if (style) { gElt.style.cssText = style; }
4351
      if (className == "CodeMirror-linenumbers") {
4352
        display.lineGutter = gElt;
4353
        gElt.style.width = (display.lineNumWidth || 1) + "px";
4354
      }
4355
    }
4356
    gutters.style.display = specs.length ? "" : "none";
4357
    updateGutterSpace(display);
4358
  }
4359
 
4360
  function updateGutters(cm) {
4361
    renderGutters(cm.display);
4362
    regChange(cm);
4363
    alignHorizontally(cm);
4364
  }
4365
 
4366
  // The display handles the DOM integration, both for input reading
4367
  // and content drawing. It holds references to DOM nodes and
4368
  // display-related state.
4369
 
4370
  function Display(place, doc, input, options) {
4371
    var d = this;
4372
    this.input = input;
4373
 
4374
    // Covers bottom-right square when both scrollbars are present.
4375
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
4376
    d.scrollbarFiller.setAttribute("cm-not-content", "true");
4377
    // Covers bottom of gutter when coverGutterNextToScrollbar is on
4378
    // and h scrollbar is present.
4379
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
4380
    d.gutterFiller.setAttribute("cm-not-content", "true");
4381
    // Will contain the actual code, positioned to cover the viewport.
4382
    d.lineDiv = eltP("div", null, "CodeMirror-code");
4383
    // Elements are added to these to represent selection and cursors.
4384
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
4385
    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
4386
    // A visibility: hidden element used to find the size of things.
4387
    d.measure = elt("div", null, "CodeMirror-measure");
4388
    // When lines outside of the viewport are measured, they are drawn in this.
4389
    d.lineMeasure = elt("div", null, "CodeMirror-measure");
4390
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
4391
    d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
4392
                      null, "position: relative; outline: none");
4393
    var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
4394
    // Moved around its parent to cover visible view.
4395
    d.mover = elt("div", [lines], null, "position: relative");
4396
    // Set to the height of the document, allowing scrolling.
4397
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
4398
    d.sizerWidth = null;
4399
    // Behavior of elts with overflow: auto and padding is
4400
    // inconsistent across browsers. This is used to ensure the
4401
    // scrollable area is big enough.
4402
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
4403
    // Will contain the gutters, if any.
4404
    d.gutters = elt("div", null, "CodeMirror-gutters");
4405
    d.lineGutter = null;
4406
    // Actual scrollable element.
4407
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
4408
    d.scroller.setAttribute("tabIndex", "-1");
4409
    // The element in which the editor lives.
4410
    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
4411
 
16493 obado 4412
    // This attribute is respected by automatic translation systems such as Google Translate,
4413
    // and may also be respected by tools used by human translators.
4414
    d.wrapper.setAttribute('translate', 'no');
4415
 
14283 obado 4416
    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
4417
    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
4418
    if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
4419
 
4420
    if (place) {
4421
      if (place.appendChild) { place.appendChild(d.wrapper); }
4422
      else { place(d.wrapper); }
4423
    }
4424
 
4425
    // Current rendered range (may be bigger than the view window).
4426
    d.viewFrom = d.viewTo = doc.first;
4427
    d.reportedViewFrom = d.reportedViewTo = doc.first;
4428
    // Information about the rendered lines.
4429
    d.view = [];
4430
    d.renderedView = null;
4431
    // Holds info about a single rendered line when it was rendered
4432
    // for measurement, while not in view.
4433
    d.externalMeasured = null;
4434
    // Empty space (in pixels) above the view
4435
    d.viewOffset = 0;
4436
    d.lastWrapHeight = d.lastWrapWidth = 0;
4437
    d.updateLineNumbers = null;
4438
 
4439
    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
4440
    d.scrollbarsClipped = false;
4441
 
4442
    // Used to only resize the line number gutter when necessary (when
4443
    // the amount of lines crosses a boundary that makes its width change)
4444
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
4445
    // Set to true when a non-horizontal-scrolling line widget is
4446
    // added. As an optimization, line widget aligning is skipped when
4447
    // this is false.
4448
    d.alignWidgets = false;
4449
 
4450
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
4451
 
4452
    // Tracks the maximum line length so that the horizontal scrollbar
4453
    // can be kept static when scrolling.
4454
    d.maxLine = null;
4455
    d.maxLineLength = 0;
4456
    d.maxLineChanged = false;
4457
 
4458
    // Used for measuring wheel scrolling granularity
4459
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
4460
 
4461
    // True when shift is held down.
4462
    d.shift = false;
4463
 
4464
    // Used to track whether anything happened since the context menu
4465
    // was opened.
4466
    d.selForContextMenu = null;
4467
 
4468
    d.activeTouch = null;
4469
 
4470
    d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
4471
    renderGutters(d);
4472
 
4473
    input.init(d);
4474
  }
4475
 
4476
  // Since the delta values reported on mouse wheel events are
4477
  // unstandardized between browsers and even browser versions, and
4478
  // generally horribly unpredictable, this code starts by measuring
4479
  // the scroll effect that the first few mouse wheel events have,
4480
  // and, from that, detects the way it can convert deltas to pixel
4481
  // offsets afterwards.
4482
  //
4483
  // The reason we want to know the amount a wheel event will scroll
4484
  // is that it gives us a chance to update the display before the
4485
  // actual scrolling happens, reducing flickering.
4486
 
4487
  var wheelSamples = 0, wheelPixelsPerUnit = null;
4488
  // Fill in a browser-detected starting value on browsers where we
4489
  // know one. These don't have to be accurate -- the result of them
4490
  // being wrong would just be a slight flicker on the first wheel
4491
  // scroll (if it is large enough).
4492
  if (ie) { wheelPixelsPerUnit = -.53; }
4493
  else if (gecko) { wheelPixelsPerUnit = 15; }
4494
  else if (chrome) { wheelPixelsPerUnit = -.7; }
4495
  else if (safari) { wheelPixelsPerUnit = -1/3; }
4496
 
4497
  function wheelEventDelta(e) {
4498
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4499
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
4500
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
4501
    else if (dy == null) { dy = e.wheelDelta; }
4502
    return {x: dx, y: dy}
4503
  }
4504
  function wheelEventPixels(e) {
4505
    var delta = wheelEventDelta(e);
4506
    delta.x *= wheelPixelsPerUnit;
4507
    delta.y *= wheelPixelsPerUnit;
4508
    return delta
4509
  }
4510
 
4511
  function onScrollWheel(cm, e) {
4512
    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
16493 obado 4513
    var pixelsPerUnit = wheelPixelsPerUnit;
4514
    if (e.deltaMode === 0) {
4515
      dx = e.deltaX;
4516
      dy = e.deltaY;
4517
      pixelsPerUnit = 1;
4518
    }
14283 obado 4519
 
4520
    var display = cm.display, scroll = display.scroller;
4521
    // Quit if there's nothing to scroll here
4522
    var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4523
    var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4524
    if (!(dx && canScrollX || dy && canScrollY)) { return }
4525
 
4526
    // Webkit browsers on OS X abort momentum scrolls when the target
4527
    // of the scroll event is removed from the scrollable element.
4528
    // This hack (see related code in patchDisplay) makes sure the
4529
    // element is kept around.
4530
    if (dy && mac && webkit) {
4531
      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4532
        for (var i = 0; i < view.length; i++) {
4533
          if (view[i].node == cur) {
4534
            cm.display.currentWheelTarget = cur;
4535
            break outer
4536
          }
4537
        }
4538
      }
4539
    }
4540
 
4541
    // On some browsers, horizontal scrolling will cause redraws to
4542
    // happen before the gutter has been realigned, causing it to
4543
    // wriggle around in a most unseemly way. When we have an
4544
    // estimated pixels/delta value, we just handle horizontal
4545
    // scrolling entirely here. It'll be slightly off from native, but
4546
    // better than glitching out.
16493 obado 4547
    if (dx && !gecko && !presto && pixelsPerUnit != null) {
14283 obado 4548
      if (dy && canScrollY)
16493 obado 4549
        { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
4550
      setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
14283 obado 4551
      // Only prevent default scrolling if vertical scrolling is
4552
      // actually possible. Otherwise, it causes vertical scroll
4553
      // jitter on OSX trackpads when deltaX is small and deltaY
4554
      // is large (issue #3579)
4555
      if (!dy || (dy && canScrollY))
4556
        { e_preventDefault(e); }
4557
      display.wheelStartX = null; // Abort measurement, if in progress
4558
      return
4559
    }
4560
 
4561
    // 'Project' the visible viewport to cover the area that is being
4562
    // scrolled into view (if we know enough to estimate it).
16493 obado 4563
    if (dy && pixelsPerUnit != null) {
4564
      var pixels = dy * pixelsPerUnit;
14283 obado 4565
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4566
      if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
4567
      else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
4568
      updateDisplaySimple(cm, {top: top, bottom: bot});
4569
    }
4570
 
16493 obado 4571
    if (wheelSamples < 20 && e.deltaMode !== 0) {
14283 obado 4572
      if (display.wheelStartX == null) {
4573
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4574
        display.wheelDX = dx; display.wheelDY = dy;
4575
        setTimeout(function () {
4576
          if (display.wheelStartX == null) { return }
4577
          var movedX = scroll.scrollLeft - display.wheelStartX;
4578
          var movedY = scroll.scrollTop - display.wheelStartY;
4579
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4580
            (movedX && display.wheelDX && movedX / display.wheelDX);
4581
          display.wheelStartX = display.wheelStartY = null;
4582
          if (!sample) { return }
4583
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4584
          ++wheelSamples;
4585
        }, 200);
4586
      } else {
4587
        display.wheelDX += dx; display.wheelDY += dy;
4588
      }
4589
    }
4590
  }
4591
 
4592
  // Selection objects are immutable. A new one is created every time
4593
  // the selection changes. A selection is one or more non-overlapping
4594
  // (and non-touching) ranges, sorted, and an integer that indicates
4595
  // which one is the primary selection (the one that's scrolled into
4596
  // view, that getCursor returns, etc).
4597
  var Selection = function(ranges, primIndex) {
4598
    this.ranges = ranges;
4599
    this.primIndex = primIndex;
4600
  };
4601
 
4602
  Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
4603
 
4604
  Selection.prototype.equals = function (other) {
4605
    if (other == this) { return true }
4606
    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
4607
    for (var i = 0; i < this.ranges.length; i++) {
15152 obado 4608
      var here = this.ranges[i], there = other.ranges[i];
14283 obado 4609
      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
4610
    }
4611
    return true
4612
  };
4613
 
4614
  Selection.prototype.deepCopy = function () {
4615
    var out = [];
4616
    for (var i = 0; i < this.ranges.length; i++)
15152 obado 4617
      { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
14283 obado 4618
    return new Selection(out, this.primIndex)
4619
  };
4620
 
4621
  Selection.prototype.somethingSelected = function () {
4622
    for (var i = 0; i < this.ranges.length; i++)
15152 obado 4623
      { if (!this.ranges[i].empty()) { return true } }
14283 obado 4624
    return false
4625
  };
4626
 
4627
  Selection.prototype.contains = function (pos, end) {
4628
    if (!end) { end = pos; }
4629
    for (var i = 0; i < this.ranges.length; i++) {
15152 obado 4630
      var range = this.ranges[i];
14283 obado 4631
      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
4632
        { return i }
4633
    }
4634
    return -1
4635
  };
4636
 
4637
  var Range = function(anchor, head) {
4638
    this.anchor = anchor; this.head = head;
4639
  };
4640
 
4641
  Range.prototype.from = function () { return minPos(this.anchor, this.head) };
4642
  Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
4643
  Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
4644
 
4645
  // Take an unsorted, potentially overlapping set of ranges, and
4646
  // build a selection out of it. 'Consumes' ranges array (modifying
4647
  // it).
4648
  function normalizeSelection(cm, ranges, primIndex) {
4649
    var mayTouch = cm && cm.options.selectionsMayTouch;
4650
    var prim = ranges[primIndex];
4651
    ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
4652
    primIndex = indexOf(ranges, prim);
4653
    for (var i = 1; i < ranges.length; i++) {
4654
      var cur = ranges[i], prev = ranges[i - 1];
4655
      var diff = cmp(prev.to(), cur.from());
4656
      if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
4657
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
4658
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
4659
        if (i <= primIndex) { --primIndex; }
4660
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
4661
      }
4662
    }
4663
    return new Selection(ranges, primIndex)
4664
  }
4665
 
4666
  function simpleSelection(anchor, head) {
4667
    return new Selection([new Range(anchor, head || anchor)], 0)
4668
  }
4669
 
4670
  // Compute the position of the end of a change (its 'to' property
4671
  // refers to the pre-change end).
4672
  function changeEnd(change) {
4673
    if (!change.text) { return change.to }
4674
    return Pos(change.from.line + change.text.length - 1,
4675
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
4676
  }
4677
 
4678
  // Adjust a position to refer to the post-change position of the
4679
  // same text, or the end of the change if the change covers it.
4680
  function adjustForChange(pos, change) {
4681
    if (cmp(pos, change.from) < 0) { return pos }
4682
    if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
4683
 
4684
    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4685
    if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
4686
    return Pos(line, ch)
4687
  }
4688
 
4689
  function computeSelAfterChange(doc, change) {
4690
    var out = [];
4691
    for (var i = 0; i < doc.sel.ranges.length; i++) {
4692
      var range = doc.sel.ranges[i];
4693
      out.push(new Range(adjustForChange(range.anchor, change),
4694
                         adjustForChange(range.head, change)));
4695
    }
4696
    return normalizeSelection(doc.cm, out, doc.sel.primIndex)
4697
  }
4698
 
4699
  function offsetPos(pos, old, nw) {
4700
    if (pos.line == old.line)
4701
      { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
4702
    else
4703
      { return Pos(nw.line + (pos.line - old.line), pos.ch) }
4704
  }
4705
 
4706
  // Used by replaceSelections to allow moving the selection to the
4707
  // start or around the replaced test. Hint may be "start" or "around".
4708
  function computeReplacedSel(doc, changes, hint) {
4709
    var out = [];
4710
    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4711
    for (var i = 0; i < changes.length; i++) {
4712
      var change = changes[i];
4713
      var from = offsetPos(change.from, oldPrev, newPrev);
4714
      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4715
      oldPrev = change.to;
4716
      newPrev = to;
4717
      if (hint == "around") {
4718
        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4719
        out[i] = new Range(inv ? to : from, inv ? from : to);
4720
      } else {
4721
        out[i] = new Range(from, from);
4722
      }
4723
    }
4724
    return new Selection(out, doc.sel.primIndex)
4725
  }
4726
 
4727
  // Used to get the editor into a consistent state again when options change.
4728
 
4729
  function loadMode(cm) {
4730
    cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4731
    resetModeState(cm);
4732
  }
4733
 
4734
  function resetModeState(cm) {
4735
    cm.doc.iter(function (line) {
4736
      if (line.stateAfter) { line.stateAfter = null; }
4737
      if (line.styles) { line.styles = null; }
4738
    });
4739
    cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
4740
    startWorker(cm, 100);
4741
    cm.state.modeGen++;
4742
    if (cm.curOp) { regChange(cm); }
4743
  }
4744
 
4745
  // DOCUMENT DATA STRUCTURE
4746
 
4747
  // By default, updates that start and end at the beginning of a line
4748
  // are treated specially, in order to make the association of line
4749
  // widgets and marker elements with the text behave more intuitive.
4750
  function isWholeLineUpdate(doc, change) {
4751
    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
4752
      (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
4753
  }
4754
 
4755
  // Perform a change on the document data structure.
15152 obado 4756
  function updateDoc(doc, change, markedSpans, estimateHeight) {
14283 obado 4757
    function spansFor(n) {return markedSpans ? markedSpans[n] : null}
4758
    function update(line, text, spans) {
15152 obado 4759
      updateLine(line, text, spans, estimateHeight);
14283 obado 4760
      signalLater(line, "change", line, change);
4761
    }
4762
    function linesFor(start, end) {
4763
      var result = [];
4764
      for (var i = start; i < end; ++i)
15152 obado 4765
        { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
14283 obado 4766
      return result
4767
    }
4768
 
4769
    var from = change.from, to = change.to, text = change.text;
4770
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4771
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4772
 
4773
    // Adjust the line structure
4774
    if (change.full) {
4775
      doc.insert(0, linesFor(0, text.length));
4776
      doc.remove(text.length, doc.size - text.length);
4777
    } else if (isWholeLineUpdate(doc, change)) {
4778
      // This is a whole-line replace. Treated specially to make
4779
      // sure line objects move the way they are supposed to.
4780
      var added = linesFor(0, text.length - 1);
4781
      update(lastLine, lastLine.text, lastSpans);
4782
      if (nlines) { doc.remove(from.line, nlines); }
4783
      if (added.length) { doc.insert(from.line, added); }
4784
    } else if (firstLine == lastLine) {
4785
      if (text.length == 1) {
4786
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4787
      } else {
4788
        var added$1 = linesFor(1, text.length - 1);
15152 obado 4789
        added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
14283 obado 4790
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4791
        doc.insert(from.line + 1, added$1);
4792
      }
4793
    } else if (text.length == 1) {
4794
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4795
      doc.remove(from.line + 1, nlines);
4796
    } else {
4797
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4798
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4799
      var added$2 = linesFor(1, text.length - 1);
4800
      if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
4801
      doc.insert(from.line + 1, added$2);
4802
    }
4803
 
4804
    signalLater(doc, "change", doc, change);
4805
  }
4806
 
4807
  // Call f for all linked documents.
4808
  function linkedDocs(doc, f, sharedHistOnly) {
4809
    function propagate(doc, skip, sharedHist) {
4810
      if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
4811
        var rel = doc.linked[i];
4812
        if (rel.doc == skip) { continue }
4813
        var shared = sharedHist && rel.sharedHist;
4814
        if (sharedHistOnly && !shared) { continue }
4815
        f(rel.doc, shared);
4816
        propagate(rel.doc, doc, shared);
4817
      } }
4818
    }
4819
    propagate(doc, null, true);
4820
  }
4821
 
4822
  // Attach a document to an editor.
4823
  function attachDoc(cm, doc) {
4824
    if (doc.cm) { throw new Error("This document is already in use.") }
4825
    cm.doc = doc;
4826
    doc.cm = cm;
4827
    estimateLineHeights(cm);
4828
    loadMode(cm);
4829
    setDirectionClass(cm);
16493 obado 4830
    cm.options.direction = doc.direction;
14283 obado 4831
    if (!cm.options.lineWrapping) { findMaxLine(cm); }
4832
    cm.options.mode = doc.modeOption;
4833
    regChange(cm);
4834
  }
4835
 
4836
  function setDirectionClass(cm) {
4837
  (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
4838
  }
4839
 
4840
  function directionChanged(cm) {
4841
    runInOp(cm, function () {
4842
      setDirectionClass(cm);
4843
      regChange(cm);
4844
    });
4845
  }
4846
 
16493 obado 4847
  function History(prev) {
14283 obado 4848
    // Arrays of change events and selections. Doing something adds an
4849
    // event to done and clears undo. Undoing moves events from done
4850
    // to undone, redoing moves them in the other direction.
4851
    this.done = []; this.undone = [];
16493 obado 4852
    this.undoDepth = prev ? prev.undoDepth : Infinity;
14283 obado 4853
    // Used to track when changes can be merged into a single undo
4854
    // event
4855
    this.lastModTime = this.lastSelTime = 0;
4856
    this.lastOp = this.lastSelOp = null;
4857
    this.lastOrigin = this.lastSelOrigin = null;
4858
    // Used by the isClean() method
16493 obado 4859
    this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
14283 obado 4860
  }
4861
 
4862
  // Create a history change event from an updateDoc-style change
4863
  // object.
4864
  function historyChangeFromChange(doc, change) {
4865
    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4866
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4867
    linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
4868
    return histChange
4869
  }
4870
 
4871
  // Pop all selection events off the end of a history array. Stop at
4872
  // a change event.
4873
  function clearSelectionEvents(array) {
4874
    while (array.length) {
4875
      var last = lst(array);
4876
      if (last.ranges) { array.pop(); }
4877
      else { break }
4878
    }
4879
  }
4880
 
4881
  // Find the top change event in the history. Pop off selection
4882
  // events that are in the way.
4883
  function lastChangeEvent(hist, force) {
4884
    if (force) {
4885
      clearSelectionEvents(hist.done);
4886
      return lst(hist.done)
4887
    } else if (hist.done.length && !lst(hist.done).ranges) {
4888
      return lst(hist.done)
4889
    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
4890
      hist.done.pop();
4891
      return lst(hist.done)
4892
    }
4893
  }
4894
 
4895
  // Register a change in the history. Merges changes that are within
4896
  // a single operation, or are close together with an origin that
4897
  // allows merging (starting with "+") into a single event.
4898
  function addChangeToHistory(doc, change, selAfter, opId) {
4899
    var hist = doc.history;
4900
    hist.undone.length = 0;
4901
    var time = +new Date, cur;
4902
    var last;
4903
 
4904
    if ((hist.lastOp == opId ||
4905
         hist.lastOrigin == change.origin && change.origin &&
4906
         ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
4907
          change.origin.charAt(0) == "*")) &&
4908
        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
4909
      // Merge this change into the last event
4910
      last = lst(cur.changes);
4911
      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
4912
        // Optimized case for simple insertion -- don't want to add
4913
        // new changesets for every character typed
4914
        last.to = changeEnd(change);
4915
      } else {
4916
        // Add new sub-event
4917
        cur.changes.push(historyChangeFromChange(doc, change));
4918
      }
4919
    } else {
4920
      // Can not be merged, start a new event.
4921
      var before = lst(hist.done);
4922
      if (!before || !before.ranges)
4923
        { pushSelectionToHistory(doc.sel, hist.done); }
4924
      cur = {changes: [historyChangeFromChange(doc, change)],
4925
             generation: hist.generation};
4926
      hist.done.push(cur);
4927
      while (hist.done.length > hist.undoDepth) {
4928
        hist.done.shift();
4929
        if (!hist.done[0].ranges) { hist.done.shift(); }
4930
      }
4931
    }
4932
    hist.done.push(selAfter);
4933
    hist.generation = ++hist.maxGeneration;
4934
    hist.lastModTime = hist.lastSelTime = time;
4935
    hist.lastOp = hist.lastSelOp = opId;
4936
    hist.lastOrigin = hist.lastSelOrigin = change.origin;
4937
 
4938
    if (!last) { signal(doc, "historyAdded"); }
4939
  }
4940
 
4941
  function selectionEventCanBeMerged(doc, origin, prev, sel) {
4942
    var ch = origin.charAt(0);
4943
    return ch == "*" ||
4944
      ch == "+" &&
4945
      prev.ranges.length == sel.ranges.length &&
4946
      prev.somethingSelected() == sel.somethingSelected() &&
4947
      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
4948
  }
4949
 
4950
  // Called whenever the selection changes, sets the new selection as
4951
  // the pending selection in the history, and pushes the old pending
4952
  // selection into the 'done' array when it was significantly
4953
  // different (in number of selected ranges, emptiness, or time).
4954
  function addSelectionToHistory(doc, sel, opId, options) {
4955
    var hist = doc.history, origin = options && options.origin;
4956
 
4957
    // A new event is started when the previous origin does not match
4958
    // the current, or the origins don't allow matching. Origins
4959
    // starting with * are always merged, those starting with + are
4960
    // merged when similar and close together in time.
4961
    if (opId == hist.lastSelOp ||
4962
        (origin && hist.lastSelOrigin == origin &&
4963
         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
4964
          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
4965
      { hist.done[hist.done.length - 1] = sel; }
4966
    else
4967
      { pushSelectionToHistory(sel, hist.done); }
4968
 
4969
    hist.lastSelTime = +new Date;
4970
    hist.lastSelOrigin = origin;
4971
    hist.lastSelOp = opId;
4972
    if (options && options.clearRedo !== false)
4973
      { clearSelectionEvents(hist.undone); }
4974
  }
4975
 
4976
  function pushSelectionToHistory(sel, dest) {
4977
    var top = lst(dest);
4978
    if (!(top && top.ranges && top.equals(sel)))
4979
      { dest.push(sel); }
4980
  }
4981
 
4982
  // Used to store marked span information in the history.
4983
  function attachLocalSpans(doc, change, from, to) {
4984
    var existing = change["spans_" + doc.id], n = 0;
4985
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
4986
      if (line.markedSpans)
4987
        { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
4988
      ++n;
4989
    });
4990
  }
4991
 
4992
  // When un/re-doing restores text containing marked spans, those
4993
  // that have been explicitly cleared should not be restored.
4994
  function removeClearedSpans(spans) {
4995
    if (!spans) { return null }
4996
    var out;
4997
    for (var i = 0; i < spans.length; ++i) {
4998
      if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
4999
      else if (out) { out.push(spans[i]); }
5000
    }
5001
    return !out ? spans : out.length ? out : null
5002
  }
5003
 
5004
  // Retrieve and filter the old marked spans stored in a change event.
5005
  function getOldSpans(doc, change) {
5006
    var found = change["spans_" + doc.id];
5007
    if (!found) { return null }
5008
    var nw = [];
5009
    for (var i = 0; i < change.text.length; ++i)
5010
      { nw.push(removeClearedSpans(found[i])); }
5011
    return nw
5012
  }
5013
 
5014
  // Used for un/re-doing changes from the history. Combines the
5015
  // result of computing the existing spans with the set of spans that
5016
  // existed in the history (so that deleting around a span and then
5017
  // undoing brings back the span).
5018
  function mergeOldSpans(doc, change) {
5019
    var old = getOldSpans(doc, change);
5020
    var stretched = stretchSpansOverChange(doc, change);
5021
    if (!old) { return stretched }
5022
    if (!stretched) { return old }
5023
 
5024
    for (var i = 0; i < old.length; ++i) {
5025
      var oldCur = old[i], stretchCur = stretched[i];
5026
      if (oldCur && stretchCur) {
5027
        spans: for (var j = 0; j < stretchCur.length; ++j) {
5028
          var span = stretchCur[j];
5029
          for (var k = 0; k < oldCur.length; ++k)
5030
            { if (oldCur[k].marker == span.marker) { continue spans } }
5031
          oldCur.push(span);
5032
        }
5033
      } else if (stretchCur) {
5034
        old[i] = stretchCur;
5035
      }
5036
    }
5037
    return old
5038
  }
5039
 
5040
  // Used both to provide a JSON-safe object in .getHistory, and, when
5041
  // detaching a document, to split the history in two
5042
  function copyHistoryArray(events, newGroup, instantiateSel) {
5043
    var copy = [];
5044
    for (var i = 0; i < events.length; ++i) {
5045
      var event = events[i];
5046
      if (event.ranges) {
5047
        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
5048
        continue
5049
      }
5050
      var changes = event.changes, newChanges = [];
5051
      copy.push({changes: newChanges});
5052
      for (var j = 0; j < changes.length; ++j) {
5053
        var change = changes[j], m = (void 0);
5054
        newChanges.push({from: change.from, to: change.to, text: change.text});
5055
        if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
5056
          if (indexOf(newGroup, Number(m[1])) > -1) {
5057
            lst(newChanges)[prop] = change[prop];
5058
            delete change[prop];
5059
          }
5060
        } } }
5061
      }
5062
    }
5063
    return copy
5064
  }
5065
 
5066
  // The 'scroll' parameter given to many of these indicated whether
5067
  // the new cursor position should be scrolled into view after
5068
  // modifying the selection.
5069
 
5070
  // If shift is held or the extend flag is set, extends a range to
5071
  // include a given position (and optionally a second position).
5072
  // Otherwise, simply returns the range between the given positions.
5073
  // Used for cursor motion and such.
5074
  function extendRange(range, head, other, extend) {
5075
    if (extend) {
5076
      var anchor = range.anchor;
5077
      if (other) {
5078
        var posBefore = cmp(head, anchor) < 0;
5079
        if (posBefore != (cmp(other, anchor) < 0)) {
5080
          anchor = head;
5081
          head = other;
5082
        } else if (posBefore != (cmp(head, other) < 0)) {
5083
          head = other;
5084
        }
5085
      }
5086
      return new Range(anchor, head)
5087
    } else {
5088
      return new Range(other || head, head)
5089
    }
5090
  }
5091
 
5092
  // Extend the primary selection range, discard the rest.
5093
  function extendSelection(doc, head, other, options, extend) {
5094
    if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
5095
    setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
5096
  }
5097
 
5098
  // Extend all selections (pos is an array of selections with length
5099
  // equal the number of selections)
5100
  function extendSelections(doc, heads, options) {
5101
    var out = [];
5102
    var extend = doc.cm && (doc.cm.display.shift || doc.extend);
5103
    for (var i = 0; i < doc.sel.ranges.length; i++)
5104
      { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
5105
    var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
5106
    setSelection(doc, newSel, options);
5107
  }
5108
 
5109
  // Updates a single range in the selection.
5110
  function replaceOneSelection(doc, i, range, options) {
5111
    var ranges = doc.sel.ranges.slice(0);
5112
    ranges[i] = range;
5113
    setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
5114
  }
5115
 
5116
  // Reset the selection to a single range.
5117
  function setSimpleSelection(doc, anchor, head, options) {
5118
    setSelection(doc, simpleSelection(anchor, head), options);
5119
  }
5120
 
5121
  // Give beforeSelectionChange handlers a change to influence a
5122
  // selection update.
5123
  function filterSelectionChange(doc, sel, options) {
5124
    var obj = {
5125
      ranges: sel.ranges,
5126
      update: function(ranges) {
5127
        this.ranges = [];
5128
        for (var i = 0; i < ranges.length; i++)
15152 obado 5129
          { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
14283 obado 5130
                                     clipPos(doc, ranges[i].head)); }
5131
      },
5132
      origin: options && options.origin
5133
    };
5134
    signal(doc, "beforeSelectionChange", doc, obj);
5135
    if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
5136
    if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
5137
    else { return sel }
5138
  }
5139
 
5140
  function setSelectionReplaceHistory(doc, sel, options) {
5141
    var done = doc.history.done, last = lst(done);
5142
    if (last && last.ranges) {
5143
      done[done.length - 1] = sel;
5144
      setSelectionNoUndo(doc, sel, options);
5145
    } else {
5146
      setSelection(doc, sel, options);
5147
    }
5148
  }
5149
 
5150
  // Set a new selection.
5151
  function setSelection(doc, sel, options) {
5152
    setSelectionNoUndo(doc, sel, options);
5153
    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
5154
  }
5155
 
5156
  function setSelectionNoUndo(doc, sel, options) {
5157
    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5158
      { sel = filterSelectionChange(doc, sel, options); }
5159
 
5160
    var bias = options && options.bias ||
5161
      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
5162
    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
5163
 
16493 obado 5164
    if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
14283 obado 5165
      { ensureCursorVisible(doc.cm); }
5166
  }
5167
 
5168
  function setSelectionInner(doc, sel) {
5169
    if (sel.equals(doc.sel)) { return }
5170
 
5171
    doc.sel = sel;
5172
 
5173
    if (doc.cm) {
5174
      doc.cm.curOp.updateInput = 1;
5175
      doc.cm.curOp.selectionChanged = true;
5176
      signalCursorActivity(doc.cm);
5177
    }
5178
    signalLater(doc, "cursorActivity", doc);
5179
  }
5180
 
5181
  // Verify that the selection does not partially select any atomic
5182
  // marked ranges.
5183
  function reCheckSelection(doc) {
5184
    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
5185
  }
5186
 
5187
  // Return a selection that does not partially select any atomic
5188
  // ranges.
5189
  function skipAtomicInSelection(doc, sel, bias, mayClear) {
5190
    var out;
5191
    for (var i = 0; i < sel.ranges.length; i++) {
5192
      var range = sel.ranges[i];
5193
      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
5194
      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
5195
      var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
5196
      if (out || newAnchor != range.anchor || newHead != range.head) {
5197
        if (!out) { out = sel.ranges.slice(0, i); }
5198
        out[i] = new Range(newAnchor, newHead);
5199
      }
5200
    }
5201
    return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
5202
  }
5203
 
5204
  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
5205
    var line = getLine(doc, pos.line);
5206
    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
5207
      var sp = line.markedSpans[i], m = sp.marker;
5208
 
5209
      // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
5210
      // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
5211
      // is with selectLeft/Right
5212
      var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
5213
      var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
5214
 
5215
      if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
5216
          (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
5217
        if (mayClear) {
5218
          signal(m, "beforeCursorEnter");
5219
          if (m.explicitlyCleared) {
5220
            if (!line.markedSpans) { break }
5221
            else {--i; continue}
5222
          }
5223
        }
5224
        if (!m.atomic) { continue }
5225
 
5226
        if (oldPos) {
5227
          var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
5228
          if (dir < 0 ? preventCursorRight : preventCursorLeft)
5229
            { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
5230
          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
5231
            { return skipAtomicInner(doc, near, pos, dir, mayClear) }
5232
        }
5233
 
5234
        var far = m.find(dir < 0 ? -1 : 1);
5235
        if (dir < 0 ? preventCursorLeft : preventCursorRight)
5236
          { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
5237
        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
5238
      }
5239
    } }
5240
    return pos
5241
  }
5242
 
5243
  // Ensure a given position is not inside an atomic range.
5244
  function skipAtomic(doc, pos, oldPos, bias, mayClear) {
5245
    var dir = bias || 1;
5246
    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
5247
        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
5248
        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
5249
        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
5250
    if (!found) {
5251
      doc.cantEdit = true;
5252
      return Pos(doc.first, 0)
5253
    }
5254
    return found
5255
  }
5256
 
5257
  function movePos(doc, pos, dir, line) {
5258
    if (dir < 0 && pos.ch == 0) {
5259
      if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
5260
      else { return null }
5261
    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
5262
      if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
5263
      else { return null }
5264
    } else {
5265
      return new Pos(pos.line, pos.ch + dir)
5266
    }
5267
  }
5268
 
5269
  function selectAll(cm) {
5270
    cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
5271
  }
5272
 
5273
  // UPDATING
5274
 
5275
  // Allow "beforeChange" event handlers to influence a change
5276
  function filterChange(doc, change, update) {
5277
    var obj = {
5278
      canceled: false,
5279
      from: change.from,
5280
      to: change.to,
5281
      text: change.text,
5282
      origin: change.origin,
5283
      cancel: function () { return obj.canceled = true; }
5284
    };
5285
    if (update) { obj.update = function (from, to, text, origin) {
5286
      if (from) { obj.from = clipPos(doc, from); }
5287
      if (to) { obj.to = clipPos(doc, to); }
5288
      if (text) { obj.text = text; }
5289
      if (origin !== undefined) { obj.origin = origin; }
5290
    }; }
5291
    signal(doc, "beforeChange", doc, obj);
5292
    if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
5293
 
5294
    if (obj.canceled) {
5295
      if (doc.cm) { doc.cm.curOp.updateInput = 2; }
5296
      return null
5297
    }
5298
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
5299
  }
5300
 
5301
  // Apply a change to a document, and add it to the document's
5302
  // history, and propagating it to all linked documents.
5303
  function makeChange(doc, change, ignoreReadOnly) {
5304
    if (doc.cm) {
5305
      if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
5306
      if (doc.cm.state.suppressEdits) { return }
5307
    }
5308
 
5309
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5310
      change = filterChange(doc, change, true);
5311
      if (!change) { return }
5312
    }
5313
 
5314
    // Possibly split or suppress the update based on the presence
5315
    // of read-only spans in its range.
5316
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
5317
    if (split) {
5318
      for (var i = split.length - 1; i >= 0; --i)
5319
        { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
5320
    } else {
5321
      makeChangeInner(doc, change);
5322
    }
5323
  }
5324
 
5325
  function makeChangeInner(doc, change) {
5326
    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
5327
    var selAfter = computeSelAfterChange(doc, change);
5328
    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
5329
 
5330
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
5331
    var rebased = [];
5332
 
5333
    linkedDocs(doc, function (doc, sharedHist) {
5334
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5335
        rebaseHist(doc.history, change);
5336
        rebased.push(doc.history);
5337
      }
5338
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
5339
    });
5340
  }
5341
 
5342
  // Revert a change stored in a document's history.
5343
  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
5344
    var suppress = doc.cm && doc.cm.state.suppressEdits;
5345
    if (suppress && !allowSelectionOnly) { return }
5346
 
5347
    var hist = doc.history, event, selAfter = doc.sel;
5348
    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
5349
 
5350
    // Verify that there is a useable event (so that ctrl-z won't
5351
    // needlessly clear selection events)
5352
    var i = 0;
5353
    for (; i < source.length; i++) {
5354
      event = source[i];
5355
      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
5356
        { break }
5357
    }
5358
    if (i == source.length) { return }
5359
    hist.lastOrigin = hist.lastSelOrigin = null;
5360
 
5361
    for (;;) {
5362
      event = source.pop();
5363
      if (event.ranges) {
5364
        pushSelectionToHistory(event, dest);
5365
        if (allowSelectionOnly && !event.equals(doc.sel)) {
5366
          setSelection(doc, event, {clearRedo: false});
5367
          return
5368
        }
5369
        selAfter = event;
5370
      } else if (suppress) {
5371
        source.push(event);
5372
        return
5373
      } else { break }
5374
    }
5375
 
5376
    // Build up a reverse change object to add to the opposite history
5377
    // stack (redo when undoing, and vice versa).
5378
    var antiChanges = [];
5379
    pushSelectionToHistory(selAfter, dest);
5380
    dest.push({changes: antiChanges, generation: hist.generation});
5381
    hist.generation = event.generation || ++hist.maxGeneration;
5382
 
5383
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
5384
 
5385
    var loop = function ( i ) {
5386
      var change = event.changes[i];
5387
      change.origin = type;
5388
      if (filter && !filterChange(doc, change, false)) {
5389
        source.length = 0;
5390
        return {}
5391
      }
5392
 
5393
      antiChanges.push(historyChangeFromChange(doc, change));
5394
 
5395
      var after = i ? computeSelAfterChange(doc, change) : lst(source);
5396
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
5397
      if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
5398
      var rebased = [];
5399
 
5400
      // Propagate to the linked documents
5401
      linkedDocs(doc, function (doc, sharedHist) {
5402
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5403
          rebaseHist(doc.history, change);
5404
          rebased.push(doc.history);
5405
        }
5406
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5407
      });
5408
    };
5409
 
5410
    for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5411
      var returned = loop( i$1 );
5412
 
5413
      if ( returned ) return returned.v;
5414
    }
5415
  }
5416
 
5417
  // Sub-views need their line numbers shifted when text is added
5418
  // above or below them in the parent document.
5419
  function shiftDoc(doc, distance) {
5420
    if (distance == 0) { return }
5421
    doc.first += distance;
5422
    doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
5423
      Pos(range.anchor.line + distance, range.anchor.ch),
5424
      Pos(range.head.line + distance, range.head.ch)
5425
    ); }), doc.sel.primIndex);
5426
    if (doc.cm) {
5427
      regChange(doc.cm, doc.first, doc.first - distance, distance);
5428
      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
5429
        { regLineChange(doc.cm, l, "gutter"); }
5430
    }
5431
  }
5432
 
5433
  // More lower-level change function, handling only a single document
5434
  // (not linked ones).
5435
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
5436
    if (doc.cm && !doc.cm.curOp)
5437
      { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
5438
 
5439
    if (change.to.line < doc.first) {
5440
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
5441
      return
5442
    }
5443
    if (change.from.line > doc.lastLine()) { return }
5444
 
5445
    // Clip the change to the size of this doc
5446
    if (change.from.line < doc.first) {
5447
      var shift = change.text.length - 1 - (doc.first - change.from.line);
5448
      shiftDoc(doc, shift);
5449
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
5450
                text: [lst(change.text)], origin: change.origin};
5451
    }
5452
    var last = doc.lastLine();
5453
    if (change.to.line > last) {
5454
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
5455
                text: [change.text[0]], origin: change.origin};
5456
    }
5457
 
5458
    change.removed = getBetween(doc, change.from, change.to);
5459
 
5460
    if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
5461
    if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
5462
    else { updateDoc(doc, change, spans); }
5463
    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
5464
 
5465
    if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
5466
      { doc.cantEdit = false; }
5467
  }
5468
 
5469
  // Handle the interaction of a change to a document with the editor
5470
  // that this document is part of.
5471
  function makeChangeSingleDocInEditor(cm, change, spans) {
5472
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
5473
 
5474
    var recomputeMaxLength = false, checkWidthStart = from.line;
5475
    if (!cm.options.lineWrapping) {
5476
      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
5477
      doc.iter(checkWidthStart, to.line + 1, function (line) {
5478
        if (line == display.maxLine) {
5479
          recomputeMaxLength = true;
5480
          return true
5481
        }
5482
      });
5483
    }
5484
 
5485
    if (doc.sel.contains(change.from, change.to) > -1)
5486
      { signalCursorActivity(cm); }
5487
 
5488
    updateDoc(doc, change, spans, estimateHeight(cm));
5489
 
5490
    if (!cm.options.lineWrapping) {
5491
      doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
5492
        var len = lineLength(line);
5493
        if (len > display.maxLineLength) {
5494
          display.maxLine = line;
5495
          display.maxLineLength = len;
5496
          display.maxLineChanged = true;
5497
          recomputeMaxLength = false;
5498
        }
5499
      });
5500
      if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
5501
    }
5502
 
5503
    retreatFrontier(doc, from.line);
5504
    startWorker(cm, 400);
5505
 
5506
    var lendiff = change.text.length - (to.line - from.line) - 1;
5507
    // Remember that these lines changed, for updating the display
5508
    if (change.full)
5509
      { regChange(cm); }
5510
    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
5511
      { regLineChange(cm, from.line, "text"); }
5512
    else
5513
      { regChange(cm, from.line, to.line + 1, lendiff); }
5514
 
5515
    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
5516
    if (changeHandler || changesHandler) {
5517
      var obj = {
5518
        from: from, to: to,
5519
        text: change.text,
5520
        removed: change.removed,
5521
        origin: change.origin
5522
      };
5523
      if (changeHandler) { signalLater(cm, "change", cm, obj); }
5524
      if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
5525
    }
5526
    cm.display.selForContextMenu = null;
5527
  }
5528
 
5529
  function replaceRange(doc, code, from, to, origin) {
5530
    var assign;
5531
 
5532
    if (!to) { to = from; }
5533
    if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
5534
    if (typeof code == "string") { code = doc.splitLines(code); }
5535
    makeChange(doc, {from: from, to: to, text: code, origin: origin});
5536
  }
5537
 
5538
  // Rebasing/resetting history to deal with externally-sourced changes
5539
 
5540
  function rebaseHistSelSingle(pos, from, to, diff) {
5541
    if (to < pos.line) {
5542
      pos.line += diff;
5543
    } else if (from < pos.line) {
5544
      pos.line = from;
5545
      pos.ch = 0;
5546
    }
5547
  }
5548
 
5549
  // Tries to rebase an array of history events given a change in the
5550
  // document. If the change touches the same lines as the event, the
5551
  // event, and everything 'behind' it, is discarded. If the change is
5552
  // before the event, the event's positions are updated. Uses a
5553
  // copy-on-write scheme for the positions, to avoid having to
5554
  // reallocate them all on every rebase, but also avoid problems with
5555
  // shared position objects being unsafely updated.
5556
  function rebaseHistArray(array, from, to, diff) {
5557
    for (var i = 0; i < array.length; ++i) {
5558
      var sub = array[i], ok = true;
5559
      if (sub.ranges) {
5560
        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
5561
        for (var j = 0; j < sub.ranges.length; j++) {
5562
          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
5563
          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
5564
        }
5565
        continue
5566
      }
5567
      for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
5568
        var cur = sub.changes[j$1];
5569
        if (to < cur.from.line) {
5570
          cur.from = Pos(cur.from.line + diff, cur.from.ch);
5571
          cur.to = Pos(cur.to.line + diff, cur.to.ch);
5572
        } else if (from <= cur.to.line) {
5573
          ok = false;
5574
          break
5575
        }
5576
      }
5577
      if (!ok) {
5578
        array.splice(0, i + 1);
5579
        i = 0;
5580
      }
5581
    }
5582
  }
5583
 
5584
  function rebaseHist(hist, change) {
5585
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5586
    rebaseHistArray(hist.done, from, to, diff);
5587
    rebaseHistArray(hist.undone, from, to, diff);
5588
  }
5589
 
5590
  // Utility for applying a change to a line by handle or number,
5591
  // returning the number and optionally registering the line as
5592
  // changed.
5593
  function changeLine(doc, handle, changeType, op) {
5594
    var no = handle, line = handle;
5595
    if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
5596
    else { no = lineNo(handle); }
5597
    if (no == null) { return null }
5598
    if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
5599
    return line
5600
  }
5601
 
5602
  // The document is represented as a BTree consisting of leaves, with
5603
  // chunk of lines in them, and branches, with up to ten leaves or
5604
  // other branch nodes below them. The top node is always a branch
5605
  // node, and is the document object itself (meaning it has
5606
  // additional methods and properties).
5607
  //
5608
  // All nodes have parent links. The tree is used both to go from
5609
  // line numbers to line objects, and to go from objects to numbers.
5610
  // It also indexes by height, and is used to convert between height
5611
  // and line object, and to find the total height of the document.
5612
  //
5613
  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
5614
 
5615
  function LeafChunk(lines) {
5616
    this.lines = lines;
5617
    this.parent = null;
5618
    var height = 0;
5619
    for (var i = 0; i < lines.length; ++i) {
15152 obado 5620
      lines[i].parent = this;
14283 obado 5621
      height += lines[i].height;
5622
    }
5623
    this.height = height;
5624
  }
5625
 
5626
  LeafChunk.prototype = {
5627
    chunkSize: function() { return this.lines.length },
5628
 
5629
    // Remove the n lines at offset 'at'.
5630
    removeInner: function(at, n) {
5631
      for (var i = at, e = at + n; i < e; ++i) {
15152 obado 5632
        var line = this.lines[i];
5633
        this.height -= line.height;
14283 obado 5634
        cleanUpLine(line);
5635
        signalLater(line, "delete");
5636
      }
5637
      this.lines.splice(at, n);
5638
    },
5639
 
5640
    // Helper used to collapse a small branch into a single leaf.
5641
    collapse: function(lines) {
5642
      lines.push.apply(lines, this.lines);
5643
    },
5644
 
5645
    // Insert the given array of lines at offset 'at', count them as
5646
    // having the given height.
5647
    insertInner: function(at, lines, height) {
5648
      this.height += height;
5649
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
15152 obado 5650
      for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
14283 obado 5651
    },
5652
 
5653
    // Used to iterate over a part of the tree.
5654
    iterN: function(at, n, op) {
5655
      for (var e = at + n; at < e; ++at)
15152 obado 5656
        { if (op(this.lines[at])) { return true } }
14283 obado 5657
    }
5658
  };
5659
 
5660
  function BranchChunk(children) {
5661
    this.children = children;
5662
    var size = 0, height = 0;
5663
    for (var i = 0; i < children.length; ++i) {
5664
      var ch = children[i];
5665
      size += ch.chunkSize(); height += ch.height;
15152 obado 5666
      ch.parent = this;
14283 obado 5667
    }
5668
    this.size = size;
5669
    this.height = height;
5670
    this.parent = null;
5671
  }
5672
 
5673
  BranchChunk.prototype = {
5674
    chunkSize: function() { return this.size },
5675
 
5676
    removeInner: function(at, n) {
5677
      this.size -= n;
5678
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5679
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5680
        if (at < sz) {
5681
          var rm = Math.min(n, sz - at), oldHeight = child.height;
5682
          child.removeInner(at, rm);
15152 obado 5683
          this.height -= oldHeight - child.height;
5684
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
14283 obado 5685
          if ((n -= rm) == 0) { break }
5686
          at = 0;
5687
        } else { at -= sz; }
5688
      }
5689
      // If the result is smaller than 25 lines, ensure that it is a
5690
      // single leaf node.
5691
      if (this.size - n < 25 &&
5692
          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
5693
        var lines = [];
5694
        this.collapse(lines);
5695
        this.children = [new LeafChunk(lines)];
5696
        this.children[0].parent = this;
5697
      }
5698
    },
5699
 
5700
    collapse: function(lines) {
15152 obado 5701
      for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
14283 obado 5702
    },
5703
 
5704
    insertInner: function(at, lines, height) {
5705
      this.size += lines.length;
5706
      this.height += height;
5707
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5708
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5709
        if (at <= sz) {
5710
          child.insertInner(at, lines, height);
5711
          if (child.lines && child.lines.length > 50) {
5712
            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
5713
            // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
5714
            var remaining = child.lines.length % 25 + 25;
5715
            for (var pos = remaining; pos < child.lines.length;) {
5716
              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
5717
              child.height -= leaf.height;
15152 obado 5718
              this.children.splice(++i, 0, leaf);
5719
              leaf.parent = this;
14283 obado 5720
            }
5721
            child.lines = child.lines.slice(0, remaining);
15152 obado 5722
            this.maybeSpill();
14283 obado 5723
          }
5724
          break
5725
        }
5726
        at -= sz;
5727
      }
5728
    },
5729
 
5730
    // When a node has grown, check whether it should be split.
5731
    maybeSpill: function() {
5732
      if (this.children.length <= 10) { return }
5733
      var me = this;
5734
      do {
5735
        var spilled = me.children.splice(me.children.length - 5, 5);
5736
        var sibling = new BranchChunk(spilled);
5737
        if (!me.parent) { // Become the parent node
5738
          var copy = new BranchChunk(me.children);
5739
          copy.parent = me;
5740
          me.children = [copy, sibling];
5741
          me = copy;
5742
       } else {
5743
          me.size -= sibling.size;
5744
          me.height -= sibling.height;
5745
          var myIndex = indexOf(me.parent.children, me);
5746
          me.parent.children.splice(myIndex + 1, 0, sibling);
5747
        }
5748
        sibling.parent = me.parent;
5749
      } while (me.children.length > 10)
5750
      me.parent.maybeSpill();
5751
    },
5752
 
5753
    iterN: function(at, n, op) {
5754
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5755
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5756
        if (at < sz) {
5757
          var used = Math.min(n, sz - at);
5758
          if (child.iterN(at, used, op)) { return true }
5759
          if ((n -= used) == 0) { break }
5760
          at = 0;
5761
        } else { at -= sz; }
5762
      }
5763
    }
5764
  };
5765
 
5766
  // Line widgets are block elements displayed above or below a line.
5767
 
5768
  var LineWidget = function(doc, node, options) {
5769
    if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
15152 obado 5770
      { this[opt] = options[opt]; } } }
14283 obado 5771
    this.doc = doc;
5772
    this.node = node;
5773
  };
5774
 
5775
  LineWidget.prototype.clear = function () {
5776
    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5777
    if (no == null || !ws) { return }
15152 obado 5778
    for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
14283 obado 5779
    if (!ws.length) { line.widgets = null; }
5780
    var height = widgetHeight(this);
5781
    updateLineHeight(line, Math.max(0, line.height - height));
5782
    if (cm) {
5783
      runInOp(cm, function () {
5784
        adjustScrollWhenAboveVisible(cm, line, -height);
5785
        regLineChange(cm, no, "widget");
5786
      });
5787
      signalLater(cm, "lineWidgetCleared", cm, this, no);
5788
    }
5789
  };
5790
 
5791
  LineWidget.prototype.changed = function () {
5792
      var this$1 = this;
5793
 
5794
    var oldH = this.height, cm = this.doc.cm, line = this.line;
5795
    this.height = null;
5796
    var diff = widgetHeight(this) - oldH;
5797
    if (!diff) { return }
5798
    if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
5799
    if (cm) {
5800
      runInOp(cm, function () {
5801
        cm.curOp.forceUpdate = true;
5802
        adjustScrollWhenAboveVisible(cm, line, diff);
5803
        signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
5804
      });
5805
    }
5806
  };
5807
  eventMixin(LineWidget);
5808
 
5809
  function adjustScrollWhenAboveVisible(cm, line, diff) {
5810
    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5811
      { addToScrollTop(cm, diff); }
5812
  }
5813
 
5814
  function addLineWidget(doc, handle, node, options) {
5815
    var widget = new LineWidget(doc, node, options);
5816
    var cm = doc.cm;
5817
    if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
5818
    changeLine(doc, handle, "widget", function (line) {
5819
      var widgets = line.widgets || (line.widgets = []);
5820
      if (widget.insertAt == null) { widgets.push(widget); }
16493 obado 5821
      else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
14283 obado 5822
      widget.line = line;
5823
      if (cm && !lineIsHidden(doc, line)) {
5824
        var aboveVisible = heightAtLine(line) < doc.scrollTop;
5825
        updateLineHeight(line, line.height + widgetHeight(widget));
5826
        if (aboveVisible) { addToScrollTop(cm, widget.height); }
5827
        cm.curOp.forceUpdate = true;
5828
      }
5829
      return true
5830
    });
5831
    if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
5832
    return widget
5833
  }
5834
 
5835
  // TEXTMARKERS
5836
 
5837
  // Created with markText and setBookmark methods. A TextMarker is a
5838
  // handle that can be used to clear or find a marked position in the
5839
  // document. Line objects hold arrays (markedSpans) containing
5840
  // {from, to, marker} object pointing to such marker objects, and
5841
  // indicating that such a marker is present on that line. Multiple
5842
  // lines may point to the same marker when it spans across lines.
5843
  // The spans will have null for their from/to properties when the
5844
  // marker continues beyond the start/end of the line. Markers have
5845
  // links back to the lines they currently touch.
5846
 
5847
  // Collapsed markers have unique ids, in order to be able to order
5848
  // them, which is needed for uniquely determining an outer marker
5849
  // when they overlap (they may nest, but not partially overlap).
5850
  var nextMarkerId = 0;
5851
 
5852
  var TextMarker = function(doc, type) {
5853
    this.lines = [];
5854
    this.type = type;
5855
    this.doc = doc;
5856
    this.id = ++nextMarkerId;
5857
  };
5858
 
5859
  // Clear the marker.
5860
  TextMarker.prototype.clear = function () {
5861
    if (this.explicitlyCleared) { return }
5862
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
5863
    if (withOp) { startOperation(cm); }
5864
    if (hasHandler(this, "clear")) {
5865
      var found = this.find();
5866
      if (found) { signalLater(this, "clear", found.from, found.to); }
5867
    }
5868
    var min = null, max = null;
5869
    for (var i = 0; i < this.lines.length; ++i) {
15152 obado 5870
      var line = this.lines[i];
5871
      var span = getMarkedSpanFor(line.markedSpans, this);
5872
      if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
14283 obado 5873
      else if (cm) {
5874
        if (span.to != null) { max = lineNo(line); }
5875
        if (span.from != null) { min = lineNo(line); }
5876
      }
5877
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
15152 obado 5878
      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
14283 obado 5879
        { updateLineHeight(line, textHeight(cm.display)); }
5880
    }
5881
    if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
15152 obado 5882
      var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
14283 obado 5883
      if (len > cm.display.maxLineLength) {
5884
        cm.display.maxLine = visual;
5885
        cm.display.maxLineLength = len;
5886
        cm.display.maxLineChanged = true;
5887
      }
5888
    } }
5889
 
5890
    if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
5891
    this.lines.length = 0;
5892
    this.explicitlyCleared = true;
5893
    if (this.atomic && this.doc.cantEdit) {
5894
      this.doc.cantEdit = false;
5895
      if (cm) { reCheckSelection(cm.doc); }
5896
    }
5897
    if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
5898
    if (withOp) { endOperation(cm); }
5899
    if (this.parent) { this.parent.clear(); }
5900
  };
5901
 
5902
  // Find the position of the marker in the document. Returns a {from,
5903
  // to} object by default. Side can be passed to get a specific side
5904
  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5905
  // Pos objects returned contain a line object, rather than a line
5906
  // number (used to prevent looking up the same line twice).
5907
  TextMarker.prototype.find = function (side, lineObj) {
5908
    if (side == null && this.type == "bookmark") { side = 1; }
5909
    var from, to;
5910
    for (var i = 0; i < this.lines.length; ++i) {
15152 obado 5911
      var line = this.lines[i];
5912
      var span = getMarkedSpanFor(line.markedSpans, this);
14283 obado 5913
      if (span.from != null) {
5914
        from = Pos(lineObj ? line : lineNo(line), span.from);
5915
        if (side == -1) { return from }
5916
      }
5917
      if (span.to != null) {
5918
        to = Pos(lineObj ? line : lineNo(line), span.to);
5919
        if (side == 1) { return to }
5920
      }
5921
    }
5922
    return from && {from: from, to: to}
5923
  };
5924
 
5925
  // Signals that the marker's widget changed, and surrounding layout
5926
  // should be recomputed.
5927
  TextMarker.prototype.changed = function () {
5928
      var this$1 = this;
5929
 
5930
    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
5931
    if (!pos || !cm) { return }
5932
    runInOp(cm, function () {
5933
      var line = pos.line, lineN = lineNo(pos.line);
5934
      var view = findViewForLine(cm, lineN);
5935
      if (view) {
5936
        clearLineMeasurementCacheFor(view);
5937
        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
5938
      }
5939
      cm.curOp.updateMaxLine = true;
5940
      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5941
        var oldHeight = widget.height;
5942
        widget.height = null;
5943
        var dHeight = widgetHeight(widget) - oldHeight;
5944
        if (dHeight)
5945
          { updateLineHeight(line, line.height + dHeight); }
5946
      }
5947
      signalLater(cm, "markerChanged", cm, this$1);
5948
    });
5949
  };
5950
 
5951
  TextMarker.prototype.attachLine = function (line) {
5952
    if (!this.lines.length && this.doc.cm) {
5953
      var op = this.doc.cm.curOp;
5954
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5955
        { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
5956
    }
5957
    this.lines.push(line);
5958
  };
5959
 
5960
  TextMarker.prototype.detachLine = function (line) {
5961
    this.lines.splice(indexOf(this.lines, line), 1);
5962
    if (!this.lines.length && this.doc.cm) {
5963
      var op = this.doc.cm.curOp
5964
      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5965
    }
5966
  };
5967
  eventMixin(TextMarker);
5968
 
5969
  // Create a marker, wire it up to the right lines, and
5970
  function markText(doc, from, to, options, type) {
5971
    // Shared markers (across linked documents) are handled separately
5972
    // (markTextShared will call out to this again, once per
5973
    // document).
5974
    if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
5975
    // Ensure we are in an operation.
5976
    if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
5977
 
5978
    var marker = new TextMarker(doc, type), diff = cmp(from, to);
5979
    if (options) { copyObj(options, marker, false); }
5980
    // Don't connect empty markers unless clearWhenEmpty is false
5981
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
5982
      { return marker }
5983
    if (marker.replacedWith) {
5984
      // Showing up as a widget implies collapsed (widget replaces text)
5985
      marker.collapsed = true;
5986
      marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
5987
      if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
5988
      if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
5989
    }
5990
    if (marker.collapsed) {
5991
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
5992
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
5993
        { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
5994
      seeCollapsedSpans();
5995
    }
5996
 
5997
    if (marker.addToHistory)
5998
      { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
5999
 
6000
    var curLine = from.line, cm = doc.cm, updateMaxLine;
6001
    doc.iter(curLine, to.line + 1, function (line) {
6002
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6003
        { updateMaxLine = true; }
6004
      if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
6005
      addMarkedSpan(line, new MarkedSpan(marker,
6006
                                         curLine == from.line ? from.ch : null,
16493 obado 6007
                                         curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
14283 obado 6008
      ++curLine;
6009
    });
6010
    // lineIsHidden depends on the presence of the spans, so needs a second pass
6011
    if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
6012
      if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
6013
    }); }
6014
 
6015
    if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
6016
 
6017
    if (marker.readOnly) {
6018
      seeReadOnlySpans();
6019
      if (doc.history.done.length || doc.history.undone.length)
6020
        { doc.clearHistory(); }
6021
    }
6022
    if (marker.collapsed) {
6023
      marker.id = ++nextMarkerId;
6024
      marker.atomic = true;
6025
    }
6026
    if (cm) {
6027
      // Sync editor state
6028
      if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
6029
      if (marker.collapsed)
6030
        { regChange(cm, from.line, to.line + 1); }
6031
      else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
6032
               marker.attributes || marker.title)
6033
        { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
6034
      if (marker.atomic) { reCheckSelection(cm.doc); }
6035
      signalLater(cm, "markerAdded", cm, marker);
6036
    }
6037
    return marker
6038
  }
6039
 
6040
  // SHARED TEXTMARKERS
6041
 
6042
  // A shared marker spans multiple linked documents. It is
6043
  // implemented as a meta-marker-object controlling multiple normal
6044
  // markers.
6045
  var SharedTextMarker = function(markers, primary) {
6046
    this.markers = markers;
6047
    this.primary = primary;
6048
    for (var i = 0; i < markers.length; ++i)
15152 obado 6049
      { markers[i].parent = this; }
14283 obado 6050
  };
6051
 
6052
  SharedTextMarker.prototype.clear = function () {
6053
    if (this.explicitlyCleared) { return }
6054
    this.explicitlyCleared = true;
6055
    for (var i = 0; i < this.markers.length; ++i)
15152 obado 6056
      { this.markers[i].clear(); }
14283 obado 6057
    signalLater(this, "clear");
6058
  };
6059
 
6060
  SharedTextMarker.prototype.find = function (side, lineObj) {
6061
    return this.primary.find(side, lineObj)
6062
  };
6063
  eventMixin(SharedTextMarker);
6064
 
6065
  function markTextShared(doc, from, to, options, type) {
6066
    options = copyObj(options);
6067
    options.shared = false;
6068
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6069
    var widget = options.widgetNode;
6070
    linkedDocs(doc, function (doc) {
6071
      if (widget) { options.widgetNode = widget.cloneNode(true); }
6072
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6073
      for (var i = 0; i < doc.linked.length; ++i)
6074
        { if (doc.linked[i].isParent) { return } }
6075
      primary = lst(markers);
6076
    });
6077
    return new SharedTextMarker(markers, primary)
6078
  }
6079
 
6080
  function findSharedMarkers(doc) {
6081
    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
6082
  }
6083
 
6084
  function copySharedMarkers(doc, markers) {
6085
    for (var i = 0; i < markers.length; i++) {
6086
      var marker = markers[i], pos = marker.find();
6087
      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6088
      if (cmp(mFrom, mTo)) {
6089
        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6090
        marker.markers.push(subMark);
6091
        subMark.parent = marker;
6092
      }
6093
    }
6094
  }
6095
 
6096
  function detachSharedMarkers(markers) {
6097
    var loop = function ( i ) {
6098
      var marker = markers[i], linked = [marker.primary.doc];
6099
      linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
6100
      for (var j = 0; j < marker.markers.length; j++) {
6101
        var subMarker = marker.markers[j];
6102
        if (indexOf(linked, subMarker.doc) == -1) {
6103
          subMarker.parent = null;
6104
          marker.markers.splice(j--, 1);
6105
        }
6106
      }
6107
    };
6108
 
6109
    for (var i = 0; i < markers.length; i++) loop( i );
6110
  }
6111
 
6112
  var nextDocId = 0;
6113
  var Doc = function(text, mode, firstLine, lineSep, direction) {
6114
    if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
6115
    if (firstLine == null) { firstLine = 0; }
6116
 
6117
    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
6118
    this.first = firstLine;
6119
    this.scrollTop = this.scrollLeft = 0;
6120
    this.cantEdit = false;
6121
    this.cleanGeneration = 1;
6122
    this.modeFrontier = this.highlightFrontier = firstLine;
6123
    var start = Pos(firstLine, 0);
6124
    this.sel = simpleSelection(start);
6125
    this.history = new History(null);
6126
    this.id = ++nextDocId;
6127
    this.modeOption = mode;
6128
    this.lineSep = lineSep;
6129
    this.direction = (direction == "rtl") ? "rtl" : "ltr";
6130
    this.extend = false;
6131
 
6132
    if (typeof text == "string") { text = this.splitLines(text); }
6133
    updateDoc(this, {from: start, to: start, text: text});
6134
    setSelection(this, simpleSelection(start), sel_dontScroll);
6135
  };
6136
 
6137
  Doc.prototype = createObj(BranchChunk.prototype, {
6138
    constructor: Doc,
6139
    // Iterate over the document. Supports two forms -- with only one
6140
    // argument, it calls that for each line in the document. With
6141
    // three, it iterates over the range given by the first two (with
6142
    // the second being non-inclusive).
6143
    iter: function(from, to, op) {
6144
      if (op) { this.iterN(from - this.first, to - from, op); }
6145
      else { this.iterN(this.first, this.first + this.size, from); }
6146
    },
6147
 
6148
    // Non-public interface for adding and removing lines.
6149
    insert: function(at, lines) {
6150
      var height = 0;
6151
      for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
6152
      this.insertInner(at - this.first, lines, height);
6153
    },
6154
    remove: function(at, n) { this.removeInner(at - this.first, n); },
6155
 
6156
    // From here, the methods are part of the public interface. Most
6157
    // are also available from CodeMirror (editor) instances.
6158
 
6159
    getValue: function(lineSep) {
6160
      var lines = getLines(this, this.first, this.first + this.size);
6161
      if (lineSep === false) { return lines }
6162
      return lines.join(lineSep || this.lineSeparator())
6163
    },
6164
    setValue: docMethodOp(function(code) {
6165
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
6166
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6167
                        text: this.splitLines(code), origin: "setValue", full: true}, true);
6168
      if (this.cm) { scrollToCoords(this.cm, 0, 0); }
6169
      setSelection(this, simpleSelection(top), sel_dontScroll);
6170
    }),
6171
    replaceRange: function(code, from, to, origin) {
6172
      from = clipPos(this, from);
6173
      to = to ? clipPos(this, to) : from;
6174
      replaceRange(this, code, from, to, origin);
6175
    },
6176
    getRange: function(from, to, lineSep) {
6177
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6178
      if (lineSep === false) { return lines }
16493 obado 6179
      if (lineSep === '') { return lines.join('') }
14283 obado 6180
      return lines.join(lineSep || this.lineSeparator())
6181
    },
6182
 
6183
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6184
 
6185
    getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6186
    getLineNumber: function(line) {return lineNo(line)},
6187
 
6188
    getLineHandleVisualStart: function(line) {
6189
      if (typeof line == "number") { line = getLine(this, line); }
6190
      return visualLine(line)
6191
    },
6192
 
6193
    lineCount: function() {return this.size},
6194
    firstLine: function() {return this.first},
6195
    lastLine: function() {return this.first + this.size - 1},
6196
 
6197
    clipPos: function(pos) {return clipPos(this, pos)},
6198
 
6199
    getCursor: function(start) {
15152 obado 6200
      var range = this.sel.primary(), pos;
6201
      if (start == null || start == "head") { pos = range.head; }
6202
      else if (start == "anchor") { pos = range.anchor; }
6203
      else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
6204
      else { pos = range.from(); }
14283 obado 6205
      return pos
6206
    },
6207
    listSelections: function() { return this.sel.ranges },
6208
    somethingSelected: function() {return this.sel.somethingSelected()},
6209
 
6210
    setCursor: docMethodOp(function(line, ch, options) {
6211
      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6212
    }),
6213
    setSelection: docMethodOp(function(anchor, head, options) {
6214
      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6215
    }),
6216
    extendSelection: docMethodOp(function(head, other, options) {
6217
      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6218
    }),
6219
    extendSelections: docMethodOp(function(heads, options) {
6220
      extendSelections(this, clipPosArray(this, heads), options);
6221
    }),
6222
    extendSelectionsBy: docMethodOp(function(f, options) {
6223
      var heads = map(this.sel.ranges, f);
6224
      extendSelections(this, clipPosArray(this, heads), options);
6225
    }),
6226
    setSelections: docMethodOp(function(ranges, primary, options) {
6227
      if (!ranges.length) { return }
6228
      var out = [];
6229
      for (var i = 0; i < ranges.length; i++)
15152 obado 6230
        { out[i] = new Range(clipPos(this, ranges[i].anchor),
16493 obado 6231
                           clipPos(this, ranges[i].head || ranges[i].anchor)); }
14283 obado 6232
      if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
6233
      setSelection(this, normalizeSelection(this.cm, out, primary), options);
6234
    }),
6235
    addSelection: docMethodOp(function(anchor, head, options) {
6236
      var ranges = this.sel.ranges.slice(0);
6237
      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6238
      setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
6239
    }),
6240
 
6241
    getSelection: function(lineSep) {
6242
      var ranges = this.sel.ranges, lines;
6243
      for (var i = 0; i < ranges.length; i++) {
15152 obado 6244
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
14283 obado 6245
        lines = lines ? lines.concat(sel) : sel;
6246
      }
6247
      if (lineSep === false) { return lines }
6248
      else { return lines.join(lineSep || this.lineSeparator()) }
6249
    },
6250
    getSelections: function(lineSep) {
6251
      var parts = [], ranges = this.sel.ranges;
6252
      for (var i = 0; i < ranges.length; i++) {
15152 obado 6253
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6254
        if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
14283 obado 6255
        parts[i] = sel;
6256
      }
6257
      return parts
6258
    },
6259
    replaceSelection: function(code, collapse, origin) {
6260
      var dup = [];
6261
      for (var i = 0; i < this.sel.ranges.length; i++)
6262
        { dup[i] = code; }
6263
      this.replaceSelections(dup, collapse, origin || "+input");
6264
    },
6265
    replaceSelections: docMethodOp(function(code, collapse, origin) {
6266
      var changes = [], sel = this.sel;
6267
      for (var i = 0; i < sel.ranges.length; i++) {
15152 obado 6268
        var range = sel.ranges[i];
6269
        changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
14283 obado 6270
      }
6271
      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6272
      for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
15152 obado 6273
        { makeChange(this, changes[i$1]); }
14283 obado 6274
      if (newSel) { setSelectionReplaceHistory(this, newSel); }
6275
      else if (this.cm) { ensureCursorVisible(this.cm); }
6276
    }),
6277
    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6278
    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6279
    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6280
    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6281
 
6282
    setExtending: function(val) {this.extend = val;},
6283
    getExtending: function() {return this.extend},
6284
 
6285
    historySize: function() {
6286
      var hist = this.history, done = 0, undone = 0;
6287
      for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
6288
      for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
6289
      return {undo: done, redo: undone}
6290
    },
15152 obado 6291
    clearHistory: function() {
6292
      var this$1 = this;
14283 obado 6293
 
16493 obado 6294
      this.history = new History(this.history);
15152 obado 6295
      linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
6296
    },
6297
 
14283 obado 6298
    markClean: function() {
6299
      this.cleanGeneration = this.changeGeneration(true);
6300
    },
6301
    changeGeneration: function(forceSplit) {
6302
      if (forceSplit)
6303
        { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
6304
      return this.history.generation
6305
    },
6306
    isClean: function (gen) {
6307
      return this.history.generation == (gen || this.cleanGeneration)
6308
    },
6309
 
6310
    getHistory: function() {
6311
      return {done: copyHistoryArray(this.history.done),
6312
              undone: copyHistoryArray(this.history.undone)}
6313
    },
6314
    setHistory: function(histData) {
16493 obado 6315
      var hist = this.history = new History(this.history);
14283 obado 6316
      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6317
      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6318
    },
6319
 
6320
    setGutterMarker: docMethodOp(function(line, gutterID, value) {
6321
      return changeLine(this, line, "gutter", function (line) {
6322
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
6323
        markers[gutterID] = value;
6324
        if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
6325
        return true
6326
      })
6327
    }),
6328
 
6329
    clearGutter: docMethodOp(function(gutterID) {
6330
      var this$1 = this;
6331
 
6332
      this.iter(function (line) {
6333
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
6334
          changeLine(this$1, line, "gutter", function () {
6335
            line.gutterMarkers[gutterID] = null;
6336
            if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
6337
            return true
6338
          });
6339
        }
6340
      });
6341
    }),
6342
 
6343
    lineInfo: function(line) {
6344
      var n;
6345
      if (typeof line == "number") {
6346
        if (!isLine(this, line)) { return null }
6347
        n = line;
6348
        line = getLine(this, line);
6349
        if (!line) { return null }
6350
      } else {
6351
        n = lineNo(line);
6352
        if (n == null) { return null }
6353
      }
6354
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
6355
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
6356
              widgets: line.widgets}
6357
    },
6358
 
6359
    addLineClass: docMethodOp(function(handle, where, cls) {
6360
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6361
        var prop = where == "text" ? "textClass"
6362
                 : where == "background" ? "bgClass"
6363
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6364
        if (!line[prop]) { line[prop] = cls; }
6365
        else if (classTest(cls).test(line[prop])) { return false }
6366
        else { line[prop] += " " + cls; }
6367
        return true
6368
      })
6369
    }),
6370
    removeLineClass: docMethodOp(function(handle, where, cls) {
6371
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6372
        var prop = where == "text" ? "textClass"
6373
                 : where == "background" ? "bgClass"
6374
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6375
        var cur = line[prop];
6376
        if (!cur) { return false }
6377
        else if (cls == null) { line[prop] = null; }
6378
        else {
6379
          var found = cur.match(classTest(cls));
6380
          if (!found) { return false }
6381
          var end = found.index + found[0].length;
6382
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
6383
        }
6384
        return true
6385
      })
6386
    }),
6387
 
6388
    addLineWidget: docMethodOp(function(handle, node, options) {
6389
      return addLineWidget(this, handle, node, options)
6390
    }),
6391
    removeLineWidget: function(widget) { widget.clear(); },
6392
 
6393
    markText: function(from, to, options) {
6394
      return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
6395
    },
6396
    setBookmark: function(pos, options) {
6397
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6398
                      insertLeft: options && options.insertLeft,
6399
                      clearWhenEmpty: false, shared: options && options.shared,
6400
                      handleMouseEvents: options && options.handleMouseEvents};
6401
      pos = clipPos(this, pos);
6402
      return markText(this, pos, pos, realOpts, "bookmark")
6403
    },
6404
    findMarksAt: function(pos) {
6405
      pos = clipPos(this, pos);
6406
      var markers = [], spans = getLine(this, pos.line).markedSpans;
6407
      if (spans) { for (var i = 0; i < spans.length; ++i) {
6408
        var span = spans[i];
6409
        if ((span.from == null || span.from <= pos.ch) &&
6410
            (span.to == null || span.to >= pos.ch))
6411
          { markers.push(span.marker.parent || span.marker); }
6412
      } }
6413
      return markers
6414
    },
6415
    findMarks: function(from, to, filter) {
6416
      from = clipPos(this, from); to = clipPos(this, to);
15152 obado 6417
      var found = [], lineNo = from.line;
14283 obado 6418
      this.iter(from.line, to.line + 1, function (line) {
6419
        var spans = line.markedSpans;
6420
        if (spans) { for (var i = 0; i < spans.length; i++) {
6421
          var span = spans[i];
15152 obado 6422
          if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
6423
                span.from == null && lineNo != from.line ||
6424
                span.from != null && lineNo == to.line && span.from >= to.ch) &&
14283 obado 6425
              (!filter || filter(span.marker)))
6426
            { found.push(span.marker.parent || span.marker); }
6427
        } }
15152 obado 6428
        ++lineNo;
14283 obado 6429
      });
6430
      return found
6431
    },
6432
    getAllMarks: function() {
6433
      var markers = [];
6434
      this.iter(function (line) {
6435
        var sps = line.markedSpans;
6436
        if (sps) { for (var i = 0; i < sps.length; ++i)
6437
          { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
6438
      });
6439
      return markers
6440
    },
6441
 
6442
    posFromIndex: function(off) {
15152 obado 6443
      var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
14283 obado 6444
      this.iter(function (line) {
6445
        var sz = line.text.length + sepSize;
6446
        if (sz > off) { ch = off; return true }
6447
        off -= sz;
15152 obado 6448
        ++lineNo;
14283 obado 6449
      });
15152 obado 6450
      return clipPos(this, Pos(lineNo, ch))
14283 obado 6451
    },
6452
    indexFromPos: function (coords) {
6453
      coords = clipPos(this, coords);
6454
      var index = coords.ch;
6455
      if (coords.line < this.first || coords.ch < 0) { return 0 }
6456
      var sepSize = this.lineSeparator().length;
6457
      this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
6458
        index += line.text.length + sepSize;
6459
      });
6460
      return index
6461
    },
6462
 
6463
    copy: function(copyHistory) {
6464
      var doc = new Doc(getLines(this, this.first, this.first + this.size),
6465
                        this.modeOption, this.first, this.lineSep, this.direction);
6466
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6467
      doc.sel = this.sel;
6468
      doc.extend = false;
6469
      if (copyHistory) {
6470
        doc.history.undoDepth = this.history.undoDepth;
6471
        doc.setHistory(this.getHistory());
6472
      }
6473
      return doc
6474
    },
6475
 
6476
    linkedDoc: function(options) {
6477
      if (!options) { options = {}; }
6478
      var from = this.first, to = this.first + this.size;
6479
      if (options.from != null && options.from > from) { from = options.from; }
6480
      if (options.to != null && options.to < to) { to = options.to; }
6481
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
6482
      if (options.sharedHist) { copy.history = this.history
6483
      ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6484
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6485
      copySharedMarkers(copy, findSharedMarkers(this));
6486
      return copy
6487
    },
6488
    unlinkDoc: function(other) {
6489
      if (other instanceof CodeMirror) { other = other.doc; }
6490
      if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
15152 obado 6491
        var link = this.linked[i];
14283 obado 6492
        if (link.doc != other) { continue }
15152 obado 6493
        this.linked.splice(i, 1);
6494
        other.unlinkDoc(this);
6495
        detachSharedMarkers(findSharedMarkers(this));
14283 obado 6496
        break
6497
      } }
6498
      // If the histories were shared, split them again
6499
      if (other.history == this.history) {
6500
        var splitIds = [other.id];
6501
        linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
6502
        other.history = new History(null);
6503
        other.history.done = copyHistoryArray(this.history.done, splitIds);
6504
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6505
      }
6506
    },
6507
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
6508
 
6509
    getMode: function() {return this.mode},
6510
    getEditor: function() {return this.cm},
6511
 
6512
    splitLines: function(str) {
6513
      if (this.lineSep) { return str.split(this.lineSep) }
6514
      return splitLinesAuto(str)
6515
    },
6516
    lineSeparator: function() { return this.lineSep || "\n" },
6517
 
6518
    setDirection: docMethodOp(function (dir) {
6519
      if (dir != "rtl") { dir = "ltr"; }
6520
      if (dir == this.direction) { return }
6521
      this.direction = dir;
6522
      this.iter(function (line) { return line.order = null; });
6523
      if (this.cm) { directionChanged(this.cm); }
6524
    })
6525
  });
6526
 
6527
  // Public alias.
6528
  Doc.prototype.eachLine = Doc.prototype.iter;
6529
 
6530
  // Kludge to work around strange IE behavior where it'll sometimes
6531
  // re-fire a series of drag-related events right after the drop (#1551)
6532
  var lastDrop = 0;
6533
 
6534
  function onDrop(e) {
6535
    var cm = this;
6536
    clearDragCursor(cm);
6537
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
6538
      { return }
6539
    e_preventDefault(e);
6540
    if (ie) { lastDrop = +new Date; }
6541
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
6542
    if (!pos || cm.isReadOnly()) { return }
6543
    // Might be a file drop, in which case we simply extract the text
6544
    // and insert it.
6545
    if (files && files.length && window.FileReader && window.File) {
6546
      var n = files.length, text = Array(n), read = 0;
15152 obado 6547
      var markAsReadAndPasteIfAllFilesAreRead = function () {
6548
        if (++read == n) {
6549
          operation(cm, function () {
14283 obado 6550
            pos = clipPos(cm.doc, pos);
6551
            var change = {from: pos, to: pos,
15152 obado 6552
                          text: cm.doc.splitLines(
6553
                              text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
14283 obado 6554
                          origin: "paste"};
6555
            makeChange(cm.doc, change);
15152 obado 6556
            setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
6557
          })();
6558
        }
6559
      };
6560
      var readTextFromFile = function (file, i) {
6561
        if (cm.options.allowDropFileTypes &&
6562
            indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
6563
          markAsReadAndPasteIfAllFilesAreRead();
6564
          return
6565
        }
6566
        var reader = new FileReader;
6567
        reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
6568
        reader.onload = function () {
6569
          var content = reader.result;
6570
          if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
6571
            markAsReadAndPasteIfAllFilesAreRead();
6572
            return
14283 obado 6573
          }
15152 obado 6574
          text[i] = content;
6575
          markAsReadAndPasteIfAllFilesAreRead();
6576
        };
14283 obado 6577
        reader.readAsText(file);
6578
      };
15152 obado 6579
      for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
14283 obado 6580
    } else { // Normal drop
6581
      // Don't do a replace if the drop happened inside of the selected text.
6582
      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
6583
        cm.state.draggingText(e);
6584
        // Ensure the editor is re-focused
6585
        setTimeout(function () { return cm.display.input.focus(); }, 20);
6586
        return
6587
      }
6588
      try {
6589
        var text$1 = e.dataTransfer.getData("Text");
6590
        if (text$1) {
6591
          var selected;
6592
          if (cm.state.draggingText && !cm.state.draggingText.copy)
6593
            { selected = cm.listSelections(); }
6594
          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
6595
          if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
6596
            { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
6597
          cm.replaceSelection(text$1, "around", "paste");
6598
          cm.display.input.focus();
6599
        }
6600
      }
15332 obado 6601
      catch(e$1){}
14283 obado 6602
    }
6603
  }
6604
 
6605
  function onDragStart(cm, e) {
6606
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
6607
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
6608
 
6609
    e.dataTransfer.setData("Text", cm.getSelection());
6610
    e.dataTransfer.effectAllowed = "copyMove";
6611
 
6612
    // Use dummy image instead of default browsers image.
6613
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
6614
    if (e.dataTransfer.setDragImage && !safari) {
6615
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
6616
      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
6617
      if (presto) {
6618
        img.width = img.height = 1;
6619
        cm.display.wrapper.appendChild(img);
6620
        // Force a relayout, or Opera won't use our image for some obscure reason
6621
        img._top = img.offsetTop;
6622
      }
6623
      e.dataTransfer.setDragImage(img, 0, 0);
6624
      if (presto) { img.parentNode.removeChild(img); }
6625
    }
6626
  }
6627
 
6628
  function onDragOver(cm, e) {
6629
    var pos = posFromMouse(cm, e);
6630
    if (!pos) { return }
6631
    var frag = document.createDocumentFragment();
6632
    drawSelectionCursor(cm, pos, frag);
6633
    if (!cm.display.dragCursor) {
6634
      cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
6635
      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
6636
    }
6637
    removeChildrenAndAdd(cm.display.dragCursor, frag);
6638
  }
6639
 
6640
  function clearDragCursor(cm) {
6641
    if (cm.display.dragCursor) {
6642
      cm.display.lineSpace.removeChild(cm.display.dragCursor);
6643
      cm.display.dragCursor = null;
6644
    }
6645
  }
6646
 
6647
  // These must be handled carefully, because naively registering a
6648
  // handler for each editor will cause the editors to never be
6649
  // garbage collected.
6650
 
6651
  function forEachCodeMirror(f) {
6652
    if (!document.getElementsByClassName) { return }
6653
    var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
6654
    for (var i = 0; i < byClass.length; i++) {
6655
      var cm = byClass[i].CodeMirror;
6656
      if (cm) { editors.push(cm); }
6657
    }
6658
    if (editors.length) { editors[0].operation(function () {
6659
      for (var i = 0; i < editors.length; i++) { f(editors[i]); }
6660
    }); }
6661
  }
6662
 
6663
  var globalsRegistered = false;
6664
  function ensureGlobalHandlers() {
6665
    if (globalsRegistered) { return }
6666
    registerGlobalHandlers();
6667
    globalsRegistered = true;
6668
  }
6669
  function registerGlobalHandlers() {
6670
    // When the window resizes, we need to refresh active editors.
6671
    var resizeTimer;
6672
    on(window, "resize", function () {
6673
      if (resizeTimer == null) { resizeTimer = setTimeout(function () {
6674
        resizeTimer = null;
6675
        forEachCodeMirror(onResize);
6676
      }, 100); }
6677
    });
6678
    // When the window loses focus, we want to show the editor as blurred
6679
    on(window, "blur", function () { return forEachCodeMirror(onBlur); });
6680
  }
6681
  // Called when the window resizes
6682
  function onResize(cm) {
6683
    var d = cm.display;
6684
    // Might be a text scaling operation, clear size caches.
6685
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
6686
    d.scrollbarsClipped = false;
6687
    cm.setSize();
6688
  }
6689
 
6690
  var keyNames = {
6691
    3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
6692
    19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
6693
    36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
6694
    46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
6695
    106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
6696
    173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
15332 obado 6697
    221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
14283 obado 6698
    63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
6699
  };
6700
 
6701
  // Number keys
6702
  for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
6703
  // Alphabetic keys
6704
  for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
6705
  // Function keys
6706
  for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
6707
 
6708
  var keyMap = {};
6709
 
6710
  keyMap.basic = {
6711
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
6712
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
6713
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
6714
    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
6715
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
6716
    "Esc": "singleSelection"
6717
  };
6718
  // Note that the save and find-related commands aren't defined by
6719
  // default. User code or addons can define them. Unknown commands
6720
  // are simply ignored.
6721
  keyMap.pcDefault = {
6722
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
6723
    "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
6724
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
6725
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
6726
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
6727
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
6728
    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
6729
    "fallthrough": "basic"
6730
  };
6731
  // Very basic readline/emacs-style bindings, which are standard on Mac.
6732
  keyMap.emacsy = {
6733
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
16493 obado 6734
    "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
6735
    "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
6736
    "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
14283 obado 6737
  };
6738
  keyMap.macDefault = {
6739
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
6740
    "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
6741
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
6742
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
6743
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
6744
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
6745
    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
6746
    "fallthrough": ["basic", "emacsy"]
6747
  };
6748
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
6749
 
6750
  // KEYMAP DISPATCH
6751
 
6752
  function normalizeKeyName(name) {
6753
    var parts = name.split(/-(?!$)/);
6754
    name = parts[parts.length - 1];
6755
    var alt, ctrl, shift, cmd;
6756
    for (var i = 0; i < parts.length - 1; i++) {
6757
      var mod = parts[i];
6758
      if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
6759
      else if (/^a(lt)?$/i.test(mod)) { alt = true; }
6760
      else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
6761
      else if (/^s(hift)?$/i.test(mod)) { shift = true; }
6762
      else { throw new Error("Unrecognized modifier name: " + mod) }
6763
    }
6764
    if (alt) { name = "Alt-" + name; }
6765
    if (ctrl) { name = "Ctrl-" + name; }
6766
    if (cmd) { name = "Cmd-" + name; }
6767
    if (shift) { name = "Shift-" + name; }
6768
    return name
6769
  }
6770
 
6771
  // This is a kludge to keep keymaps mostly working as raw objects
6772
  // (backwards compatibility) while at the same time support features
6773
  // like normalization and multi-stroke key bindings. It compiles a
6774
  // new normalized keymap, and then updates the old object to reflect
6775
  // this.
6776
  function normalizeKeyMap(keymap) {
6777
    var copy = {};
6778
    for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
6779
      var value = keymap[keyname];
6780
      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
6781
      if (value == "...") { delete keymap[keyname]; continue }
6782
 
6783
      var keys = map(keyname.split(" "), normalizeKeyName);
6784
      for (var i = 0; i < keys.length; i++) {
6785
        var val = (void 0), name = (void 0);
6786
        if (i == keys.length - 1) {
6787
          name = keys.join(" ");
6788
          val = value;
6789
        } else {
6790
          name = keys.slice(0, i + 1).join(" ");
6791
          val = "...";
6792
        }
6793
        var prev = copy[name];
6794
        if (!prev) { copy[name] = val; }
6795
        else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
6796
      }
6797
      delete keymap[keyname];
6798
    } }
6799
    for (var prop in copy) { keymap[prop] = copy[prop]; }
6800
    return keymap
6801
  }
6802
 
15152 obado 6803
  function lookupKey(key, map, handle, context) {
6804
    map = getKeyMap(map);
6805
    var found = map.call ? map.call(key, context) : map[key];
14283 obado 6806
    if (found === false) { return "nothing" }
6807
    if (found === "...") { return "multi" }
6808
    if (found != null && handle(found)) { return "handled" }
6809
 
15152 obado 6810
    if (map.fallthrough) {
6811
      if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
6812
        { return lookupKey(key, map.fallthrough, handle, context) }
6813
      for (var i = 0; i < map.fallthrough.length; i++) {
6814
        var result = lookupKey(key, map.fallthrough[i], handle, context);
14283 obado 6815
        if (result) { return result }
6816
      }
6817
    }
6818
  }
6819
 
6820
  // Modifier key presses don't count as 'real' key presses for the
6821
  // purpose of keymap fallthrough.
6822
  function isModifierKey(value) {
6823
    var name = typeof value == "string" ? value : keyNames[value.keyCode];
6824
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
6825
  }
6826
 
6827
  function addModifierNames(name, event, noShift) {
6828
    var base = name;
6829
    if (event.altKey && base != "Alt") { name = "Alt-" + name; }
6830
    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
15332 obado 6831
    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
14283 obado 6832
    if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
6833
    return name
6834
  }
6835
 
6836
  // Look up the name of a key as indicated by an event object.
6837
  function keyName(event, noShift) {
6838
    if (presto && event.keyCode == 34 && event["char"]) { return false }
6839
    var name = keyNames[event.keyCode];
6840
    if (name == null || event.altGraphKey) { return false }
6841
    // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
6842
    // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
6843
    if (event.keyCode == 3 && event.code) { name = event.code; }
6844
    return addModifierNames(name, event, noShift)
6845
  }
6846
 
6847
  function getKeyMap(val) {
6848
    return typeof val == "string" ? keyMap[val] : val
6849
  }
6850
 
6851
  // Helper for deleting text near the selection(s), used to implement
6852
  // backspace, delete, and similar functionality.
6853
  function deleteNearSelection(cm, compute) {
6854
    var ranges = cm.doc.sel.ranges, kill = [];
6855
    // Build up a set of ranges to kill first, merging overlapping
6856
    // ranges.
6857
    for (var i = 0; i < ranges.length; i++) {
6858
      var toKill = compute(ranges[i]);
6859
      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
6860
        var replaced = kill.pop();
6861
        if (cmp(replaced.from, toKill.from) < 0) {
6862
          toKill.from = replaced.from;
6863
          break
6864
        }
6865
      }
6866
      kill.push(toKill);
6867
    }
6868
    // Next, remove those actual ranges.
6869
    runInOp(cm, function () {
6870
      for (var i = kill.length - 1; i >= 0; i--)
6871
        { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
6872
      ensureCursorVisible(cm);
6873
    });
6874
  }
6875
 
6876
  function moveCharLogically(line, ch, dir) {
6877
    var target = skipExtendingChars(line.text, ch + dir, dir);
6878
    return target < 0 || target > line.text.length ? null : target
6879
  }
6880
 
6881
  function moveLogically(line, start, dir) {
6882
    var ch = moveCharLogically(line, start.ch, dir);
6883
    return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
6884
  }
6885
 
6886
  function endOfLine(visually, cm, lineObj, lineNo, dir) {
6887
    if (visually) {
15152 obado 6888
      if (cm.doc.direction == "rtl") { dir = -dir; }
14283 obado 6889
      var order = getOrder(lineObj, cm.doc.direction);
6890
      if (order) {
6891
        var part = dir < 0 ? lst(order) : order[0];
6892
        var moveInStorageOrder = (dir < 0) == (part.level == 1);
6893
        var sticky = moveInStorageOrder ? "after" : "before";
6894
        var ch;
6895
        // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
6896
        // it could be that the last bidi part is not on the last visual line,
6897
        // since visual lines contain content order-consecutive chunks.
6898
        // Thus, in rtl, we are looking for the first (content-order) character
6899
        // in the rtl chunk that is on the last line (that is, the same line
6900
        // as the last (content-order) character).
6901
        if (part.level > 0 || cm.doc.direction == "rtl") {
6902
          var prep = prepareMeasureForLine(cm, lineObj);
6903
          ch = dir < 0 ? lineObj.text.length - 1 : 0;
6904
          var targetTop = measureCharPrepared(cm, prep, ch).top;
6905
          ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
6906
          if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
6907
        } else { ch = dir < 0 ? part.to : part.from; }
6908
        return new Pos(lineNo, ch, sticky)
6909
      }
6910
    }
6911
    return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6912
  }
6913
 
6914
  function moveVisually(cm, line, start, dir) {
6915
    var bidi = getOrder(line, cm.doc.direction);
6916
    if (!bidi) { return moveLogically(line, start, dir) }
6917
    if (start.ch >= line.text.length) {
6918
      start.ch = line.text.length;
6919
      start.sticky = "before";
6920
    } else if (start.ch <= 0) {
6921
      start.ch = 0;
6922
      start.sticky = "after";
6923
    }
6924
    var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
6925
    if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
6926
      // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
6927
      // nothing interesting happens.
6928
      return moveLogically(line, start, dir)
6929
    }
6930
 
6931
    var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
6932
    var prep;
6933
    var getWrappedLineExtent = function (ch) {
6934
      if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
6935
      prep = prep || prepareMeasureForLine(cm, line);
6936
      return wrappedLineExtentChar(cm, line, prep, ch)
6937
    };
6938
    var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
6939
 
6940
    if (cm.doc.direction == "rtl" || part.level == 1) {
6941
      var moveInStorageOrder = (part.level == 1) == (dir < 0);
6942
      var ch = mv(start, moveInStorageOrder ? 1 : -1);
6943
      if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
6944
        // Case 2: We move within an rtl part or in an rtl editor on the same visual line
6945
        var sticky = moveInStorageOrder ? "before" : "after";
6946
        return new Pos(start.line, ch, sticky)
6947
      }
6948
    }
6949
 
6950
    // Case 3: Could not move within this bidi part in this visual line, so leave
6951
    // the current bidi part
6952
 
6953
    var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
6954
      var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
6955
        ? new Pos(start.line, mv(ch, 1), "before")
6956
        : new Pos(start.line, ch, "after"); };
6957
 
6958
      for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
6959
        var part = bidi[partPos];
6960
        var moveInStorageOrder = (dir > 0) == (part.level != 1);
6961
        var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
6962
        if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
6963
        ch = moveInStorageOrder ? part.from : mv(part.to, -1);
6964
        if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
6965
      }
6966
    };
6967
 
6968
    // Case 3a: Look for other bidi parts on the same visual line
6969
    var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
6970
    if (res) { return res }
6971
 
6972
    // Case 3b: Look for other bidi parts on the next visual line
6973
    var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
6974
    if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
6975
      res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
6976
      if (res) { return res }
6977
    }
6978
 
6979
    // Case 4: Nowhere to move
6980
    return null
6981
  }
6982
 
6983
  // Commands are parameter-less actions that can be performed on an
6984
  // editor, mostly used for keybindings.
6985
  var commands = {
6986
    selectAll: selectAll,
6987
    singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
6988
    killLine: function (cm) { return deleteNearSelection(cm, function (range) {
6989
      if (range.empty()) {
6990
        var len = getLine(cm.doc, range.head.line).text.length;
6991
        if (range.head.ch == len && range.head.line < cm.lastLine())
6992
          { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
6993
        else
6994
          { return {from: range.head, to: Pos(range.head.line, len)} }
6995
      } else {
6996
        return {from: range.from(), to: range.to()}
6997
      }
6998
    }); },
6999
    deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
7000
      from: Pos(range.from().line, 0),
7001
      to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
7002
    }); }); },
7003
    delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
7004
      from: Pos(range.from().line, 0), to: range.from()
7005
    }); }); },
7006
    delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
7007
      var top = cm.charCoords(range.head, "div").top + 5;
7008
      var leftPos = cm.coordsChar({left: 0, top: top}, "div");
7009
      return {from: leftPos, to: range.from()}
7010
    }); },
7011
    delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
7012
      var top = cm.charCoords(range.head, "div").top + 5;
7013
      var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
7014
      return {from: range.from(), to: rightPos }
7015
    }); },
7016
    undo: function (cm) { return cm.undo(); },
7017
    redo: function (cm) { return cm.redo(); },
7018
    undoSelection: function (cm) { return cm.undoSelection(); },
7019
    redoSelection: function (cm) { return cm.redoSelection(); },
7020
    goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
7021
    goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
7022
    goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
7023
      {origin: "+move", bias: 1}
7024
    ); },
7025
    goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
7026
      {origin: "+move", bias: 1}
7027
    ); },
7028
    goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
7029
      {origin: "+move", bias: -1}
7030
    ); },
7031
    goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
7032
      var top = cm.cursorCoords(range.head, "div").top + 5;
7033
      return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
7034
    }, sel_move); },
7035
    goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
7036
      var top = cm.cursorCoords(range.head, "div").top + 5;
7037
      return cm.coordsChar({left: 0, top: top}, "div")
7038
    }, sel_move); },
7039
    goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
7040
      var top = cm.cursorCoords(range.head, "div").top + 5;
7041
      var pos = cm.coordsChar({left: 0, top: top}, "div");
7042
      if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
7043
      return pos
7044
    }, sel_move); },
7045
    goLineUp: function (cm) { return cm.moveV(-1, "line"); },
7046
    goLineDown: function (cm) { return cm.moveV(1, "line"); },
7047
    goPageUp: function (cm) { return cm.moveV(-1, "page"); },
7048
    goPageDown: function (cm) { return cm.moveV(1, "page"); },
7049
    goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
7050
    goCharRight: function (cm) { return cm.moveH(1, "char"); },
7051
    goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
7052
    goColumnRight: function (cm) { return cm.moveH(1, "column"); },
7053
    goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
7054
    goGroupRight: function (cm) { return cm.moveH(1, "group"); },
7055
    goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
7056
    goWordRight: function (cm) { return cm.moveH(1, "word"); },
16493 obado 7057
    delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
14283 obado 7058
    delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
7059
    delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
7060
    delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
7061
    delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
7062
    delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
7063
    indentAuto: function (cm) { return cm.indentSelection("smart"); },
7064
    indentMore: function (cm) { return cm.indentSelection("add"); },
7065
    indentLess: function (cm) { return cm.indentSelection("subtract"); },
7066
    insertTab: function (cm) { return cm.replaceSelection("\t"); },
7067
    insertSoftTab: function (cm) {
7068
      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
7069
      for (var i = 0; i < ranges.length; i++) {
7070
        var pos = ranges[i].from();
7071
        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
7072
        spaces.push(spaceStr(tabSize - col % tabSize));
7073
      }
7074
      cm.replaceSelections(spaces);
7075
    },
7076
    defaultTab: function (cm) {
7077
      if (cm.somethingSelected()) { cm.indentSelection("add"); }
7078
      else { cm.execCommand("insertTab"); }
7079
    },
7080
    // Swap the two chars left and right of each selection's head.
7081
    // Move cursor behind the two swapped characters afterwards.
7082
    //
7083
    // Doesn't consider line feeds a character.
7084
    // Doesn't scan more than one line above to find a character.
7085
    // Doesn't do anything on an empty line.
7086
    // Doesn't do anything with non-empty selections.
7087
    transposeChars: function (cm) { return runInOp(cm, function () {
7088
      var ranges = cm.listSelections(), newSel = [];
7089
      for (var i = 0; i < ranges.length; i++) {
7090
        if (!ranges[i].empty()) { continue }
7091
        var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
7092
        if (line) {
7093
          if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
7094
          if (cur.ch > 0) {
7095
            cur = new Pos(cur.line, cur.ch + 1);
7096
            cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
7097
                            Pos(cur.line, cur.ch - 2), cur, "+transpose");
7098
          } else if (cur.line > cm.doc.first) {
7099
            var prev = getLine(cm.doc, cur.line - 1).text;
7100
            if (prev) {
7101
              cur = new Pos(cur.line, 1);
7102
              cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
7103
                              prev.charAt(prev.length - 1),
7104
                              Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
7105
            }
7106
          }
7107
        }
7108
        newSel.push(new Range(cur, cur));
7109
      }
7110
      cm.setSelections(newSel);
7111
    }); },
7112
    newlineAndIndent: function (cm) { return runInOp(cm, function () {
7113
      var sels = cm.listSelections();
7114
      for (var i = sels.length - 1; i >= 0; i--)
7115
        { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
7116
      sels = cm.listSelections();
7117
      for (var i$1 = 0; i$1 < sels.length; i$1++)
7118
        { cm.indentLine(sels[i$1].from().line, null, true); }
7119
      ensureCursorVisible(cm);
7120
    }); },
7121
    openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
7122
    toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
7123
  };
7124
 
7125
 
7126
  function lineStart(cm, lineN) {
7127
    var line = getLine(cm.doc, lineN);
7128
    var visual = visualLine(line);
7129
    if (visual != line) { lineN = lineNo(visual); }
7130
    return endOfLine(true, cm, visual, lineN, 1)
7131
  }
7132
  function lineEnd(cm, lineN) {
7133
    var line = getLine(cm.doc, lineN);
7134
    var visual = visualLineEnd(line);
7135
    if (visual != line) { lineN = lineNo(visual); }
7136
    return endOfLine(true, cm, line, lineN, -1)
7137
  }
7138
  function lineStartSmart(cm, pos) {
7139
    var start = lineStart(cm, pos.line);
7140
    var line = getLine(cm.doc, start.line);
7141
    var order = getOrder(line, cm.doc.direction);
7142
    if (!order || order[0].level == 0) {
15152 obado 7143
      var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
14283 obado 7144
      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
7145
      return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
7146
    }
7147
    return start
7148
  }
7149
 
7150
  // Run a handler that was bound to a key.
7151
  function doHandleBinding(cm, bound, dropShift) {
7152
    if (typeof bound == "string") {
7153
      bound = commands[bound];
7154
      if (!bound) { return false }
7155
    }
7156
    // Ensure previous input has been read, so that the handler sees a
7157
    // consistent view of the document
7158
    cm.display.input.ensurePolled();
7159
    var prevShift = cm.display.shift, done = false;
7160
    try {
7161
      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7162
      if (dropShift) { cm.display.shift = false; }
7163
      done = bound(cm) != Pass;
7164
    } finally {
7165
      cm.display.shift = prevShift;
7166
      cm.state.suppressEdits = false;
7167
    }
7168
    return done
7169
  }
7170
 
7171
  function lookupKeyForEditor(cm, name, handle) {
7172
    for (var i = 0; i < cm.state.keyMaps.length; i++) {
7173
      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
7174
      if (result) { return result }
7175
    }
7176
    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7177
      || lookupKey(name, cm.options.keyMap, handle, cm)
7178
  }
7179
 
7180
  // Note that, despite the name, this function is also used to check
7181
  // for bound mouse clicks.
7182
 
7183
  var stopSeq = new Delayed;
7184
 
7185
  function dispatchKey(cm, name, e, handle) {
7186
    var seq = cm.state.keySeq;
7187
    if (seq) {
7188
      if (isModifierKey(name)) { return "handled" }
7189
      if (/\'$/.test(name))
7190
        { cm.state.keySeq = null; }
7191
      else
7192
        { stopSeq.set(50, function () {
7193
          if (cm.state.keySeq == seq) {
7194
            cm.state.keySeq = null;
7195
            cm.display.input.reset();
7196
          }
7197
        }); }
7198
      if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
7199
    }
7200
    return dispatchKeyInner(cm, name, e, handle)
7201
  }
7202
 
7203
  function dispatchKeyInner(cm, name, e, handle) {
7204
    var result = lookupKeyForEditor(cm, name, handle);
7205
 
7206
    if (result == "multi")
7207
      { cm.state.keySeq = name; }
7208
    if (result == "handled")
7209
      { signalLater(cm, "keyHandled", cm, name, e); }
7210
 
7211
    if (result == "handled" || result == "multi") {
7212
      e_preventDefault(e);
7213
      restartBlink(cm);
7214
    }
7215
 
7216
    return !!result
7217
  }
7218
 
7219
  // Handle a key from the keydown event.
7220
  function handleKeyBinding(cm, e) {
7221
    var name = keyName(e, true);
7222
    if (!name) { return false }
7223
 
7224
    if (e.shiftKey && !cm.state.keySeq) {
7225
      // First try to resolve full name (including 'Shift-'). Failing
7226
      // that, see if there is a cursor-motion command (starting with
7227
      // 'go') bound to the keyname without 'Shift-'.
7228
      return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
7229
          || dispatchKey(cm, name, e, function (b) {
7230
               if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
7231
                 { return doHandleBinding(cm, b) }
7232
             })
7233
    } else {
7234
      return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
7235
    }
7236
  }
7237
 
7238
  // Handle a key from the keypress event
7239
  function handleCharBinding(cm, e, ch) {
7240
    return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
7241
  }
7242
 
7243
  var lastStoppedKey = null;
7244
  function onKeyDown(e) {
7245
    var cm = this;
15152 obado 7246
    if (e.target && e.target != cm.display.input.getField()) { return }
14283 obado 7247
    cm.curOp.focus = activeElt();
7248
    if (signalDOMEvent(cm, e)) { return }
7249
    // IE does strange things with escape.
7250
    if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
7251
    var code = e.keyCode;
7252
    cm.display.shift = code == 16 || e.shiftKey;
7253
    var handled = handleKeyBinding(cm, e);
7254
    if (presto) {
7255
      lastStoppedKey = handled ? code : null;
7256
      // Opera has no cut event... we try to at least catch the key combo
7257
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
7258
        { cm.replaceSelection("", null, "cut"); }
7259
    }
15152 obado 7260
    if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
7261
      { document.execCommand("cut"); }
14283 obado 7262
 
7263
    // Turn mouse into crosshair when Alt is held on Mac.
7264
    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
7265
      { showCrossHair(cm); }
7266
  }
7267
 
7268
  function showCrossHair(cm) {
7269
    var lineDiv = cm.display.lineDiv;
7270
    addClass(lineDiv, "CodeMirror-crosshair");
7271
 
7272
    function up(e) {
7273
      if (e.keyCode == 18 || !e.altKey) {
7274
        rmClass(lineDiv, "CodeMirror-crosshair");
7275
        off(document, "keyup", up);
7276
        off(document, "mouseover", up);
7277
      }
7278
    }
7279
    on(document, "keyup", up);
7280
    on(document, "mouseover", up);
7281
  }
7282
 
7283
  function onKeyUp(e) {
7284
    if (e.keyCode == 16) { this.doc.sel.shift = false; }
7285
    signalDOMEvent(this, e);
7286
  }
7287
 
7288
  function onKeyPress(e) {
7289
    var cm = this;
15152 obado 7290
    if (e.target && e.target != cm.display.input.getField()) { return }
14283 obado 7291
    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
7292
    var keyCode = e.keyCode, charCode = e.charCode;
7293
    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
7294
    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
7295
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
7296
    // Some browsers fire keypress events for backspace
7297
    if (ch == "\x08") { return }
7298
    if (handleCharBinding(cm, e, ch)) { return }
7299
    cm.display.input.onKeyPress(e);
7300
  }
7301
 
7302
  var DOUBLECLICK_DELAY = 400;
7303
 
7304
  var PastClick = function(time, pos, button) {
7305
    this.time = time;
7306
    this.pos = pos;
7307
    this.button = button;
7308
  };
7309
 
7310
  PastClick.prototype.compare = function (time, pos, button) {
7311
    return this.time + DOUBLECLICK_DELAY > time &&
7312
      cmp(pos, this.pos) == 0 && button == this.button
7313
  };
7314
 
7315
  var lastClick, lastDoubleClick;
7316
  function clickRepeat(pos, button) {
7317
    var now = +new Date;
7318
    if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
7319
      lastClick = lastDoubleClick = null;
7320
      return "triple"
7321
    } else if (lastClick && lastClick.compare(now, pos, button)) {
7322
      lastDoubleClick = new PastClick(now, pos, button);
7323
      lastClick = null;
7324
      return "double"
7325
    } else {
7326
      lastClick = new PastClick(now, pos, button);
7327
      lastDoubleClick = null;
7328
      return "single"
7329
    }
7330
  }
7331
 
7332
  // A mouse down can be a single click, double click, triple click,
7333
  // start of selection drag, start of text drag, new cursor
7334
  // (ctrl-click), rectangle drag (alt-drag), or xwin
7335
  // middle-click-paste. Or it might be a click on something we should
7336
  // not interfere with, such as a scrollbar or widget.
7337
  function onMouseDown(e) {
7338
    var cm = this, display = cm.display;
7339
    if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
7340
    display.input.ensurePolled();
7341
    display.shift = e.shiftKey;
7342
 
7343
    if (eventInWidget(display, e)) {
7344
      if (!webkit) {
7345
        // Briefly turn off draggability, to allow widgets to do
7346
        // normal dragging things.
7347
        display.scroller.draggable = false;
7348
        setTimeout(function () { return display.scroller.draggable = true; }, 100);
7349
      }
7350
      return
7351
    }
7352
    if (clickInGutter(cm, e)) { return }
7353
    var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
7354
    window.focus();
7355
 
7356
    // #3261: make sure, that we're not starting a second selection
7357
    if (button == 1 && cm.state.selectingText)
7358
      { cm.state.selectingText(e); }
7359
 
7360
    if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
7361
 
7362
    if (button == 1) {
7363
      if (pos) { leftButtonDown(cm, pos, repeat, e); }
7364
      else if (e_target(e) == display.scroller) { e_preventDefault(e); }
7365
    } else if (button == 2) {
7366
      if (pos) { extendSelection(cm.doc, pos); }
7367
      setTimeout(function () { return display.input.focus(); }, 20);
7368
    } else if (button == 3) {
7369
      if (captureRightClick) { cm.display.input.onContextMenu(e); }
7370
      else { delayBlurEvent(cm); }
7371
    }
7372
  }
7373
 
7374
  function handleMappedButton(cm, button, pos, repeat, event) {
7375
    var name = "Click";
7376
    if (repeat == "double") { name = "Double" + name; }
7377
    else if (repeat == "triple") { name = "Triple" + name; }
7378
    name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
7379
 
7380
    return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
7381
      if (typeof bound == "string") { bound = commands[bound]; }
7382
      if (!bound) { return false }
7383
      var done = false;
7384
      try {
7385
        if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7386
        done = bound(cm, pos) != Pass;
7387
      } finally {
7388
        cm.state.suppressEdits = false;
7389
      }
7390
      return done
7391
    })
7392
  }
7393
 
7394
  function configureMouse(cm, repeat, event) {
7395
    var option = cm.getOption("configureMouse");
7396
    var value = option ? option(cm, repeat, event) : {};
7397
    if (value.unit == null) {
7398
      var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
7399
      value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
7400
    }
7401
    if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
7402
    if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
7403
    if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
7404
    return value
7405
  }
7406
 
7407
  function leftButtonDown(cm, pos, repeat, event) {
7408
    if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
7409
    else { cm.curOp.focus = activeElt(); }
7410
 
7411
    var behavior = configureMouse(cm, repeat, event);
7412
 
7413
    var sel = cm.doc.sel, contained;
7414
    if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
7415
        repeat == "single" && (contained = sel.contains(pos)) > -1 &&
7416
        (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
7417
        (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
7418
      { leftButtonStartDrag(cm, event, pos, behavior); }
7419
    else
7420
      { leftButtonSelect(cm, event, pos, behavior); }
7421
  }
7422
 
7423
  // Start a text drag. When it ends, see if any dragging actually
7424
  // happen, and treat as a click if it didn't.
7425
  function leftButtonStartDrag(cm, event, pos, behavior) {
7426
    var display = cm.display, moved = false;
7427
    var dragEnd = operation(cm, function (e) {
7428
      if (webkit) { display.scroller.draggable = false; }
7429
      cm.state.draggingText = false;
16493 obado 7430
      if (cm.state.delayingBlurEvent) {
7431
        if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
7432
        else { delayBlurEvent(cm); }
7433
      }
14283 obado 7434
      off(display.wrapper.ownerDocument, "mouseup", dragEnd);
7435
      off(display.wrapper.ownerDocument, "mousemove", mouseMove);
7436
      off(display.scroller, "dragstart", dragStart);
7437
      off(display.scroller, "drop", dragEnd);
7438
      if (!moved) {
7439
        e_preventDefault(e);
7440
        if (!behavior.addNew)
7441
          { extendSelection(cm.doc, pos, null, null, behavior.extend); }
7442
        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
15152 obado 7443
        if ((webkit && !safari) || ie && ie_version == 9)
7444
          { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
14283 obado 7445
        else
7446
          { display.input.focus(); }
7447
      }
7448
    });
7449
    var mouseMove = function(e2) {
7450
      moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
7451
    };
7452
    var dragStart = function () { return moved = true; };
7453
    // Let the drag handler handle this.
7454
    if (webkit) { display.scroller.draggable = true; }
7455
    cm.state.draggingText = dragEnd;
7456
    dragEnd.copy = !behavior.moveOnDrag;
7457
    on(display.wrapper.ownerDocument, "mouseup", dragEnd);
7458
    on(display.wrapper.ownerDocument, "mousemove", mouseMove);
7459
    on(display.scroller, "dragstart", dragStart);
7460
    on(display.scroller, "drop", dragEnd);
7461
 
16493 obado 7462
    cm.state.delayingBlurEvent = true;
14283 obado 7463
    setTimeout(function () { return display.input.focus(); }, 20);
16493 obado 7464
    // IE's approach to draggable
7465
    if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
14283 obado 7466
  }
7467
 
7468
  function rangeForUnit(cm, pos, unit) {
7469
    if (unit == "char") { return new Range(pos, pos) }
7470
    if (unit == "word") { return cm.findWordAt(pos) }
7471
    if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
7472
    var result = unit(cm, pos);
7473
    return new Range(result.from, result.to)
7474
  }
7475
 
7476
  // Normal selection, as opposed to text dragging.
7477
  function leftButtonSelect(cm, event, start, behavior) {
16493 obado 7478
    if (ie) { delayBlurEvent(cm); }
14283 obado 7479
    var display = cm.display, doc = cm.doc;
7480
    e_preventDefault(event);
7481
 
7482
    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
7483
    if (behavior.addNew && !behavior.extend) {
7484
      ourIndex = doc.sel.contains(start);
7485
      if (ourIndex > -1)
7486
        { ourRange = ranges[ourIndex]; }
7487
      else
7488
        { ourRange = new Range(start, start); }
7489
    } else {
7490
      ourRange = doc.sel.primary();
7491
      ourIndex = doc.sel.primIndex;
7492
    }
7493
 
7494
    if (behavior.unit == "rectangle") {
7495
      if (!behavior.addNew) { ourRange = new Range(start, start); }
7496
      start = posFromMouse(cm, event, true, true);
7497
      ourIndex = -1;
7498
    } else {
15152 obado 7499
      var range = rangeForUnit(cm, start, behavior.unit);
14283 obado 7500
      if (behavior.extend)
15152 obado 7501
        { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
14283 obado 7502
      else
15152 obado 7503
        { ourRange = range; }
14283 obado 7504
    }
7505
 
7506
    if (!behavior.addNew) {
7507
      ourIndex = 0;
7508
      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
7509
      startSel = doc.sel;
7510
    } else if (ourIndex == -1) {
7511
      ourIndex = ranges.length;
7512
      setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
7513
                   {scroll: false, origin: "*mouse"});
7514
    } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
7515
      setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
7516
                   {scroll: false, origin: "*mouse"});
7517
      startSel = doc.sel;
7518
    } else {
7519
      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
7520
    }
7521
 
7522
    var lastPos = start;
7523
    function extendTo(pos) {
7524
      if (cmp(lastPos, pos) == 0) { return }
7525
      lastPos = pos;
7526
 
7527
      if (behavior.unit == "rectangle") {
7528
        var ranges = [], tabSize = cm.options.tabSize;
7529
        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
7530
        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
7531
        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
7532
        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
7533
             line <= end; line++) {
7534
          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
7535
          if (left == right)
7536
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
7537
          else if (text.length > leftPos)
7538
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
7539
        }
7540
        if (!ranges.length) { ranges.push(new Range(start, start)); }
7541
        setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
7542
                     {origin: "*mouse", scroll: false});
7543
        cm.scrollIntoView(pos);
7544
      } else {
7545
        var oldRange = ourRange;
15152 obado 7546
        var range = rangeForUnit(cm, pos, behavior.unit);
14283 obado 7547
        var anchor = oldRange.anchor, head;
15152 obado 7548
        if (cmp(range.anchor, anchor) > 0) {
7549
          head = range.head;
7550
          anchor = minPos(oldRange.from(), range.anchor);
14283 obado 7551
        } else {
15152 obado 7552
          head = range.anchor;
7553
          anchor = maxPos(oldRange.to(), range.head);
14283 obado 7554
        }
7555
        var ranges$1 = startSel.ranges.slice(0);
7556
        ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
7557
        setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
7558
      }
7559
    }
7560
 
7561
    var editorSize = display.wrapper.getBoundingClientRect();
7562
    // Used to ensure timeout re-tries don't fire when another extend
7563
    // happened in the meantime (clearTimeout isn't reliable -- at
7564
    // least on Chrome, the timeouts still happen even when cleared,
7565
    // if the clear happens after their scheduled firing time).
7566
    var counter = 0;
7567
 
7568
    function extend(e) {
7569
      var curCount = ++counter;
7570
      var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
7571
      if (!cur) { return }
7572
      if (cmp(cur, lastPos) != 0) {
7573
        cm.curOp.focus = activeElt();
7574
        extendTo(cur);
7575
        var visible = visibleLines(display, doc);
7576
        if (cur.line >= visible.to || cur.line < visible.from)
7577
          { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
7578
      } else {
7579
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
7580
        if (outside) { setTimeout(operation(cm, function () {
7581
          if (counter != curCount) { return }
7582
          display.scroller.scrollTop += outside;
7583
          extend(e);
7584
        }), 50); }
7585
      }
7586
    }
7587
 
7588
    function done(e) {
7589
      cm.state.selectingText = false;
7590
      counter = Infinity;
7591
      // If e is null or undefined we interpret this as someone trying
7592
      // to explicitly cancel the selection rather than the user
7593
      // letting go of the mouse button.
7594
      if (e) {
7595
        e_preventDefault(e);
7596
        display.input.focus();
7597
      }
7598
      off(display.wrapper.ownerDocument, "mousemove", move);
7599
      off(display.wrapper.ownerDocument, "mouseup", up);
7600
      doc.history.lastSelOrigin = null;
7601
    }
7602
 
7603
    var move = operation(cm, function (e) {
7604
      if (e.buttons === 0 || !e_button(e)) { done(e); }
7605
      else { extend(e); }
7606
    });
7607
    var up = operation(cm, done);
7608
    cm.state.selectingText = up;
7609
    on(display.wrapper.ownerDocument, "mousemove", move);
7610
    on(display.wrapper.ownerDocument, "mouseup", up);
7611
  }
7612
 
7613
  // Used when mouse-selecting to adjust the anchor to the proper side
7614
  // of a bidi jump depending on the visual position of the head.
15152 obado 7615
  function bidiSimplify(cm, range) {
7616
    var anchor = range.anchor;
7617
    var head = range.head;
14283 obado 7618
    var anchorLine = getLine(cm.doc, anchor.line);
15152 obado 7619
    if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
14283 obado 7620
    var order = getOrder(anchorLine);
15152 obado 7621
    if (!order) { return range }
14283 obado 7622
    var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
15152 obado 7623
    if (part.from != anchor.ch && part.to != anchor.ch) { return range }
14283 obado 7624
    var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
15152 obado 7625
    if (boundary == 0 || boundary == order.length) { return range }
14283 obado 7626
 
7627
    // Compute the relative visual position of the head compared to the
7628
    // anchor (<0 is to the left, >0 to the right)
7629
    var leftSide;
7630
    if (head.line != anchor.line) {
7631
      leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
7632
    } else {
7633
      var headIndex = getBidiPartAt(order, head.ch, head.sticky);
7634
      var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
7635
      if (headIndex == boundary - 1 || headIndex == boundary)
7636
        { leftSide = dir < 0; }
7637
      else
7638
        { leftSide = dir > 0; }
7639
    }
7640
 
7641
    var usePart = order[boundary + (leftSide ? -1 : 0)];
7642
    var from = leftSide == (usePart.level == 1);
7643
    var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
15152 obado 7644
    return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
14283 obado 7645
  }
7646
 
7647
 
7648
  // Determines whether an event happened in the gutter, and fires the
7649
  // handlers for the corresponding event.
7650
  function gutterEvent(cm, e, type, prevent) {
7651
    var mX, mY;
7652
    if (e.touches) {
7653
      mX = e.touches[0].clientX;
7654
      mY = e.touches[0].clientY;
7655
    } else {
7656
      try { mX = e.clientX; mY = e.clientY; }
15332 obado 7657
      catch(e$1) { return false }
14283 obado 7658
    }
7659
    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
7660
    if (prevent) { e_preventDefault(e); }
7661
 
7662
    var display = cm.display;
7663
    var lineBox = display.lineDiv.getBoundingClientRect();
7664
 
7665
    if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
7666
    mY -= lineBox.top - display.viewOffset;
7667
 
7668
    for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
7669
      var g = display.gutters.childNodes[i];
7670
      if (g && g.getBoundingClientRect().right >= mX) {
7671
        var line = lineAtHeight(cm.doc, mY);
7672
        var gutter = cm.display.gutterSpecs[i];
7673
        signal(cm, type, cm, line, gutter.className, e);
7674
        return e_defaultPrevented(e)
7675
      }
7676
    }
7677
  }
7678
 
7679
  function clickInGutter(cm, e) {
7680
    return gutterEvent(cm, e, "gutterClick", true)
7681
  }
7682
 
7683
  // CONTEXT MENU HANDLING
7684
 
7685
  // To make the context menu work, we need to briefly unhide the
7686
  // textarea (making it as unobtrusive as possible) to let the
7687
  // right-click take effect on it.
7688
  function onContextMenu(cm, e) {
7689
    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
7690
    if (signalDOMEvent(cm, e, "contextmenu")) { return }
7691
    if (!captureRightClick) { cm.display.input.onContextMenu(e); }
7692
  }
7693
 
7694
  function contextMenuInGutter(cm, e) {
7695
    if (!hasHandler(cm, "gutterContextMenu")) { return false }
7696
    return gutterEvent(cm, e, "gutterContextMenu", false)
7697
  }
7698
 
7699
  function themeChanged(cm) {
7700
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
7701
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
7702
    clearCaches(cm);
7703
  }
7704
 
7705
  var Init = {toString: function(){return "CodeMirror.Init"}};
7706
 
7707
  var defaults = {};
7708
  var optionHandlers = {};
7709
 
7710
  function defineOptions(CodeMirror) {
7711
    var optionHandlers = CodeMirror.optionHandlers;
7712
 
7713
    function option(name, deflt, handle, notOnInit) {
7714
      CodeMirror.defaults[name] = deflt;
7715
      if (handle) { optionHandlers[name] =
7716
        notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
7717
    }
7718
 
7719
    CodeMirror.defineOption = option;
7720
 
7721
    // Passed to option handlers when there is no old value.
7722
    CodeMirror.Init = Init;
7723
 
7724
    // These two are, on init, called from the constructor because they
7725
    // have to be initialized before the editor can start at all.
7726
    option("value", "", function (cm, val) { return cm.setValue(val); }, true);
7727
    option("mode", null, function (cm, val) {
7728
      cm.doc.modeOption = val;
7729
      loadMode(cm);
7730
    }, true);
7731
 
7732
    option("indentUnit", 2, loadMode, true);
7733
    option("indentWithTabs", false);
7734
    option("smartIndent", true);
7735
    option("tabSize", 4, function (cm) {
7736
      resetModeState(cm);
7737
      clearCaches(cm);
7738
      regChange(cm);
7739
    }, true);
7740
 
7741
    option("lineSeparator", null, function (cm, val) {
7742
      cm.doc.lineSep = val;
7743
      if (!val) { return }
7744
      var newBreaks = [], lineNo = cm.doc.first;
7745
      cm.doc.iter(function (line) {
7746
        for (var pos = 0;;) {
7747
          var found = line.text.indexOf(val, pos);
7748
          if (found == -1) { break }
7749
          pos = found + val.length;
7750
          newBreaks.push(Pos(lineNo, found));
7751
        }
7752
        lineNo++;
7753
      });
7754
      for (var i = newBreaks.length - 1; i >= 0; i--)
7755
        { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
7756
    });
16493 obado 7757
    option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
14283 obado 7758
      cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
7759
      if (old != Init) { cm.refresh(); }
7760
    });
7761
    option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
7762
    option("electricChars", true);
7763
    option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
7764
      throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
7765
    }, true);
7766
    option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
7767
    option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
7768
    option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
7769
    option("rtlMoveVisually", !windows);
7770
    option("wholeLineUpdateBefore", true);
7771
 
7772
    option("theme", "default", function (cm) {
7773
      themeChanged(cm);
7774
      updateGutters(cm);
7775
    }, true);
7776
    option("keyMap", "default", function (cm, val, old) {
7777
      var next = getKeyMap(val);
7778
      var prev = old != Init && getKeyMap(old);
7779
      if (prev && prev.detach) { prev.detach(cm, next); }
7780
      if (next.attach) { next.attach(cm, prev || null); }
7781
    });
7782
    option("extraKeys", null);
7783
    option("configureMouse", null);
7784
 
7785
    option("lineWrapping", false, wrappingChanged, true);
7786
    option("gutters", [], function (cm, val) {
7787
      cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
7788
      updateGutters(cm);
7789
    }, true);
7790
    option("fixedGutter", true, function (cm, val) {
7791
      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
7792
      cm.refresh();
7793
    }, true);
7794
    option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
7795
    option("scrollbarStyle", "native", function (cm) {
7796
      initScrollbars(cm);
7797
      updateScrollbars(cm);
7798
      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
7799
      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
7800
    }, true);
7801
    option("lineNumbers", false, function (cm, val) {
7802
      cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
7803
      updateGutters(cm);
7804
    }, true);
7805
    option("firstLineNumber", 1, updateGutters, true);
7806
    option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
7807
    option("showCursorWhenSelecting", false, updateSelection, true);
7808
 
7809
    option("resetSelectionOnContextMenu", true);
7810
    option("lineWiseCopyCut", true);
7811
    option("pasteLinesPerSelection", true);
7812
    option("selectionsMayTouch", false);
7813
 
7814
    option("readOnly", false, function (cm, val) {
7815
      if (val == "nocursor") {
7816
        onBlur(cm);
7817
        cm.display.input.blur();
7818
      }
7819
      cm.display.input.readOnlyChanged(val);
7820
    });
15152 obado 7821
 
7822
    option("screenReaderLabel", null, function (cm, val) {
7823
      val = (val === '') ? null : val;
7824
      cm.display.input.screenReaderLabelChanged(val);
7825
    });
7826
 
14283 obado 7827
    option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
7828
    option("dragDrop", true, dragDropChanged);
7829
    option("allowDropFileTypes", null);
7830
 
7831
    option("cursorBlinkRate", 530);
7832
    option("cursorScrollMargin", 0);
7833
    option("cursorHeight", 1, updateSelection, true);
7834
    option("singleCursorHeightPerLine", true, updateSelection, true);
7835
    option("workTime", 100);
7836
    option("workDelay", 100);
7837
    option("flattenSpans", true, resetModeState, true);
7838
    option("addModeClass", false, resetModeState, true);
7839
    option("pollInterval", 100);
7840
    option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
7841
    option("historyEventDelay", 1250);
7842
    option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
7843
    option("maxHighlightLength", 10000, resetModeState, true);
7844
    option("moveInputWithCursor", true, function (cm, val) {
7845
      if (!val) { cm.display.input.resetPosition(); }
7846
    });
7847
 
7848
    option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
7849
    option("autofocus", null);
7850
    option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
7851
    option("phrases", null);
7852
  }
7853
 
7854
  function dragDropChanged(cm, value, old) {
7855
    var wasOn = old && old != Init;
7856
    if (!value != !wasOn) {
7857
      var funcs = cm.display.dragFunctions;
7858
      var toggle = value ? on : off;
7859
      toggle(cm.display.scroller, "dragstart", funcs.start);
7860
      toggle(cm.display.scroller, "dragenter", funcs.enter);
7861
      toggle(cm.display.scroller, "dragover", funcs.over);
7862
      toggle(cm.display.scroller, "dragleave", funcs.leave);
7863
      toggle(cm.display.scroller, "drop", funcs.drop);
7864
    }
7865
  }
7866
 
7867
  function wrappingChanged(cm) {
7868
    if (cm.options.lineWrapping) {
7869
      addClass(cm.display.wrapper, "CodeMirror-wrap");
7870
      cm.display.sizer.style.minWidth = "";
7871
      cm.display.sizerWidth = null;
7872
    } else {
7873
      rmClass(cm.display.wrapper, "CodeMirror-wrap");
7874
      findMaxLine(cm);
7875
    }
7876
    estimateLineHeights(cm);
7877
    regChange(cm);
7878
    clearCaches(cm);
7879
    setTimeout(function () { return updateScrollbars(cm); }, 100);
7880
  }
7881
 
7882
  // A CodeMirror instance represents an editor. This is the object
7883
  // that user code is usually dealing with.
7884
 
7885
  function CodeMirror(place, options) {
7886
    var this$1 = this;
7887
 
7888
    if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
7889
 
7890
    this.options = options = options ? copyObj(options) : {};
7891
    // Determine effective options based on given values and defaults.
7892
    copyObj(defaults, options, false);
7893
 
7894
    var doc = options.value;
7895
    if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
7896
    else if (options.mode) { doc.modeOption = options.mode; }
7897
    this.doc = doc;
7898
 
7899
    var input = new CodeMirror.inputStyles[options.inputStyle](this);
7900
    var display = this.display = new Display(place, doc, input, options);
7901
    display.wrapper.CodeMirror = this;
7902
    themeChanged(this);
7903
    if (options.lineWrapping)
7904
      { this.display.wrapper.className += " CodeMirror-wrap"; }
7905
    initScrollbars(this);
7906
 
7907
    this.state = {
7908
      keyMaps: [],  // stores maps added by addKeyMap
7909
      overlays: [], // highlighting overlays, as added by addOverlay
7910
      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
7911
      overwrite: false,
7912
      delayingBlurEvent: false,
7913
      focused: false,
7914
      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
7915
      pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
7916
      selectingText: false,
7917
      draggingText: false,
7918
      highlight: new Delayed(), // stores highlight worker timeout
7919
      keySeq: null,  // Unfinished key sequence
7920
      specialChars: null
7921
    };
7922
 
7923
    if (options.autofocus && !mobile) { display.input.focus(); }
7924
 
7925
    // Override magic textarea content restore that IE sometimes does
7926
    // on our hidden textarea on reload
7927
    if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
7928
 
7929
    registerEventHandlers(this);
7930
    ensureGlobalHandlers();
7931
 
7932
    startOperation(this);
7933
    this.curOp.forceUpdate = true;
7934
    attachDoc(this, doc);
7935
 
7936
    if ((options.autofocus && !mobile) || this.hasFocus())
16493 obado 7937
      { setTimeout(function () {
7938
        if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
7939
      }, 20); }
14283 obado 7940
    else
7941
      { onBlur(this); }
7942
 
7943
    for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
15152 obado 7944
      { optionHandlers[opt](this, options[opt], Init); } }
14283 obado 7945
    maybeUpdateLineNumberWidth(this);
7946
    if (options.finishInit) { options.finishInit(this); }
15152 obado 7947
    for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
14283 obado 7948
    endOperation(this);
7949
    // Suppress optimizelegibility in Webkit, since it breaks text
7950
    // measuring on line wrapping boundaries.
7951
    if (webkit && options.lineWrapping &&
7952
        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
7953
      { display.lineDiv.style.textRendering = "auto"; }
7954
  }
7955
 
7956
  // The default configuration options.
7957
  CodeMirror.defaults = defaults;
7958
  // Functions to run when options are changed.
7959
  CodeMirror.optionHandlers = optionHandlers;
7960
 
7961
  // Attach the necessary event handlers when initializing the editor
7962
  function registerEventHandlers(cm) {
7963
    var d = cm.display;
7964
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
7965
    // Older IE's will not fire a second mousedown for a double click
7966
    if (ie && ie_version < 11)
7967
      { on(d.scroller, "dblclick", operation(cm, function (e) {
7968
        if (signalDOMEvent(cm, e)) { return }
7969
        var pos = posFromMouse(cm, e);
7970
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
7971
        e_preventDefault(e);
7972
        var word = cm.findWordAt(pos);
7973
        extendSelection(cm.doc, word.anchor, word.head);
7974
      })); }
7975
    else
7976
      { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
7977
    // Some browsers fire contextmenu *after* opening the menu, at
7978
    // which point we can't mess with it anymore. Context menu is
7979
    // handled in onMouseDown for these browsers.
7980
    on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
15152 obado 7981
    on(d.input.getField(), "contextmenu", function (e) {
7982
      if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
7983
    });
14283 obado 7984
 
7985
    // Used to suppress mouse event handling when a touch happens
7986
    var touchFinished, prevTouch = {end: 0};
7987
    function finishTouch() {
7988
      if (d.activeTouch) {
7989
        touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
7990
        prevTouch = d.activeTouch;
7991
        prevTouch.end = +new Date;
7992
      }
7993
    }
7994
    function isMouseLikeTouchEvent(e) {
7995
      if (e.touches.length != 1) { return false }
7996
      var touch = e.touches[0];
7997
      return touch.radiusX <= 1 && touch.radiusY <= 1
7998
    }
7999
    function farAway(touch, other) {
8000
      if (other.left == null) { return true }
8001
      var dx = other.left - touch.left, dy = other.top - touch.top;
8002
      return dx * dx + dy * dy > 20 * 20
8003
    }
8004
    on(d.scroller, "touchstart", function (e) {
8005
      if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
8006
        d.input.ensurePolled();
8007
        clearTimeout(touchFinished);
8008
        var now = +new Date;
8009
        d.activeTouch = {start: now, moved: false,
8010
                         prev: now - prevTouch.end <= 300 ? prevTouch : null};
8011
        if (e.touches.length == 1) {
8012
          d.activeTouch.left = e.touches[0].pageX;
8013
          d.activeTouch.top = e.touches[0].pageY;
8014
        }
8015
      }
8016
    });
8017
    on(d.scroller, "touchmove", function () {
8018
      if (d.activeTouch) { d.activeTouch.moved = true; }
8019
    });
8020
    on(d.scroller, "touchend", function (e) {
8021
      var touch = d.activeTouch;
8022
      if (touch && !eventInWidget(d, e) && touch.left != null &&
8023
          !touch.moved && new Date - touch.start < 300) {
8024
        var pos = cm.coordsChar(d.activeTouch, "page"), range;
8025
        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
8026
          { range = new Range(pos, pos); }
8027
        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
8028
          { range = cm.findWordAt(pos); }
8029
        else // Triple tap
8030
          { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
8031
        cm.setSelection(range.anchor, range.head);
8032
        cm.focus();
8033
        e_preventDefault(e);
8034
      }
8035
      finishTouch();
8036
    });
8037
    on(d.scroller, "touchcancel", finishTouch);
8038
 
8039
    // Sync scrolling between fake scrollbars and real scrollable
8040
    // area, ensure viewport is updated when scrolling.
8041
    on(d.scroller, "scroll", function () {
8042
      if (d.scroller.clientHeight) {
8043
        updateScrollTop(cm, d.scroller.scrollTop);
8044
        setScrollLeft(cm, d.scroller.scrollLeft, true);
8045
        signal(cm, "scroll", cm);
8046
      }
8047
    });
8048
 
8049
    // Listen to wheel events in order to try and update the viewport on time.
8050
    on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
8051
    on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
8052
 
8053
    // Prevent wrapper from ever scrolling
8054
    on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
8055
 
8056
    d.dragFunctions = {
8057
      enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
8058
      over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
8059
      start: function (e) { return onDragStart(cm, e); },
8060
      drop: operation(cm, onDrop),
8061
      leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
8062
    };
8063
 
8064
    var inp = d.input.getField();
8065
    on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
8066
    on(inp, "keydown", operation(cm, onKeyDown));
8067
    on(inp, "keypress", operation(cm, onKeyPress));
8068
    on(inp, "focus", function (e) { return onFocus(cm, e); });
8069
    on(inp, "blur", function (e) { return onBlur(cm, e); });
8070
  }
8071
 
8072
  var initHooks = [];
8073
  CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
8074
 
8075
  // Indent the given line. The how parameter can be "smart",
8076
  // "add"/null, "subtract", or "prev". When aggressive is false
8077
  // (typically set to true for forced single-line indents), empty
8078
  // lines are not indented, and places where the mode returns Pass
8079
  // are left alone.
8080
  function indentLine(cm, n, how, aggressive) {
8081
    var doc = cm.doc, state;
8082
    if (how == null) { how = "add"; }
8083
    if (how == "smart") {
8084
      // Fall back to "prev" when the mode doesn't have an indentation
8085
      // method.
8086
      if (!doc.mode.indent) { how = "prev"; }
8087
      else { state = getContextBefore(cm, n).state; }
8088
    }
8089
 
8090
    var tabSize = cm.options.tabSize;
8091
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
8092
    if (line.stateAfter) { line.stateAfter = null; }
8093
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
8094
    if (!aggressive && !/\S/.test(line.text)) {
8095
      indentation = 0;
8096
      how = "not";
8097
    } else if (how == "smart") {
8098
      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
8099
      if (indentation == Pass || indentation > 150) {
8100
        if (!aggressive) { return }
8101
        how = "prev";
8102
      }
8103
    }
8104
    if (how == "prev") {
8105
      if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
8106
      else { indentation = 0; }
8107
    } else if (how == "add") {
8108
      indentation = curSpace + cm.options.indentUnit;
8109
    } else if (how == "subtract") {
8110
      indentation = curSpace - cm.options.indentUnit;
8111
    } else if (typeof how == "number") {
8112
      indentation = curSpace + how;
8113
    }
8114
    indentation = Math.max(0, indentation);
8115
 
8116
    var indentString = "", pos = 0;
8117
    if (cm.options.indentWithTabs)
8118
      { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
8119
    if (pos < indentation) { indentString += spaceStr(indentation - pos); }
8120
 
8121
    if (indentString != curSpaceString) {
8122
      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
8123
      line.stateAfter = null;
8124
      return true
8125
    } else {
8126
      // Ensure that, if the cursor was in the whitespace at the start
8127
      // of the line, it is moved to the end of that space.
8128
      for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
8129
        var range = doc.sel.ranges[i$1];
8130
        if (range.head.line == n && range.head.ch < curSpaceString.length) {
8131
          var pos$1 = Pos(n, curSpaceString.length);
8132
          replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
8133
          break
8134
        }
8135
      }
8136
    }
8137
  }
8138
 
8139
  // This will be set to a {lineWise: bool, text: [string]} object, so
8140
  // that, when pasting, we know what kind of selections the copied
8141
  // text was made out of.
8142
  var lastCopied = null;
8143
 
8144
  function setLastCopied(newLastCopied) {
8145
    lastCopied = newLastCopied;
8146
  }
8147
 
8148
  function applyTextInput(cm, inserted, deleted, sel, origin) {
8149
    var doc = cm.doc;
8150
    cm.display.shift = false;
8151
    if (!sel) { sel = doc.sel; }
8152
 
8153
    var recent = +new Date - 200;
8154
    var paste = origin == "paste" || cm.state.pasteIncoming > recent;
8155
    var textLines = splitLinesAuto(inserted), multiPaste = null;
8156
    // When pasting N lines into N selections, insert one line per selection
8157
    if (paste && sel.ranges.length > 1) {
8158
      if (lastCopied && lastCopied.text.join("\n") == inserted) {
8159
        if (sel.ranges.length % lastCopied.text.length == 0) {
8160
          multiPaste = [];
8161
          for (var i = 0; i < lastCopied.text.length; i++)
8162
            { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
8163
        }
8164
      } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
8165
        multiPaste = map(textLines, function (l) { return [l]; });
8166
      }
8167
    }
8168
 
8169
    var updateInput = cm.curOp.updateInput;
8170
    // Normal behavior is to insert the new text into every selection
8171
    for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
15152 obado 8172
      var range = sel.ranges[i$1];
8173
      var from = range.from(), to = range.to();
8174
      if (range.empty()) {
14283 obado 8175
        if (deleted && deleted > 0) // Handle deletion
8176
          { from = Pos(from.line, from.ch - deleted); }
8177
        else if (cm.state.overwrite && !paste) // Handle overwrite
8178
          { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
15332 obado 8179
        else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
14283 obado 8180
          { from = to = Pos(from.line, 0); }
8181
      }
8182
      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
8183
                         origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
8184
      makeChange(cm.doc, changeEvent);
8185
      signalLater(cm, "inputRead", cm, changeEvent);
8186
    }
8187
    if (inserted && !paste)
8188
      { triggerElectric(cm, inserted); }
8189
 
8190
    ensureCursorVisible(cm);
8191
    if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
8192
    cm.curOp.typing = true;
8193
    cm.state.pasteIncoming = cm.state.cutIncoming = -1;
8194
  }
8195
 
8196
  function handlePaste(e, cm) {
8197
    var pasted = e.clipboardData && e.clipboardData.getData("Text");
8198
    if (pasted) {
8199
      e.preventDefault();
8200
      if (!cm.isReadOnly() && !cm.options.disableInput)
8201
        { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
8202
      return true
8203
    }
8204
  }
8205
 
8206
  function triggerElectric(cm, inserted) {
8207
    // When an 'electric' character is inserted, immediately trigger a reindent
8208
    if (!cm.options.electricChars || !cm.options.smartIndent) { return }
8209
    var sel = cm.doc.sel;
8210
 
8211
    for (var i = sel.ranges.length - 1; i >= 0; i--) {
15152 obado 8212
      var range = sel.ranges[i];
8213
      if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
8214
      var mode = cm.getModeAt(range.head);
14283 obado 8215
      var indented = false;
8216
      if (mode.electricChars) {
8217
        for (var j = 0; j < mode.electricChars.length; j++)
8218
          { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
15152 obado 8219
            indented = indentLine(cm, range.head.line, "smart");
14283 obado 8220
            break
8221
          } }
8222
      } else if (mode.electricInput) {
15152 obado 8223
        if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
8224
          { indented = indentLine(cm, range.head.line, "smart"); }
14283 obado 8225
      }
15152 obado 8226
      if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
14283 obado 8227
    }
8228
  }
8229
 
8230
  function copyableRanges(cm) {
8231
    var text = [], ranges = [];
8232
    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
8233
      var line = cm.doc.sel.ranges[i].head.line;
8234
      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
8235
      ranges.push(lineRange);
8236
      text.push(cm.getRange(lineRange.anchor, lineRange.head));
8237
    }
8238
    return {text: text, ranges: ranges}
8239
  }
8240
 
8241
  function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
8242
    field.setAttribute("autocorrect", autocorrect ? "" : "off");
8243
    field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
8244
    field.setAttribute("spellcheck", !!spellcheck);
8245
  }
8246
 
8247
  function hiddenTextarea() {
16493 obado 8248
    var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
14283 obado 8249
    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
8250
    // The textarea is kept positioned near the cursor to prevent the
8251
    // fact that it'll be scrolled into view on input from scrolling
8252
    // our fake cursor out of view. On webkit, when wrap=off, paste is
8253
    // very slow. So make the area wide instead.
8254
    if (webkit) { te.style.width = "1000px"; }
8255
    else { te.setAttribute("wrap", "off"); }
8256
    // If border: 0; -- iOS fails to open keyboard (issue #1287)
8257
    if (ios) { te.style.border = "1px solid black"; }
8258
    disableBrowserMagic(te);
8259
    return div
8260
  }
8261
 
8262
  // The publicly visible API. Note that methodOp(f) means
8263
  // 'wrap f in an operation, performed on its `this` parameter'.
8264
 
8265
  // This is not the complete set of editor methods. Most of the
8266
  // methods defined on the Doc type are also injected into
8267
  // CodeMirror.prototype, for backwards compatibility and
8268
  // convenience.
8269
 
8270
  function addEditorMethods(CodeMirror) {
8271
    var optionHandlers = CodeMirror.optionHandlers;
8272
 
8273
    var helpers = CodeMirror.helpers = {};
8274
 
8275
    CodeMirror.prototype = {
8276
      constructor: CodeMirror,
8277
      focus: function(){window.focus(); this.display.input.focus();},
8278
 
8279
      setOption: function(option, value) {
8280
        var options = this.options, old = options[option];
8281
        if (options[option] == value && option != "mode") { return }
8282
        options[option] = value;
8283
        if (optionHandlers.hasOwnProperty(option))
8284
          { operation(this, optionHandlers[option])(this, value, old); }
8285
        signal(this, "optionChange", this, option);
8286
      },
8287
 
8288
      getOption: function(option) {return this.options[option]},
8289
      getDoc: function() {return this.doc},
8290
 
15152 obado 8291
      addKeyMap: function(map, bottom) {
8292
        this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
14283 obado 8293
      },
15152 obado 8294
      removeKeyMap: function(map) {
14283 obado 8295
        var maps = this.state.keyMaps;
8296
        for (var i = 0; i < maps.length; ++i)
15152 obado 8297
          { if (maps[i] == map || maps[i].name == map) {
14283 obado 8298
            maps.splice(i, 1);
8299
            return true
8300
          } }
8301
      },
8302
 
8303
      addOverlay: methodOp(function(spec, options) {
8304
        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
8305
        if (mode.startState) { throw new Error("Overlays may not be stateful.") }
8306
        insertSorted(this.state.overlays,
8307
                     {mode: mode, modeSpec: spec, opaque: options && options.opaque,
8308
                      priority: (options && options.priority) || 0},
8309
                     function (overlay) { return overlay.priority; });
8310
        this.state.modeGen++;
8311
        regChange(this);
8312
      }),
8313
      removeOverlay: methodOp(function(spec) {
8314
        var overlays = this.state.overlays;
8315
        for (var i = 0; i < overlays.length; ++i) {
8316
          var cur = overlays[i].modeSpec;
8317
          if (cur == spec || typeof spec == "string" && cur.name == spec) {
8318
            overlays.splice(i, 1);
15152 obado 8319
            this.state.modeGen++;
8320
            regChange(this);
14283 obado 8321
            return
8322
          }
8323
        }
8324
      }),
8325
 
8326
      indentLine: methodOp(function(n, dir, aggressive) {
8327
        if (typeof dir != "string" && typeof dir != "number") {
8328
          if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
8329
          else { dir = dir ? "add" : "subtract"; }
8330
        }
8331
        if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
8332
      }),
8333
      indentSelection: methodOp(function(how) {
8334
        var ranges = this.doc.sel.ranges, end = -1;
8335
        for (var i = 0; i < ranges.length; i++) {
15152 obado 8336
          var range = ranges[i];
8337
          if (!range.empty()) {
8338
            var from = range.from(), to = range.to();
14283 obado 8339
            var start = Math.max(end, from.line);
15152 obado 8340
            end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
14283 obado 8341
            for (var j = start; j < end; ++j)
15152 obado 8342
              { indentLine(this, j, how); }
8343
            var newRanges = this.doc.sel.ranges;
14283 obado 8344
            if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
15152 obado 8345
              { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
8346
          } else if (range.head.line > end) {
8347
            indentLine(this, range.head.line, how, true);
8348
            end = range.head.line;
8349
            if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
14283 obado 8350
          }
8351
        }
8352
      }),
8353
 
8354
      // Fetch the parser token for a given character. Useful for hacks
8355
      // that want to inspect the mode state (say, for completion).
8356
      getTokenAt: function(pos, precise) {
8357
        return takeToken(this, pos, precise)
8358
      },
8359
 
8360
      getLineTokens: function(line, precise) {
8361
        return takeToken(this, Pos(line), precise, true)
8362
      },
8363
 
8364
      getTokenTypeAt: function(pos) {
8365
        pos = clipPos(this.doc, pos);
8366
        var styles = getLineStyles(this, getLine(this.doc, pos.line));
8367
        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
8368
        var type;
8369
        if (ch == 0) { type = styles[2]; }
8370
        else { for (;;) {
8371
          var mid = (before + after) >> 1;
8372
          if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
8373
          else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
8374
          else { type = styles[mid * 2 + 2]; break }
8375
        } }
8376
        var cut = type ? type.indexOf("overlay ") : -1;
8377
        return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
8378
      },
8379
 
8380
      getModeAt: function(pos) {
8381
        var mode = this.doc.mode;
8382
        if (!mode.innerMode) { return mode }
8383
        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
8384
      },
8385
 
8386
      getHelper: function(pos, type) {
8387
        return this.getHelpers(pos, type)[0]
8388
      },
8389
 
8390
      getHelpers: function(pos, type) {
8391
        var found = [];
8392
        if (!helpers.hasOwnProperty(type)) { return found }
8393
        var help = helpers[type], mode = this.getModeAt(pos);
8394
        if (typeof mode[type] == "string") {
8395
          if (help[mode[type]]) { found.push(help[mode[type]]); }
8396
        } else if (mode[type]) {
8397
          for (var i = 0; i < mode[type].length; i++) {
8398
            var val = help[mode[type][i]];
8399
            if (val) { found.push(val); }
8400
          }
8401
        } else if (mode.helperType && help[mode.helperType]) {
8402
          found.push(help[mode.helperType]);
8403
        } else if (help[mode.name]) {
8404
          found.push(help[mode.name]);
8405
        }
8406
        for (var i$1 = 0; i$1 < help._global.length; i$1++) {
8407
          var cur = help._global[i$1];
15152 obado 8408
          if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
14283 obado 8409
            { found.push(cur.val); }
8410
        }
8411
        return found
8412
      },
8413
 
8414
      getStateAfter: function(line, precise) {
8415
        var doc = this.doc;
8416
        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
8417
        return getContextBefore(this, line + 1, precise).state
8418
      },
8419
 
8420
      cursorCoords: function(start, mode) {
15152 obado 8421
        var pos, range = this.doc.sel.primary();
8422
        if (start == null) { pos = range.head; }
14283 obado 8423
        else if (typeof start == "object") { pos = clipPos(this.doc, start); }
15152 obado 8424
        else { pos = start ? range.from() : range.to(); }
14283 obado 8425
        return cursorCoords(this, pos, mode || "page")
8426
      },
8427
 
8428
      charCoords: function(pos, mode) {
8429
        return charCoords(this, clipPos(this.doc, pos), mode || "page")
8430
      },
8431
 
8432
      coordsChar: function(coords, mode) {
8433
        coords = fromCoordSystem(this, coords, mode || "page");
8434
        return coordsChar(this, coords.left, coords.top)
8435
      },
8436
 
8437
      lineAtHeight: function(height, mode) {
8438
        height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
8439
        return lineAtHeight(this.doc, height + this.display.viewOffset)
8440
      },
8441
      heightAtLine: function(line, mode, includeWidgets) {
8442
        var end = false, lineObj;
8443
        if (typeof line == "number") {
8444
          var last = this.doc.first + this.doc.size - 1;
8445
          if (line < this.doc.first) { line = this.doc.first; }
8446
          else if (line > last) { line = last; end = true; }
8447
          lineObj = getLine(this.doc, line);
8448
        } else {
8449
          lineObj = line;
8450
        }
8451
        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
8452
          (end ? this.doc.height - heightAtLine(lineObj) : 0)
8453
      },
8454
 
8455
      defaultTextHeight: function() { return textHeight(this.display) },
8456
      defaultCharWidth: function() { return charWidth(this.display) },
8457
 
8458
      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8459
 
8460
      addWidget: function(pos, node, scroll, vert, horiz) {
8461
        var display = this.display;
8462
        pos = cursorCoords(this, clipPos(this.doc, pos));
8463
        var top = pos.bottom, left = pos.left;
8464
        node.style.position = "absolute";
8465
        node.setAttribute("cm-ignore-events", "true");
8466
        this.display.input.setUneditable(node);
8467
        display.sizer.appendChild(node);
8468
        if (vert == "over") {
8469
          top = pos.top;
8470
        } else if (vert == "above" || vert == "near") {
8471
          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
8472
          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
8473
          // Default to positioning above (if specified and possible); otherwise default to positioning below
8474
          if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
8475
            { top = pos.top - node.offsetHeight; }
8476
          else if (pos.bottom + node.offsetHeight <= vspace)
8477
            { top = pos.bottom; }
8478
          if (left + node.offsetWidth > hspace)
8479
            { left = hspace - node.offsetWidth; }
8480
        }
8481
        node.style.top = top + "px";
8482
        node.style.left = node.style.right = "";
8483
        if (horiz == "right") {
8484
          left = display.sizer.clientWidth - node.offsetWidth;
8485
          node.style.right = "0px";
8486
        } else {
8487
          if (horiz == "left") { left = 0; }
8488
          else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
8489
          node.style.left = left + "px";
8490
        }
8491
        if (scroll)
8492
          { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
8493
      },
8494
 
8495
      triggerOnKeyDown: methodOp(onKeyDown),
8496
      triggerOnKeyPress: methodOp(onKeyPress),
8497
      triggerOnKeyUp: onKeyUp,
8498
      triggerOnMouseDown: methodOp(onMouseDown),
8499
 
8500
      execCommand: function(cmd) {
8501
        if (commands.hasOwnProperty(cmd))
8502
          { return commands[cmd].call(null, this) }
8503
      },
8504
 
8505
      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8506
 
8507
      findPosH: function(from, amount, unit, visually) {
8508
        var dir = 1;
8509
        if (amount < 0) { dir = -1; amount = -amount; }
8510
        var cur = clipPos(this.doc, from);
8511
        for (var i = 0; i < amount; ++i) {
15152 obado 8512
          cur = findPosH(this.doc, cur, dir, unit, visually);
14283 obado 8513
          if (cur.hitSide) { break }
8514
        }
8515
        return cur
8516
      },
8517
 
8518
      moveH: methodOp(function(dir, unit) {
8519
        var this$1 = this;
8520
 
15152 obado 8521
        this.extendSelectionsBy(function (range) {
8522
          if (this$1.display.shift || this$1.doc.extend || range.empty())
8523
            { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
14283 obado 8524
          else
15152 obado 8525
            { return dir < 0 ? range.from() : range.to() }
14283 obado 8526
        }, sel_move);
8527
      }),
8528
 
8529
      deleteH: methodOp(function(dir, unit) {
8530
        var sel = this.doc.sel, doc = this.doc;
8531
        if (sel.somethingSelected())
8532
          { doc.replaceSelection("", null, "+delete"); }
8533
        else
15152 obado 8534
          { deleteNearSelection(this, function (range) {
8535
            var other = findPosH(doc, range.head, dir, unit, false);
8536
            return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
14283 obado 8537
          }); }
8538
      }),
8539
 
8540
      findPosV: function(from, amount, unit, goalColumn) {
8541
        var dir = 1, x = goalColumn;
8542
        if (amount < 0) { dir = -1; amount = -amount; }
8543
        var cur = clipPos(this.doc, from);
8544
        for (var i = 0; i < amount; ++i) {
15152 obado 8545
          var coords = cursorCoords(this, cur, "div");
14283 obado 8546
          if (x == null) { x = coords.left; }
8547
          else { coords.left = x; }
15152 obado 8548
          cur = findPosV(this, coords, dir, unit);
14283 obado 8549
          if (cur.hitSide) { break }
8550
        }
8551
        return cur
8552
      },
8553
 
8554
      moveV: methodOp(function(dir, unit) {
8555
        var this$1 = this;
8556
 
8557
        var doc = this.doc, goals = [];
8558
        var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
15152 obado 8559
        doc.extendSelectionsBy(function (range) {
14283 obado 8560
          if (collapse)
15152 obado 8561
            { return dir < 0 ? range.from() : range.to() }
8562
          var headPos = cursorCoords(this$1, range.head, "div");
8563
          if (range.goalColumn != null) { headPos.left = range.goalColumn; }
14283 obado 8564
          goals.push(headPos.left);
8565
          var pos = findPosV(this$1, headPos, dir, unit);
15152 obado 8566
          if (unit == "page" && range == doc.sel.primary())
14283 obado 8567
            { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
8568
          return pos
8569
        }, sel_move);
8570
        if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
8571
          { doc.sel.ranges[i].goalColumn = goals[i]; } }
8572
      }),
8573
 
8574
      // Find the word at the given position (as returned by coordsChar).
8575
      findWordAt: function(pos) {
8576
        var doc = this.doc, line = getLine(doc, pos.line).text;
8577
        var start = pos.ch, end = pos.ch;
8578
        if (line) {
8579
          var helper = this.getHelper(pos, "wordChars");
8580
          if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
8581
          var startChar = line.charAt(start);
8582
          var check = isWordChar(startChar, helper)
8583
            ? function (ch) { return isWordChar(ch, helper); }
8584
            : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
8585
            : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
8586
          while (start > 0 && check(line.charAt(start - 1))) { --start; }
8587
          while (end < line.length && check(line.charAt(end))) { ++end; }
8588
        }
8589
        return new Range(Pos(pos.line, start), Pos(pos.line, end))
8590
      },
8591
 
8592
      toggleOverwrite: function(value) {
8593
        if (value != null && value == this.state.overwrite) { return }
8594
        if (this.state.overwrite = !this.state.overwrite)
8595
          { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8596
        else
8597
          { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8598
 
8599
        signal(this, "overwriteToggle", this, this.state.overwrite);
8600
      },
8601
      hasFocus: function() { return this.display.input.getField() == activeElt() },
8602
      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
8603
 
8604
      scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
8605
      getScrollInfo: function() {
8606
        var scroller = this.display.scroller;
8607
        return {left: scroller.scrollLeft, top: scroller.scrollTop,
8608
                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
8609
                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
8610
                clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
8611
      },
8612
 
15152 obado 8613
      scrollIntoView: methodOp(function(range, margin) {
8614
        if (range == null) {
8615
          range = {from: this.doc.sel.primary().head, to: null};
14283 obado 8616
          if (margin == null) { margin = this.options.cursorScrollMargin; }
15152 obado 8617
        } else if (typeof range == "number") {
8618
          range = {from: Pos(range, 0), to: null};
8619
        } else if (range.from == null) {
8620
          range = {from: range, to: null};
14283 obado 8621
        }
15152 obado 8622
        if (!range.to) { range.to = range.from; }
8623
        range.margin = margin || 0;
14283 obado 8624
 
15152 obado 8625
        if (range.from.line != null) {
8626
          scrollToRange(this, range);
14283 obado 8627
        } else {
15152 obado 8628
          scrollToCoordsRange(this, range.from, range.to, range.margin);
14283 obado 8629
        }
8630
      }),
8631
 
8632
      setSize: methodOp(function(width, height) {
8633
        var this$1 = this;
8634
 
8635
        var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
8636
        if (width != null) { this.display.wrapper.style.width = interpret(width); }
8637
        if (height != null) { this.display.wrapper.style.height = interpret(height); }
8638
        if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
15152 obado 8639
        var lineNo = this.display.viewFrom;
8640
        this.doc.iter(lineNo, this.display.viewTo, function (line) {
14283 obado 8641
          if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
15152 obado 8642
            { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
8643
          ++lineNo;
14283 obado 8644
        });
8645
        this.curOp.forceUpdate = true;
8646
        signal(this, "refresh", this);
8647
      }),
8648
 
8649
      operation: function(f){return runInOp(this, f)},
8650
      startOperation: function(){return startOperation(this)},
8651
      endOperation: function(){return endOperation(this)},
8652
 
8653
      refresh: methodOp(function() {
8654
        var oldHeight = this.display.cachedTextHeight;
8655
        regChange(this);
8656
        this.curOp.forceUpdate = true;
8657
        clearCaches(this);
8658
        scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
8659
        updateGutterSpace(this.display);
15152 obado 8660
        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
14283 obado 8661
          { estimateLineHeights(this); }
8662
        signal(this, "refresh", this);
8663
      }),
8664
 
8665
      swapDoc: methodOp(function(doc) {
8666
        var old = this.doc;
8667
        old.cm = null;
8668
        // Cancel the current text selection if any (#5821)
8669
        if (this.state.selectingText) { this.state.selectingText(); }
8670
        attachDoc(this, doc);
8671
        clearCaches(this);
8672
        this.display.input.reset();
8673
        scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
8674
        this.curOp.forceScroll = true;
8675
        signalLater(this, "swapDoc", this, old);
8676
        return old
8677
      }),
8678
 
8679
      phrase: function(phraseText) {
8680
        var phrases = this.options.phrases;
8681
        return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
8682
      },
8683
 
8684
      getInputField: function(){return this.display.input.getField()},
8685
      getWrapperElement: function(){return this.display.wrapper},
8686
      getScrollerElement: function(){return this.display.scroller},
8687
      getGutterElement: function(){return this.display.gutters}
8688
    };
8689
    eventMixin(CodeMirror);
8690
 
8691
    CodeMirror.registerHelper = function(type, name, value) {
8692
      if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
8693
      helpers[type][name] = value;
8694
    };
8695
    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
8696
      CodeMirror.registerHelper(type, name, value);
8697
      helpers[type]._global.push({pred: predicate, val: value});
8698
    };
8699
  }
8700
 
8701
  // Used for horizontal relative motion. Dir is -1 or 1 (left or
16493 obado 8702
  // right), unit can be "codepoint", "char", "column" (like char, but
8703
  // doesn't cross line boundaries), "word" (across next word), or
8704
  // "group" (to the start of next group of word or
8705
  // non-word-non-whitespace chars). The visually param controls
8706
  // whether, in right-to-left text, direction 1 means to move towards
8707
  // the next index in the string, or towards the character to the right
8708
  // of the current position. The resulting position will have a
8709
  // hitSide=true property if it reached the end of the document.
14283 obado 8710
  function findPosH(doc, pos, dir, unit, visually) {
8711
    var oldPos = pos;
8712
    var origDir = dir;
8713
    var lineObj = getLine(doc, pos.line);
15152 obado 8714
    var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
14283 obado 8715
    function findNextLine() {
15152 obado 8716
      var l = pos.line + lineDir;
14283 obado 8717
      if (l < doc.first || l >= doc.first + doc.size) { return false }
8718
      pos = new Pos(l, pos.ch, pos.sticky);
8719
      return lineObj = getLine(doc, l)
8720
    }
8721
    function moveOnce(boundToLine) {
8722
      var next;
16493 obado 8723
      if (unit == "codepoint") {
8724
        var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
8725
        if (isNaN(ch)) {
8726
          next = null;
8727
        } else {
8728
          var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
8729
          next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
8730
        }
8731
      } else if (visually) {
14283 obado 8732
        next = moveVisually(doc.cm, lineObj, pos, dir);
8733
      } else {
8734
        next = moveLogically(lineObj, pos, dir);
8735
      }
8736
      if (next == null) {
8737
        if (!boundToLine && findNextLine())
15152 obado 8738
          { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
14283 obado 8739
        else
8740
          { return false }
8741
      } else {
8742
        pos = next;
8743
      }
8744
      return true
8745
    }
8746
 
16493 obado 8747
    if (unit == "char" || unit == "codepoint") {
14283 obado 8748
      moveOnce();
8749
    } else if (unit == "column") {
8750
      moveOnce(true);
8751
    } else if (unit == "word" || unit == "group") {
8752
      var sawType = null, group = unit == "group";
8753
      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
8754
      for (var first = true;; first = false) {
8755
        if (dir < 0 && !moveOnce(!first)) { break }
8756
        var cur = lineObj.text.charAt(pos.ch) || "\n";
8757
        var type = isWordChar(cur, helper) ? "w"
8758
          : group && cur == "\n" ? "n"
8759
          : !group || /\s/.test(cur) ? null
8760
          : "p";
8761
        if (group && !first && !type) { type = "s"; }
8762
        if (sawType && sawType != type) {
8763
          if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
8764
          break
8765
        }
8766
 
8767
        if (type) { sawType = type; }
8768
        if (dir > 0 && !moveOnce(!first)) { break }
8769
      }
8770
    }
8771
    var result = skipAtomic(doc, pos, oldPos, origDir, true);
8772
    if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8773
    return result
8774
  }
8775
 
8776
  // For relative vertical movement. Dir may be -1 or 1. Unit can be
8777
  // "page" or "line". The resulting position will have a hitSide=true
8778
  // property if it reached the end of the document.
8779
  function findPosV(cm, pos, dir, unit) {
8780
    var doc = cm.doc, x = pos.left, y;
8781
    if (unit == "page") {
8782
      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
8783
      var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
8784
      y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
8785
 
8786
    } else if (unit == "line") {
8787
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8788
    }
8789
    var target;
8790
    for (;;) {
8791
      target = coordsChar(cm, x, y);
8792
      if (!target.outside) { break }
8793
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
8794
      y += dir * 5;
8795
    }
8796
    return target
8797
  }
8798
 
8799
  // CONTENTEDITABLE INPUT STYLE
8800
 
8801
  var ContentEditableInput = function(cm) {
8802
    this.cm = cm;
8803
    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
8804
    this.polling = new Delayed();
8805
    this.composing = null;
8806
    this.gracePeriod = false;
8807
    this.readDOMTimeout = null;
8808
  };
8809
 
8810
  ContentEditableInput.prototype.init = function (display) {
8811
      var this$1 = this;
8812
 
8813
    var input = this, cm = input.cm;
8814
    var div = input.div = display.lineDiv;
16493 obado 8815
    div.contentEditable = true;
14283 obado 8816
    disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
8817
 
15152 obado 8818
    function belongsToInput(e) {
8819
      for (var t = e.target; t; t = t.parentNode) {
8820
        if (t == div) { return true }
8821
        if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
8822
      }
8823
      return false
8824
    }
8825
 
14283 obado 8826
    on(div, "paste", function (e) {
15152 obado 8827
      if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
14283 obado 8828
      // IE doesn't fire input events, so we schedule a read for the pasted content in this way
8829
      if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
8830
    });
8831
 
8832
    on(div, "compositionstart", function (e) {
8833
      this$1.composing = {data: e.data, done: false};
8834
    });
8835
    on(div, "compositionupdate", function (e) {
8836
      if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
8837
    });
8838
    on(div, "compositionend", function (e) {
8839
      if (this$1.composing) {
8840
        if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
8841
        this$1.composing.done = true;
8842
      }
8843
    });
8844
 
8845
    on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8846
 
8847
    on(div, "input", function () {
8848
      if (!this$1.composing) { this$1.readFromDOMSoon(); }
8849
    });
8850
 
8851
    function onCopyCut(e) {
15152 obado 8852
      if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
14283 obado 8853
      if (cm.somethingSelected()) {
8854
        setLastCopied({lineWise: false, text: cm.getSelections()});
8855
        if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
8856
      } else if (!cm.options.lineWiseCopyCut) {
8857
        return
8858
      } else {
8859
        var ranges = copyableRanges(cm);
8860
        setLastCopied({lineWise: true, text: ranges.text});
8861
        if (e.type == "cut") {
8862
          cm.operation(function () {
8863
            cm.setSelections(ranges.ranges, 0, sel_dontScroll);
8864
            cm.replaceSelection("", null, "cut");
8865
          });
8866
        }
8867
      }
8868
      if (e.clipboardData) {
8869
        e.clipboardData.clearData();
8870
        var content = lastCopied.text.join("\n");
8871
        // iOS exposes the clipboard API, but seems to discard content inserted into it
8872
        e.clipboardData.setData("Text", content);
8873
        if (e.clipboardData.getData("Text") == content) {
8874
          e.preventDefault();
8875
          return
8876
        }
8877
      }
8878
      // Old-fashioned briefly-focus-a-textarea hack
8879
      var kludge = hiddenTextarea(), te = kludge.firstChild;
8880
      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
8881
      te.value = lastCopied.text.join("\n");
16493 obado 8882
      var hadFocus = activeElt();
14283 obado 8883
      selectInput(te);
8884
      setTimeout(function () {
8885
        cm.display.lineSpace.removeChild(kludge);
8886
        hadFocus.focus();
8887
        if (hadFocus == div) { input.showPrimarySelection(); }
8888
      }, 50);
8889
    }
8890
    on(div, "copy", onCopyCut);
8891
    on(div, "cut", onCopyCut);
8892
  };
8893
 
15152 obado 8894
  ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
8895
    // Label for screenreaders, accessibility
8896
    if(label) {
8897
      this.div.setAttribute('aria-label', label);
8898
    } else {
8899
      this.div.removeAttribute('aria-label');
8900
    }
8901
  };
8902
 
14283 obado 8903
  ContentEditableInput.prototype.prepareSelection = function () {
8904
    var result = prepareSelection(this.cm, false);
16493 obado 8905
    result.focus = activeElt() == this.div;
14283 obado 8906
    return result
8907
  };
8908
 
8909
  ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
8910
    if (!info || !this.cm.display.view.length) { return }
8911
    if (info.focus || takeFocus) { this.showPrimarySelection(); }
8912
    this.showMultipleSelections(info);
8913
  };
8914
 
8915
  ContentEditableInput.prototype.getSelection = function () {
8916
    return this.cm.display.wrapper.ownerDocument.getSelection()
8917
  };
8918
 
8919
  ContentEditableInput.prototype.showPrimarySelection = function () {
8920
    var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
8921
    var from = prim.from(), to = prim.to();
8922
 
8923
    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8924
      sel.removeAllRanges();
8925
      return
8926
    }
8927
 
8928
    var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8929
    var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
8930
    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
8931
        cmp(minPos(curAnchor, curFocus), from) == 0 &&
8932
        cmp(maxPos(curAnchor, curFocus), to) == 0)
8933
      { return }
8934
 
8935
    var view = cm.display.view;
8936
    var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
8937
        {node: view[0].measure.map[2], offset: 0};
8938
    var end = to.line < cm.display.viewTo && posToDOM(cm, to);
8939
    if (!end) {
8940
      var measure = view[view.length - 1].measure;
15152 obado 8941
      var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
8942
      end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
14283 obado 8943
    }
8944
 
8945
    if (!start || !end) {
8946
      sel.removeAllRanges();
8947
      return
8948
    }
8949
 
8950
    var old = sel.rangeCount && sel.getRangeAt(0), rng;
8951
    try { rng = range(start.node, start.offset, end.offset, end.node); }
8952
    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
8953
    if (rng) {
8954
      if (!gecko && cm.state.focused) {
8955
        sel.collapse(start.node, start.offset);
8956
        if (!rng.collapsed) {
8957
          sel.removeAllRanges();
8958
          sel.addRange(rng);
8959
        }
8960
      } else {
8961
        sel.removeAllRanges();
8962
        sel.addRange(rng);
8963
      }
8964
      if (old && sel.anchorNode == null) { sel.addRange(old); }
8965
      else if (gecko) { this.startGracePeriod(); }
8966
    }
8967
    this.rememberSelection();
8968
  };
8969
 
8970
  ContentEditableInput.prototype.startGracePeriod = function () {
8971
      var this$1 = this;
8972
 
8973
    clearTimeout(this.gracePeriod);
8974
    this.gracePeriod = setTimeout(function () {
8975
      this$1.gracePeriod = false;
8976
      if (this$1.selectionChanged())
8977
        { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
8978
    }, 20);
8979
  };
8980
 
8981
  ContentEditableInput.prototype.showMultipleSelections = function (info) {
8982
    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
8983
    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
8984
  };
8985
 
8986
  ContentEditableInput.prototype.rememberSelection = function () {
8987
    var sel = this.getSelection();
8988
    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
8989
    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
8990
  };
8991
 
8992
  ContentEditableInput.prototype.selectionInEditor = function () {
8993
    var sel = this.getSelection();
8994
    if (!sel.rangeCount) { return false }
8995
    var node = sel.getRangeAt(0).commonAncestorContainer;
8996
    return contains(this.div, node)
8997
  };
8998
 
8999
  ContentEditableInput.prototype.focus = function () {
9000
    if (this.cm.options.readOnly != "nocursor") {
16493 obado 9001
      if (!this.selectionInEditor() || activeElt() != this.div)
14283 obado 9002
        { this.showSelection(this.prepareSelection(), true); }
9003
      this.div.focus();
9004
    }
9005
  };
9006
  ContentEditableInput.prototype.blur = function () { this.div.blur(); };
9007
  ContentEditableInput.prototype.getField = function () { return this.div };
9008
 
9009
  ContentEditableInput.prototype.supportsTouch = function () { return true };
9010
 
9011
  ContentEditableInput.prototype.receivedFocus = function () {
16493 obado 9012
      var this$1 = this;
9013
 
14283 obado 9014
    var input = this;
9015
    if (this.selectionInEditor())
16493 obado 9016
      { setTimeout(function () { return this$1.pollSelection(); }, 20); }
14283 obado 9017
    else
9018
      { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
9019
 
9020
    function poll() {
9021
      if (input.cm.state.focused) {
9022
        input.pollSelection();
9023
        input.polling.set(input.cm.options.pollInterval, poll);
9024
      }
9025
    }
9026
    this.polling.set(this.cm.options.pollInterval, poll);
9027
  };
9028
 
9029
  ContentEditableInput.prototype.selectionChanged = function () {
9030
    var sel = this.getSelection();
9031
    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
9032
      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
9033
  };
9034
 
9035
  ContentEditableInput.prototype.pollSelection = function () {
9036
    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
9037
    var sel = this.getSelection(), cm = this.cm;
9038
    // On Android Chrome (version 56, at least), backspacing into an
9039
    // uneditable block element will put the cursor in that element,
9040
    // and then, because it's not editable, hide the virtual keyboard.
9041
    // Because Android doesn't allow us to actually detect backspace
9042
    // presses in a sane way, this code checks for when that happens
9043
    // and simulates a backspace press in this case.
9044
    if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
9045
      this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
9046
      this.blur();
9047
      this.focus();
9048
      return
9049
    }
9050
    if (this.composing) { return }
9051
    this.rememberSelection();
9052
    var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
9053
    var head = domToPos(cm, sel.focusNode, sel.focusOffset);
9054
    if (anchor && head) { runInOp(cm, function () {
9055
      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
9056
      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
9057
    }); }
9058
  };
9059
 
9060
  ContentEditableInput.prototype.pollContent = function () {
9061
    if (this.readDOMTimeout != null) {
9062
      clearTimeout(this.readDOMTimeout);
9063
      this.readDOMTimeout = null;
9064
    }
9065
 
9066
    var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
9067
    var from = sel.from(), to = sel.to();
9068
    if (from.ch == 0 && from.line > cm.firstLine())
9069
      { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
9070
    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
9071
      { to = Pos(to.line + 1, 0); }
9072
    if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
9073
 
9074
    var fromIndex, fromLine, fromNode;
9075
    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
9076
      fromLine = lineNo(display.view[0].line);
9077
      fromNode = display.view[0].node;
9078
    } else {
9079
      fromLine = lineNo(display.view[fromIndex].line);
9080
      fromNode = display.view[fromIndex - 1].node.nextSibling;
9081
    }
9082
    var toIndex = findViewIndex(cm, to.line);
9083
    var toLine, toNode;
9084
    if (toIndex == display.view.length - 1) {
9085
      toLine = display.viewTo - 1;
9086
      toNode = display.lineDiv.lastChild;
9087
    } else {
9088
      toLine = lineNo(display.view[toIndex + 1].line) - 1;
9089
      toNode = display.view[toIndex + 1].node.previousSibling;
9090
    }
9091
 
9092
    if (!fromNode) { return false }
9093
    var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
9094
    var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
9095
    while (newText.length > 1 && oldText.length > 1) {
9096
      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
9097
      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
9098
      else { break }
9099
    }
9100
 
9101
    var cutFront = 0, cutEnd = 0;
9102
    var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
9103
    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
9104
      { ++cutFront; }
9105
    var newBot = lst(newText), oldBot = lst(oldText);
9106
    var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
9107
                             oldBot.length - (oldText.length == 1 ? cutFront : 0));
9108
    while (cutEnd < maxCutEnd &&
9109
           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
9110
      { ++cutEnd; }
9111
    // Try to move start of change to start of selection if ambiguous
9112
    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
9113
      while (cutFront && cutFront > from.ch &&
9114
             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
9115
        cutFront--;
9116
        cutEnd++;
9117
      }
9118
    }
9119
 
9120
    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
9121
    newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
9122
 
9123
    var chFrom = Pos(fromLine, cutFront);
9124
    var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
9125
    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
9126
      replaceRange(cm.doc, newText, chFrom, chTo, "+input");
9127
      return true
9128
    }
9129
  };
9130
 
9131
  ContentEditableInput.prototype.ensurePolled = function () {
9132
    this.forceCompositionEnd();
9133
  };
9134
  ContentEditableInput.prototype.reset = function () {
9135
    this.forceCompositionEnd();
9136
  };
9137
  ContentEditableInput.prototype.forceCompositionEnd = function () {
9138
    if (!this.composing) { return }
9139
    clearTimeout(this.readDOMTimeout);
9140
    this.composing = null;
9141
    this.updateFromDOM();
9142
    this.div.blur();
9143
    this.div.focus();
9144
  };
9145
  ContentEditableInput.prototype.readFromDOMSoon = function () {
9146
      var this$1 = this;
9147
 
9148
    if (this.readDOMTimeout != null) { return }
9149
    this.readDOMTimeout = setTimeout(function () {
9150
      this$1.readDOMTimeout = null;
9151
      if (this$1.composing) {
9152
        if (this$1.composing.done) { this$1.composing = null; }
9153
        else { return }
9154
      }
9155
      this$1.updateFromDOM();
9156
    }, 80);
9157
  };
9158
 
9159
  ContentEditableInput.prototype.updateFromDOM = function () {
9160
      var this$1 = this;
9161
 
9162
    if (this.cm.isReadOnly() || !this.pollContent())
9163
      { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
9164
  };
9165
 
9166
  ContentEditableInput.prototype.setUneditable = function (node) {
9167
    node.contentEditable = "false";
9168
  };
9169
 
9170
  ContentEditableInput.prototype.onKeyPress = function (e) {
9171
    if (e.charCode == 0 || this.composing) { return }
9172
    e.preventDefault();
9173
    if (!this.cm.isReadOnly())
9174
      { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
9175
  };
9176
 
9177
  ContentEditableInput.prototype.readOnlyChanged = function (val) {
9178
    this.div.contentEditable = String(val != "nocursor");
9179
  };
9180
 
9181
  ContentEditableInput.prototype.onContextMenu = function () {};
9182
  ContentEditableInput.prototype.resetPosition = function () {};
9183
 
9184
  ContentEditableInput.prototype.needsContentAttribute = true;
9185
 
9186
  function posToDOM(cm, pos) {
9187
    var view = findViewForLine(cm, pos.line);
9188
    if (!view || view.hidden) { return null }
9189
    var line = getLine(cm.doc, pos.line);
9190
    var info = mapFromLineView(view, line, pos.line);
9191
 
9192
    var order = getOrder(line, cm.doc.direction), side = "left";
9193
    if (order) {
9194
      var partPos = getBidiPartAt(order, pos.ch);
9195
      side = partPos % 2 ? "right" : "left";
9196
    }
9197
    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9198
    result.offset = result.collapse == "right" ? result.end : result.start;
9199
    return result
9200
  }
9201
 
9202
  function isInGutter(node) {
9203
    for (var scan = node; scan; scan = scan.parentNode)
9204
      { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
9205
    return false
9206
  }
9207
 
9208
  function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9209
 
9210
  function domTextBetween(cm, from, to, fromLine, toLine) {
9211
    var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
9212
    function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
9213
    function close() {
9214
      if (closing) {
9215
        text += lineSep;
9216
        if (extraLinebreak) { text += lineSep; }
9217
        closing = extraLinebreak = false;
9218
      }
9219
    }
9220
    function addText(str) {
9221
      if (str) {
9222
        close();
9223
        text += str;
9224
      }
9225
    }
9226
    function walk(node) {
9227
      if (node.nodeType == 1) {
9228
        var cmText = node.getAttribute("cm-text");
9229
        if (cmText) {
9230
          addText(cmText);
9231
          return
9232
        }
15152 obado 9233
        var markerID = node.getAttribute("cm-marker"), range;
14283 obado 9234
        if (markerID) {
9235
          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
15152 obado 9236
          if (found.length && (range = found[0].find(0)))
9237
            { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
14283 obado 9238
          return
9239
        }
9240
        if (node.getAttribute("contenteditable") == "false") { return }
9241
        var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
9242
        if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
9243
 
9244
        if (isBlock) { close(); }
9245
        for (var i = 0; i < node.childNodes.length; i++)
9246
          { walk(node.childNodes[i]); }
9247
 
9248
        if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
9249
        if (isBlock) { closing = true; }
9250
      } else if (node.nodeType == 3) {
9251
        addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
9252
      }
9253
    }
9254
    for (;;) {
9255
      walk(from);
9256
      if (from == to) { break }
9257
      from = from.nextSibling;
9258
      extraLinebreak = false;
9259
    }
9260
    return text
9261
  }
9262
 
9263
  function domToPos(cm, node, offset) {
9264
    var lineNode;
9265
    if (node == cm.display.lineDiv) {
9266
      lineNode = cm.display.lineDiv.childNodes[offset];
9267
      if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
9268
      node = null; offset = 0;
9269
    } else {
9270
      for (lineNode = node;; lineNode = lineNode.parentNode) {
9271
        if (!lineNode || lineNode == cm.display.lineDiv) { return null }
9272
        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
9273
      }
9274
    }
9275
    for (var i = 0; i < cm.display.view.length; i++) {
9276
      var lineView = cm.display.view[i];
9277
      if (lineView.node == lineNode)
9278
        { return locateNodeInLineView(lineView, node, offset) }
9279
    }
9280
  }
9281
 
9282
  function locateNodeInLineView(lineView, node, offset) {
9283
    var wrapper = lineView.text.firstChild, bad = false;
9284
    if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
9285
    if (node == wrapper) {
9286
      bad = true;
9287
      node = wrapper.childNodes[offset];
9288
      offset = 0;
9289
      if (!node) {
9290
        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
9291
        return badPos(Pos(lineNo(line), line.text.length), bad)
9292
      }
9293
    }
9294
 
9295
    var textNode = node.nodeType == 3 ? node : null, topNode = node;
9296
    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
9297
      textNode = node.firstChild;
9298
      if (offset) { offset = textNode.nodeValue.length; }
9299
    }
9300
    while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
9301
    var measure = lineView.measure, maps = measure.maps;
9302
 
9303
    function find(textNode, topNode, offset) {
9304
      for (var i = -1; i < (maps ? maps.length : 0); i++) {
15152 obado 9305
        var map = i < 0 ? measure.map : maps[i];
9306
        for (var j = 0; j < map.length; j += 3) {
9307
          var curNode = map[j + 2];
14283 obado 9308
          if (curNode == textNode || curNode == topNode) {
9309
            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
15152 obado 9310
            var ch = map[j] + offset;
9311
            if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
14283 obado 9312
            return Pos(line, ch)
9313
          }
9314
        }
9315
      }
9316
    }
9317
    var found = find(textNode, topNode, offset);
9318
    if (found) { return badPos(found, bad) }
9319
 
9320
    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
9321
    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
9322
      found = find(after, after.firstChild, 0);
9323
      if (found)
9324
        { return badPos(Pos(found.line, found.ch - dist), bad) }
9325
      else
9326
        { dist += after.textContent.length; }
9327
    }
9328
    for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
9329
      found = find(before, before.firstChild, -1);
9330
      if (found)
9331
        { return badPos(Pos(found.line, found.ch + dist$1), bad) }
9332
      else
9333
        { dist$1 += before.textContent.length; }
9334
    }
9335
  }
9336
 
9337
  // TEXTAREA INPUT STYLE
9338
 
9339
  var TextareaInput = function(cm) {
9340
    this.cm = cm;
9341
    // See input.poll and input.reset
9342
    this.prevInput = "";
9343
 
9344
    // Flag that indicates whether we expect input to appear real soon
9345
    // now (after some event like 'keypress' or 'input') and are
9346
    // polling intensively.
9347
    this.pollingFast = false;
9348
    // Self-resetting timeout for the poller
9349
    this.polling = new Delayed();
9350
    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
9351
    this.hasSelection = false;
9352
    this.composing = null;
9353
  };
9354
 
9355
  TextareaInput.prototype.init = function (display) {
9356
      var this$1 = this;
9357
 
9358
    var input = this, cm = this.cm;
9359
    this.createField(display);
9360
    var te = this.textarea;
9361
 
9362
    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
9363
 
9364
    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
9365
    if (ios) { te.style.width = "0px"; }
9366
 
9367
    on(te, "input", function () {
9368
      if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9369
      input.poll();
9370
    });
9371
 
9372
    on(te, "paste", function (e) {
9373
      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9374
 
9375
      cm.state.pasteIncoming = +new Date;
9376
      input.fastPoll();
9377
    });
9378
 
9379
    function prepareCopyCut(e) {
9380
      if (signalDOMEvent(cm, e)) { return }
9381
      if (cm.somethingSelected()) {
9382
        setLastCopied({lineWise: false, text: cm.getSelections()});
9383
      } else if (!cm.options.lineWiseCopyCut) {
9384
        return
9385
      } else {
9386
        var ranges = copyableRanges(cm);
9387
        setLastCopied({lineWise: true, text: ranges.text});
9388
        if (e.type == "cut") {
9389
          cm.setSelections(ranges.ranges, null, sel_dontScroll);
9390
        } else {
9391
          input.prevInput = "";
9392
          te.value = ranges.text.join("\n");
9393
          selectInput(te);
9394
        }
9395
      }
9396
      if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
9397
    }
9398
    on(te, "cut", prepareCopyCut);
9399
    on(te, "copy", prepareCopyCut);
9400
 
9401
    on(display.scroller, "paste", function (e) {
9402
      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
9403
      if (!te.dispatchEvent) {
9404
        cm.state.pasteIncoming = +new Date;
9405
        input.focus();
9406
        return
9407
      }
9408
 
9409
      // Pass the `paste` event to the textarea so it's handled by its event listener.
9410
      var event = new Event("paste");
9411
      event.clipboardData = e.clipboardData;
9412
      te.dispatchEvent(event);
9413
    });
9414
 
9415
    // Prevent normal selection in the editor (we handle our own)
9416
    on(display.lineSpace, "selectstart", function (e) {
9417
      if (!eventInWidget(display, e)) { e_preventDefault(e); }
9418
    });
9419
 
9420
    on(te, "compositionstart", function () {
9421
      var start = cm.getCursor("from");
9422
      if (input.composing) { input.composing.range.clear(); }
9423
      input.composing = {
9424
        start: start,
9425
        range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
9426
      };
9427
    });
9428
    on(te, "compositionend", function () {
9429
      if (input.composing) {
9430
        input.poll();
9431
        input.composing.range.clear();
9432
        input.composing = null;
9433
      }
9434
    });
9435
  };
9436
 
9437
  TextareaInput.prototype.createField = function (_display) {
9438
    // Wraps and hides input textarea
9439
    this.wrapper = hiddenTextarea();
9440
    // The semihidden textarea that is focused when the editor is
9441
    // focused, and receives input.
9442
    this.textarea = this.wrapper.firstChild;
9443
  };
9444
 
15152 obado 9445
  TextareaInput.prototype.screenReaderLabelChanged = function (label) {
9446
    // Label for screenreaders, accessibility
9447
    if(label) {
9448
      this.textarea.setAttribute('aria-label', label);
9449
    } else {
9450
      this.textarea.removeAttribute('aria-label');
9451
    }
9452
  };
9453
 
14283 obado 9454
  TextareaInput.prototype.prepareSelection = function () {
9455
    // Redraw the selection and/or cursor
9456
    var cm = this.cm, display = cm.display, doc = cm.doc;
9457
    var result = prepareSelection(cm);
9458
 
9459
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
9460
    if (cm.options.moveInputWithCursor) {
9461
      var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
9462
      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
9463
      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
9464
                                          headPos.top + lineOff.top - wrapOff.top));
9465
      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
9466
                                           headPos.left + lineOff.left - wrapOff.left));
9467
    }
9468
 
9469
    return result
9470
  };
9471
 
9472
  TextareaInput.prototype.showSelection = function (drawn) {
9473
    var cm = this.cm, display = cm.display;
9474
    removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
9475
    removeChildrenAndAdd(display.selectionDiv, drawn.selection);
9476
    if (drawn.teTop != null) {
9477
      this.wrapper.style.top = drawn.teTop + "px";
9478
      this.wrapper.style.left = drawn.teLeft + "px";
9479
    }
9480
  };
9481
 
9482
  // Reset the input to correspond to the selection (or to be empty,
9483
  // when not typing and nothing is selected)
9484
  TextareaInput.prototype.reset = function (typing) {
9485
    if (this.contextMenuPending || this.composing) { return }
9486
    var cm = this.cm;
9487
    if (cm.somethingSelected()) {
9488
      this.prevInput = "";
9489
      var content = cm.getSelection();
9490
      this.textarea.value = content;
9491
      if (cm.state.focused) { selectInput(this.textarea); }
9492
      if (ie && ie_version >= 9) { this.hasSelection = content; }
9493
    } else if (!typing) {
9494
      this.prevInput = this.textarea.value = "";
9495
      if (ie && ie_version >= 9) { this.hasSelection = null; }
9496
    }
9497
  };
9498
 
9499
  TextareaInput.prototype.getField = function () { return this.textarea };
9500
 
9501
  TextareaInput.prototype.supportsTouch = function () { return false };
9502
 
9503
  TextareaInput.prototype.focus = function () {
9504
    if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
9505
      try { this.textarea.focus(); }
9506
      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
9507
    }
9508
  };
9509
 
9510
  TextareaInput.prototype.blur = function () { this.textarea.blur(); };
9511
 
9512
  TextareaInput.prototype.resetPosition = function () {
9513
    this.wrapper.style.top = this.wrapper.style.left = 0;
9514
  };
9515
 
9516
  TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
9517
 
9518
  // Poll for input changes, using the normal rate of polling. This
9519
  // runs as long as the editor is focused.
9520
  TextareaInput.prototype.slowPoll = function () {
9521
      var this$1 = this;
9522
 
9523
    if (this.pollingFast) { return }
9524
    this.polling.set(this.cm.options.pollInterval, function () {
9525
      this$1.poll();
9526
      if (this$1.cm.state.focused) { this$1.slowPoll(); }
9527
    });
9528
  };
9529
 
9530
  // When an event has just come in that is likely to add or change
9531
  // something in the input textarea, we poll faster, to ensure that
9532
  // the change appears on the screen quickly.
9533
  TextareaInput.prototype.fastPoll = function () {
9534
    var missed = false, input = this;
9535
    input.pollingFast = true;
9536
    function p() {
9537
      var changed = input.poll();
9538
      if (!changed && !missed) {missed = true; input.polling.set(60, p);}
9539
      else {input.pollingFast = false; input.slowPoll();}
9540
    }
9541
    input.polling.set(20, p);
9542
  };
9543
 
9544
  // Read input from the textarea, and update the document to match.
9545
  // When something is selected, it is present in the textarea, and
9546
  // selected (unless it is huge, in which case a placeholder is
9547
  // used). When nothing is selected, the cursor sits after previously
9548
  // seen text (can be empty), which is stored in prevInput (we must
9549
  // not reset the textarea when typing, because that breaks IME).
9550
  TextareaInput.prototype.poll = function () {
9551
      var this$1 = this;
9552
 
9553
    var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
9554
    // Since this is called a *lot*, try to bail out as cheaply as
9555
    // possible when it is clear that nothing happened. hasSelection
9556
    // will be the case when there is a lot of text in the textarea,
9557
    // in which case reading its value would be expensive.
9558
    if (this.contextMenuPending || !cm.state.focused ||
9559
        (hasSelection(input) && !prevInput && !this.composing) ||
9560
        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
9561
      { return false }
9562
 
9563
    var text = input.value;
9564
    // If nothing changed, bail.
9565
    if (text == prevInput && !cm.somethingSelected()) { return false }
9566
    // Work around nonsensical selection resetting in IE9/10, and
9567
    // inexplicable appearance of private area unicode characters on
9568
    // some key combos in Mac (#2689).
9569
    if (ie && ie_version >= 9 && this.hasSelection === text ||
9570
        mac && /[\uf700-\uf7ff]/.test(text)) {
9571
      cm.display.input.reset();
9572
      return false
9573
    }
9574
 
9575
    if (cm.doc.sel == cm.display.selForContextMenu) {
9576
      var first = text.charCodeAt(0);
9577
      if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
9578
      if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
9579
    }
9580
    // Find the part of the input that is actually new
9581
    var same = 0, l = Math.min(prevInput.length, text.length);
9582
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
9583
 
9584
    runInOp(cm, function () {
9585
      applyTextInput(cm, text.slice(same), prevInput.length - same,
9586
                     null, this$1.composing ? "*compose" : null);
9587
 
9588
      // Don't leave long text in the textarea, since it makes further polling slow
9589
      if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
9590
      else { this$1.prevInput = text; }
9591
 
9592
      if (this$1.composing) {
9593
        this$1.composing.range.clear();
9594
        this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
9595
                                           {className: "CodeMirror-composing"});
9596
      }
9597
    });
9598
    return true
9599
  };
9600
 
9601
  TextareaInput.prototype.ensurePolled = function () {
9602
    if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9603
  };
9604
 
9605
  TextareaInput.prototype.onKeyPress = function () {
9606
    if (ie && ie_version >= 9) { this.hasSelection = null; }
9607
    this.fastPoll();
9608
  };
9609
 
9610
  TextareaInput.prototype.onContextMenu = function (e) {
9611
    var input = this, cm = input.cm, display = cm.display, te = input.textarea;
9612
    if (input.contextMenuPending) { input.contextMenuPending(); }
9613
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
9614
    if (!pos || presto) { return } // Opera is difficult.
9615
 
9616
    // Reset the current text selection only if the click is done outside of the selection
9617
    // and 'resetSelectionOnContextMenu' option is true.
9618
    var reset = cm.options.resetSelectionOnContextMenu;
9619
    if (reset && cm.doc.sel.contains(pos) == -1)
9620
      { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
9621
 
9622
    var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
9623
    var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
9624
    input.wrapper.style.cssText = "position: static";
9625
    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);";
9626
    var oldScrollY;
9627
    if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
9628
    display.input.focus();
9629
    if (webkit) { window.scrollTo(null, oldScrollY); }
9630
    display.input.reset();
9631
    // Adds "Select all" to context menu in FF
9632
    if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
9633
    input.contextMenuPending = rehide;
9634
    display.selForContextMenu = cm.doc.sel;
9635
    clearTimeout(display.detectingSelectAll);
9636
 
9637
    // Select-all will be greyed out if there's nothing to select, so
9638
    // this adds a zero-width space so that we can later check whether
9639
    // it got selected.
9640
    function prepareSelectAllHack() {
9641
      if (te.selectionStart != null) {
9642
        var selected = cm.somethingSelected();
9643
        var extval = "\u200b" + (selected ? te.value : "");
9644
        te.value = "\u21da"; // Used to catch context-menu undo
9645
        te.value = extval;
9646
        input.prevInput = selected ? "" : "\u200b";
9647
        te.selectionStart = 1; te.selectionEnd = extval.length;
9648
        // Re-set this, in case some other handler touched the
9649
        // selection in the meantime.
9650
        display.selForContextMenu = cm.doc.sel;
9651
      }
9652
    }
9653
    function rehide() {
9654
      if (input.contextMenuPending != rehide) { return }
9655
      input.contextMenuPending = false;
9656
      input.wrapper.style.cssText = oldWrapperCSS;
9657
      te.style.cssText = oldCSS;
9658
      if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
9659
 
9660
      // Try to detect the user choosing select-all
9661
      if (te.selectionStart != null) {
9662
        if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
9663
        var i = 0, poll = function () {
9664
          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
9665
              te.selectionEnd > 0 && input.prevInput == "\u200b") {
9666
            operation(cm, selectAll)(cm);
9667
          } else if (i++ < 10) {
9668
            display.detectingSelectAll = setTimeout(poll, 500);
9669
          } else {
9670
            display.selForContextMenu = null;
9671
            display.input.reset();
9672
          }
9673
        };
9674
        display.detectingSelectAll = setTimeout(poll, 200);
9675
      }
9676
    }
9677
 
9678
    if (ie && ie_version >= 9) { prepareSelectAllHack(); }
9679
    if (captureRightClick) {
9680
      e_stop(e);
9681
      var mouseup = function () {
9682
        off(window, "mouseup", mouseup);
9683
        setTimeout(rehide, 20);
9684
      };
9685
      on(window, "mouseup", mouseup);
9686
    } else {
9687
      setTimeout(rehide, 50);
9688
    }
9689
  };
9690
 
9691
  TextareaInput.prototype.readOnlyChanged = function (val) {
9692
    if (!val) { this.reset(); }
9693
    this.textarea.disabled = val == "nocursor";
16493 obado 9694
    this.textarea.readOnly = !!val;
14283 obado 9695
  };
9696
 
9697
  TextareaInput.prototype.setUneditable = function () {};
9698
 
9699
  TextareaInput.prototype.needsContentAttribute = false;
9700
 
9701
  function fromTextArea(textarea, options) {
9702
    options = options ? copyObj(options) : {};
9703
    options.value = textarea.value;
9704
    if (!options.tabindex && textarea.tabIndex)
9705
      { options.tabindex = textarea.tabIndex; }
9706
    if (!options.placeholder && textarea.placeholder)
9707
      { options.placeholder = textarea.placeholder; }
9708
    // Set autofocus to true if this textarea is focused, or if it has
9709
    // autofocus and no other element is focused.
9710
    if (options.autofocus == null) {
9711
      var hasFocus = activeElt();
9712
      options.autofocus = hasFocus == textarea ||
9713
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
9714
    }
9715
 
9716
    function save() {textarea.value = cm.getValue();}
9717
 
9718
    var realSubmit;
9719
    if (textarea.form) {
9720
      on(textarea.form, "submit", save);
9721
      // Deplorable hack to make the submit method do the right thing.
9722
      if (!options.leaveSubmitMethodAlone) {
9723
        var form = textarea.form;
9724
        realSubmit = form.submit;
9725
        try {
9726
          var wrappedSubmit = form.submit = function () {
9727
            save();
9728
            form.submit = realSubmit;
9729
            form.submit();
9730
            form.submit = wrappedSubmit;
9731
          };
9732
        } catch(e) {}
9733
      }
9734
    }
9735
 
9736
    options.finishInit = function (cm) {
9737
      cm.save = save;
9738
      cm.getTextArea = function () { return textarea; };
9739
      cm.toTextArea = function () {
9740
        cm.toTextArea = isNaN; // Prevent this from being ran twice
9741
        save();
9742
        textarea.parentNode.removeChild(cm.getWrapperElement());
9743
        textarea.style.display = "";
9744
        if (textarea.form) {
9745
          off(textarea.form, "submit", save);
15152 obado 9746
          if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
14283 obado 9747
            { textarea.form.submit = realSubmit; }
9748
        }
9749
      };
9750
    };
9751
 
9752
    textarea.style.display = "none";
9753
    var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
9754
      options);
9755
    return cm
9756
  }
9757
 
9758
  function addLegacyProps(CodeMirror) {
9759
    CodeMirror.off = off;
9760
    CodeMirror.on = on;
9761
    CodeMirror.wheelEventPixels = wheelEventPixels;
9762
    CodeMirror.Doc = Doc;
9763
    CodeMirror.splitLines = splitLinesAuto;
9764
    CodeMirror.countColumn = countColumn;
9765
    CodeMirror.findColumn = findColumn;
9766
    CodeMirror.isWordChar = isWordCharBasic;
9767
    CodeMirror.Pass = Pass;
9768
    CodeMirror.signal = signal;
9769
    CodeMirror.Line = Line;
9770
    CodeMirror.changeEnd = changeEnd;
9771
    CodeMirror.scrollbarModel = scrollbarModel;
9772
    CodeMirror.Pos = Pos;
9773
    CodeMirror.cmpPos = cmp;
9774
    CodeMirror.modes = modes;
9775
    CodeMirror.mimeModes = mimeModes;
9776
    CodeMirror.resolveMode = resolveMode;
9777
    CodeMirror.getMode = getMode;
9778
    CodeMirror.modeExtensions = modeExtensions;
9779
    CodeMirror.extendMode = extendMode;
9780
    CodeMirror.copyState = copyState;
9781
    CodeMirror.startState = startState;
9782
    CodeMirror.innerMode = innerMode;
9783
    CodeMirror.commands = commands;
9784
    CodeMirror.keyMap = keyMap;
9785
    CodeMirror.keyName = keyName;
9786
    CodeMirror.isModifierKey = isModifierKey;
9787
    CodeMirror.lookupKey = lookupKey;
9788
    CodeMirror.normalizeKeyMap = normalizeKeyMap;
9789
    CodeMirror.StringStream = StringStream;
9790
    CodeMirror.SharedTextMarker = SharedTextMarker;
9791
    CodeMirror.TextMarker = TextMarker;
9792
    CodeMirror.LineWidget = LineWidget;
9793
    CodeMirror.e_preventDefault = e_preventDefault;
9794
    CodeMirror.e_stopPropagation = e_stopPropagation;
9795
    CodeMirror.e_stop = e_stop;
9796
    CodeMirror.addClass = addClass;
9797
    CodeMirror.contains = contains;
9798
    CodeMirror.rmClass = rmClass;
9799
    CodeMirror.keyNames = keyNames;
9800
  }
9801
 
9802
  // EDITOR CONSTRUCTOR
9803
 
9804
  defineOptions(CodeMirror);
9805
 
9806
  addEditorMethods(CodeMirror);
9807
 
9808
  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
9809
  var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
9810
  for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
9811
    { CodeMirror.prototype[prop] = (function(method) {
9812
      return function() {return method.apply(this.doc, arguments)}
9813
    })(Doc.prototype[prop]); } }
9814
 
9815
  eventMixin(Doc);
9816
  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9817
 
9818
  // Extra arguments are stored as the mode's dependencies, which is
9819
  // used by (legacy) mechanisms like loadmode.js to automatically
9820
  // load a mode. (Preferred mechanism is the require/define calls.)
9821
  CodeMirror.defineMode = function(name/*, mode, …*/) {
9822
    if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
9823
    defineMode.apply(this, arguments);
9824
  };
9825
 
9826
  CodeMirror.defineMIME = defineMIME;
9827
 
9828
  // Minimal default mode.
9829
  CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9830
  CodeMirror.defineMIME("text/plain", "null");
9831
 
9832
  // EXTENSIONS
9833
 
9834
  CodeMirror.defineExtension = function (name, func) {
9835
    CodeMirror.prototype[name] = func;
9836
  };
9837
  CodeMirror.defineDocExtension = function (name, func) {
9838
    Doc.prototype[name] = func;
9839
  };
9840
 
9841
  CodeMirror.fromTextArea = fromTextArea;
9842
 
9843
  addLegacyProps(CodeMirror);
9844
 
16493 obado 9845
  CodeMirror.version = "5.65.2";
14283 obado 9846
 
9847
  return CodeMirror;
9848
 
9849
})));