Subversion Repositories wimsdev

Rev

Rev 17702 | 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
16859 obado 2
// Distributed under an MIT license: https://codemirror.net/5/LICENSE
14283 obado 3
 
16859 obado 4
// This is CodeMirror (https://codemirror.net/5), a code editor
14283 obado 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);
16859 obado 29
  var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
30
  var chrome_version = chrome && +chrome[1];
14283 obado 31
  var presto = /Opera\//.test(userAgent);
32
  var safari = /Apple Computer/.test(navigator.vendor);
33
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
34
  var phantom = /PhantomJS/.test(userAgent);
35
 
16493 obado 36
  var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
14283 obado 37
  var android = /Android/.test(userAgent);
38
  // This is woefully incomplete. Suggestions for alternative methods welcome.
39
  var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
40
  var mac = ios || /Mac/.test(platform);
41
  var chromeOS = /\bCrOS\b/.test(userAgent);
42
  var windows = /win/i.test(platform);
43
 
44
  var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
45
  if (presto_version) { presto_version = Number(presto_version[1]); }
46
  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
47
  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
48
  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
49
  var captureRightClick = gecko || (ie && ie_version >= 9);
50
 
51
  function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
52
 
53
  var rmClass = function(node, cls) {
54
    var current = node.className;
55
    var match = classTest(cls).exec(current);
56
    if (match) {
57
      var after = current.slice(match.index + match[0].length);
58
      node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
59
    }
60
  };
61
 
62
  function removeChildren(e) {
63
    for (var count = e.childNodes.length; count > 0; --count)
64
      { e.removeChild(e.firstChild); }
65
    return e
66
  }
67
 
68
  function removeChildrenAndAdd(parent, e) {
69
    return removeChildren(parent).appendChild(e)
70
  }
71
 
72
  function elt(tag, content, className, style) {
73
    var e = document.createElement(tag);
74
    if (className) { e.className = className; }
75
    if (style) { e.style.cssText = style; }
76
    if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
77
    else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
78
    return e
79
  }
80
  // wrapper for elt, which removes the elt from the accessibility tree
81
  function eltP(tag, content, className, style) {
82
    var e = elt(tag, content, className, style);
83
    e.setAttribute("role", "presentation");
84
    return e
85
  }
86
 
87
  var range;
88
  if (document.createRange) { range = function(node, start, end, endNode) {
89
    var r = document.createRange();
90
    r.setEnd(endNode || node, end);
91
    r.setStart(node, start);
92
    return r
93
  }; }
94
  else { range = function(node, start, end) {
95
    var r = document.body.createTextRange();
96
    try { r.moveToElementText(node.parentNode); }
97
    catch(e) { return r }
98
    r.collapse(true);
99
    r.moveEnd("character", end);
100
    r.moveStart("character", start);
101
    return r
102
  }; }
103
 
104
  function contains(parent, child) {
105
    if (child.nodeType == 3) // Android browser always returns false when child is a textnode
106
      { child = child.parentNode; }
107
    if (parent.contains)
108
      { return parent.contains(child) }
109
    do {
110
      if (child.nodeType == 11) { child = child.host; }
111
      if (child == parent) { return true }
112
    } while (child = child.parentNode)
113
  }
114
 
18249 obado 115
  function activeElt(rootNode) {
14283 obado 116
    // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
117
    // IE < 10 will throw when accessed while the page is loading or in an iframe.
118
    // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
18249 obado 119
    var doc = rootNode.ownerDocument || rootNode;
14283 obado 120
    var activeElement;
121
    try {
18249 obado 122
      activeElement = rootNode.activeElement;
14283 obado 123
    } catch(e) {
17702 obado 124
      activeElement = doc.body || null;
14283 obado 125
    }
126
    while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
127
      { activeElement = activeElement.shadowRoot.activeElement; }
128
    return activeElement
129
  }
130
 
131
  function addClass(node, cls) {
132
    var current = node.className;
133
    if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
134
  }
135
  function joinClasses(a, b) {
136
    var as = a.split(" ");
137
    for (var i = 0; i < as.length; i++)
138
      { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
139
    return b
140
  }
141
 
142
  var selectInput = function(node) { node.select(); };
143
  if (ios) // Mobile Safari apparently has a bug where select() is broken.
144
    { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
145
  else if (ie) // Suppress mysterious IE10 errors
146
    { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
147
 
17702 obado 148
  function doc(cm) { return cm.display.wrapper.ownerDocument }
149
 
18249 obado 150
  function root(cm) {
151
    return rootNode(cm.display.wrapper)
152
  }
153
 
154
  function rootNode(element) {
155
    // Detect modern browsers (2017+).
156
    return element.getRootNode ? element.getRootNode() : element.ownerDocument
157
  }
158
 
17702 obado 159
  function win(cm) { return doc(cm).defaultView }
160
 
14283 obado 161
  function bind(f) {
162
    var args = Array.prototype.slice.call(arguments, 1);
163
    return function(){return f.apply(null, args)}
164
  }
165
 
166
  function copyObj(obj, target, overwrite) {
167
    if (!target) { target = {}; }
168
    for (var prop in obj)
169
      { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
170
        { target[prop] = obj[prop]; } }
171
    return target
172
  }
173
 
174
  // Counts the column offset in a string, taking tabs into account.
175
  // Used mostly to find indentation.
176
  function countColumn(string, end, tabSize, startIndex, startValue) {
177
    if (end == null) {
178
      end = string.search(/[^\s\u00a0]/);
179
      if (end == -1) { end = string.length; }
180
    }
181
    for (var i = startIndex || 0, n = startValue || 0;;) {
182
      var nextTab = string.indexOf("\t", i);
183
      if (nextTab < 0 || nextTab >= end)
184
        { return n + (end - i) }
185
      n += nextTab - i;
186
      n += tabSize - (n % tabSize);
187
      i = nextTab + 1;
188
    }
189
  }
190
 
15152 obado 191
  var Delayed = function() {
192
    this.id = null;
193
    this.f = null;
194
    this.time = 0;
195
    this.handler = bind(this.onTimeout, this);
196
  };
197
  Delayed.prototype.onTimeout = function (self) {
198
    self.id = 0;
199
    if (self.time <= +new Date) {
200
      self.f();
201
    } else {
202
      setTimeout(self.handler, self.time - +new Date);
203
    }
204
  };
14283 obado 205
  Delayed.prototype.set = function (ms, f) {
15152 obado 206
    this.f = f;
207
    var time = +new Date + ms;
208
    if (!this.id || time < this.time) {
209
      clearTimeout(this.id);
210
      this.id = setTimeout(this.handler, ms);
211
      this.time = time;
212
    }
14283 obado 213
  };
214
 
215
  function indexOf(array, elt) {
216
    for (var i = 0; i < array.length; ++i)
217
      { if (array[i] == elt) { return i } }
218
    return -1
219
  }
220
 
221
  // Number of pixels added to scroller and sizer to hide scrollbar
15152 obado 222
  var scrollerGap = 50;
14283 obado 223
 
224
  // Returned or thrown by various protocols to signal 'I'm not
225
  // handling this'.
226
  var Pass = {toString: function(){return "CodeMirror.Pass"}};
227
 
228
  // Reused option objects for setSelection & friends
229
  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
230
 
231
  // The inverse of countColumn -- find the offset that corresponds to
232
  // a particular column.
233
  function findColumn(string, goal, tabSize) {
234
    for (var pos = 0, col = 0;;) {
235
      var nextTab = string.indexOf("\t", pos);
236
      if (nextTab == -1) { nextTab = string.length; }
237
      var skipped = nextTab - pos;
238
      if (nextTab == string.length || col + skipped >= goal)
239
        { return pos + Math.min(skipped, goal - col) }
240
      col += nextTab - pos;
241
      col += tabSize - (col % tabSize);
242
      pos = nextTab + 1;
243
      if (col >= goal) { return pos }
244
    }
245
  }
246
 
247
  var spaceStrs = [""];
248
  function spaceStr(n) {
249
    while (spaceStrs.length <= n)
250
      { spaceStrs.push(lst(spaceStrs) + " "); }
251
    return spaceStrs[n]
252
  }
253
 
254
  function lst(arr) { return arr[arr.length-1] }
255
 
256
  function map(array, f) {
257
    var out = [];
258
    for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
259
    return out
260
  }
261
 
262
  function insertSorted(array, value, score) {
263
    var pos = 0, priority = score(value);
264
    while (pos < array.length && score(array[pos]) <= priority) { pos++; }
265
    array.splice(pos, 0, value);
266
  }
267
 
268
  function nothing() {}
269
 
270
  function createObj(base, props) {
271
    var inst;
272
    if (Object.create) {
273
      inst = Object.create(base);
274
    } else {
275
      nothing.prototype = base;
276
      inst = new nothing();
277
    }
278
    if (props) { copyObj(props, inst); }
279
    return inst
280
  }
281
 
282
  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
283
  function isWordCharBasic(ch) {
284
    return /\w/.test(ch) || ch > "\x80" &&
285
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
286
  }
287
  function isWordChar(ch, helper) {
288
    if (!helper) { return isWordCharBasic(ch) }
289
    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
290
    return helper.test(ch)
291
  }
292
 
293
  function isEmpty(obj) {
294
    for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
295
    return true
296
  }
297
 
298
  // Extending unicode characters. A series of a non-extending char +
299
  // any number of extending chars is treated as a single unit as far
300
  // as editing and measuring is concerned. This is not fully correct,
301
  // since some scripts/fonts/browsers also treat other configurations
302
  // of code points as a group.
303
  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]/;
304
  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
305
 
306
  // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
307
  function skipExtendingChars(str, pos, dir) {
308
    while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
309
    return pos
310
  }
311
 
312
  // Returns the value from the range [`from`; `to`] that satisfies
313
  // `pred` and is closest to `from`. Assumes that at least `to`
314
  // satisfies `pred`. Supports `from` being greater than `to`.
315
  function findFirst(pred, from, to) {
316
    // At any point we are certain `to` satisfies `pred`, don't know
317
    // whether `from` does.
318
    var dir = from > to ? -1 : 1;
319
    for (;;) {
320
      if (from == to) { return from }
321
      var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
322
      if (mid == from) { return pred(mid) ? from : to }
323
      if (pred(mid)) { to = mid; }
324
      else { from = mid + dir; }
325
    }
326
  }
327
 
328
  // BIDI HELPERS
329
 
330
  function iterateBidiSections(order, from, to, f) {
331
    if (!order) { return f(from, to, "ltr", 0) }
332
    var found = false;
333
    for (var i = 0; i < order.length; ++i) {
334
      var part = order[i];
335
      if (part.from < to && part.to > from || from == to && part.to == from) {
336
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
337
        found = true;
338
      }
339
    }
340
    if (!found) { f(from, to, "ltr"); }
341
  }
342
 
343
  var bidiOther = null;
344
  function getBidiPartAt(order, ch, sticky) {
345
    var found;
346
    bidiOther = null;
347
    for (var i = 0; i < order.length; ++i) {
348
      var cur = order[i];
349
      if (cur.from < ch && cur.to > ch) { return i }
350
      if (cur.to == ch) {
351
        if (cur.from != cur.to && sticky == "before") { found = i; }
352
        else { bidiOther = i; }
353
      }
354
      if (cur.from == ch) {
355
        if (cur.from != cur.to && sticky != "before") { found = i; }
356
        else { bidiOther = i; }
357
      }
358
    }
359
    return found != null ? found : bidiOther
360
  }
361
 
362
  // Bidirectional ordering algorithm
363
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
364
  // that this (partially) implements.
365
 
366
  // One-char codes used for character types:
367
  // L (L):   Left-to-Right
368
  // R (R):   Right-to-Left
369
  // r (AL):  Right-to-Left Arabic
370
  // 1 (EN):  European Number
371
  // + (ES):  European Number Separator
372
  // % (ET):  European Number Terminator
373
  // n (AN):  Arabic Number
374
  // , (CS):  Common Number Separator
375
  // m (NSM): Non-Spacing Mark
376
  // b (BN):  Boundary Neutral
377
  // s (B):   Paragraph Separator
378
  // t (S):   Segment Separator
379
  // w (WS):  Whitespace
380
  // N (ON):  Other Neutrals
381
 
382
  // Returns null if characters are ordered as they appear
383
  // (left-to-right), or an array of sections ({from, to, level}
384
  // objects) in the order in which they occur visually.
385
  var bidiOrdering = (function() {
386
    // Character types for codepoints 0 to 0xff
387
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
388
    // Character types for codepoints 0x600 to 0x6f9
389
    var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
390
    function charType(code) {
391
      if (code <= 0xf7) { return lowTypes.charAt(code) }
392
      else if (0x590 <= code && code <= 0x5f4) { return "R" }
393
      else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
394
      else if (0x6ee <= code && code <= 0x8ac) { return "r" }
395
      else if (0x2000 <= code && code <= 0x200b) { return "w" }
396
      else if (code == 0x200c) { return "b" }
397
      else { return "L" }
398
    }
399
 
400
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
401
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
402
 
403
    function BidiSpan(level, from, to) {
404
      this.level = level;
405
      this.from = from; this.to = to;
406
    }
407
 
408
    return function(str, direction) {
409
      var outerType = direction == "ltr" ? "L" : "R";
410
 
411
      if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
412
      var len = str.length, types = [];
413
      for (var i = 0; i < len; ++i)
414
        { types.push(charType(str.charCodeAt(i))); }
415
 
416
      // W1. Examine each non-spacing mark (NSM) in the level run, and
417
      // change the type of the NSM to the type of the previous
418
      // character. If the NSM is at the start of the level run, it will
419
      // get the type of sor.
420
      for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
421
        var type = types[i$1];
422
        if (type == "m") { types[i$1] = prev; }
423
        else { prev = type; }
424
      }
425
 
426
      // W2. Search backwards from each instance of a European number
427
      // until the first strong type (R, L, AL, or sor) is found. If an
428
      // AL is found, change the type of the European number to Arabic
429
      // number.
430
      // W3. Change all ALs to R.
431
      for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
432
        var type$1 = types[i$2];
433
        if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
434
        else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
435
      }
436
 
437
      // W4. A single European separator between two European numbers
438
      // changes to a European number. A single common separator between
439
      // two numbers of the same type changes to that type.
440
      for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
441
        var type$2 = types[i$3];
442
        if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
443
        else if (type$2 == "," && prev$1 == types[i$3+1] &&
444
                 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
445
        prev$1 = type$2;
446
      }
447
 
448
      // W5. A sequence of European terminators adjacent to European
449
      // numbers changes to all European numbers.
450
      // W6. Otherwise, separators and terminators change to Other
451
      // Neutral.
452
      for (var i$4 = 0; i$4 < len; ++i$4) {
453
        var type$3 = types[i$4];
454
        if (type$3 == ",") { types[i$4] = "N"; }
455
        else if (type$3 == "%") {
456
          var end = (void 0);
457
          for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
458
          var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
459
          for (var j = i$4; j < end; ++j) { types[j] = replace; }
460
          i$4 = end - 1;
461
        }
462
      }
463
 
464
      // W7. Search backwards from each instance of a European number
465
      // until the first strong type (R, L, or sor) is found. If an L is
466
      // found, then change the type of the European number to L.
467
      for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
468
        var type$4 = types[i$5];
469
        if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
470
        else if (isStrong.test(type$4)) { cur$1 = type$4; }
471
      }
472
 
473
      // N1. A sequence of neutrals takes the direction of the
474
      // surrounding strong text if the text on both sides has the same
475
      // direction. European and Arabic numbers act as if they were R in
476
      // terms of their influence on neutrals. Start-of-level-run (sor)
477
      // and end-of-level-run (eor) are used at level run boundaries.
478
      // N2. Any remaining neutrals take the embedding direction.
479
      for (var i$6 = 0; i$6 < len; ++i$6) {
480
        if (isNeutral.test(types[i$6])) {
481
          var end$1 = (void 0);
482
          for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
483
          var before = (i$6 ? types[i$6-1] : outerType) == "L";
484
          var after = (end$1 < len ? types[end$1] : outerType) == "L";
485
          var replace$1 = before == after ? (before ? "L" : "R") : outerType;
486
          for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
487
          i$6 = end$1 - 1;
488
        }
489
      }
490
 
491
      // Here we depart from the documented algorithm, in order to avoid
492
      // building up an actual levels array. Since there are only three
493
      // levels (0, 1, 2) in an implementation that doesn't take
494
      // explicit embedding into account, we can build up the order on
495
      // the fly, without following the level-based algorithm.
496
      var order = [], m;
497
      for (var i$7 = 0; i$7 < len;) {
498
        if (countsAsLeft.test(types[i$7])) {
499
          var start = i$7;
500
          for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
501
          order.push(new BidiSpan(0, start, i$7));
502
        } else {
15152 obado 503
          var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
14283 obado 504
          for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
505
          for (var j$2 = pos; j$2 < i$7;) {
506
            if (countsAsNum.test(types[j$2])) {
15152 obado 507
              if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
14283 obado 508
              var nstart = j$2;
509
              for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
510
              order.splice(at, 0, new BidiSpan(2, nstart, j$2));
15152 obado 511
              at += isRTL;
14283 obado 512
              pos = j$2;
513
            } else { ++j$2; }
514
          }
515
          if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
516
        }
517
      }
518
      if (direction == "ltr") {
519
        if (order[0].level == 1 && (m = str.match(/^\s+/))) {
520
          order[0].from = m[0].length;
521
          order.unshift(new BidiSpan(0, 0, m[0].length));
522
        }
523
        if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
524
          lst(order).to -= m[0].length;
525
          order.push(new BidiSpan(0, len - m[0].length, len));
526
        }
527
      }
528
 
529
      return direction == "rtl" ? order.reverse() : order
530
    }
531
  })();
532
 
533
  // Get the bidi ordering for the given line (and cache it). Returns
534
  // false for lines that are fully left-to-right, and an array of
535
  // BidiSpan objects otherwise.
536
  function getOrder(line, direction) {
537
    var order = line.order;
538
    if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
539
    return order
540
  }
541
 
542
  // EVENT HANDLING
543
 
544
  // Lightweight event framework. on/off also work on DOM nodes,
545
  // registering native DOM handlers.
546
 
547
  var noHandlers = [];
548
 
549
  var on = function(emitter, type, f) {
550
    if (emitter.addEventListener) {
551
      emitter.addEventListener(type, f, false);
552
    } else if (emitter.attachEvent) {
553
      emitter.attachEvent("on" + type, f);
554
    } else {
15152 obado 555
      var map = emitter._handlers || (emitter._handlers = {});
556
      map[type] = (map[type] || noHandlers).concat(f);
14283 obado 557
    }
558
  };
559
 
560
  function getHandlers(emitter, type) {
561
    return emitter._handlers && emitter._handlers[type] || noHandlers
562
  }
563
 
564
  function off(emitter, type, f) {
565
    if (emitter.removeEventListener) {
566
      emitter.removeEventListener(type, f, false);
567
    } else if (emitter.detachEvent) {
568
      emitter.detachEvent("on" + type, f);
569
    } else {
15152 obado 570
      var map = emitter._handlers, arr = map && map[type];
14283 obado 571
      if (arr) {
572
        var index = indexOf(arr, f);
573
        if (index > -1)
15152 obado 574
          { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
14283 obado 575
      }
576
    }
577
  }
578
 
579
  function signal(emitter, type /*, values...*/) {
580
    var handlers = getHandlers(emitter, type);
581
    if (!handlers.length) { return }
582
    var args = Array.prototype.slice.call(arguments, 2);
583
    for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
584
  }
585
 
586
  // The DOM events that CodeMirror handles can be overridden by
587
  // registering a (non-DOM) handler on the editor for the event name,
588
  // and preventDefault-ing the event in that handler.
589
  function signalDOMEvent(cm, e, override) {
590
    if (typeof e == "string")
591
      { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
592
    signal(cm, override || e.type, cm, e);
593
    return e_defaultPrevented(e) || e.codemirrorIgnore
594
  }
595
 
596
  function signalCursorActivity(cm) {
597
    var arr = cm._handlers && cm._handlers.cursorActivity;
598
    if (!arr) { return }
599
    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
600
    for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
601
      { set.push(arr[i]); } }
602
  }
603
 
604
  function hasHandler(emitter, type) {
605
    return getHandlers(emitter, type).length > 0
606
  }
607
 
608
  // Add on and off methods to a constructor's prototype, to make
609
  // registering events on such objects more convenient.
610
  function eventMixin(ctor) {
611
    ctor.prototype.on = function(type, f) {on(this, type, f);};
612
    ctor.prototype.off = function(type, f) {off(this, type, f);};
613
  }
614
 
615
  // Due to the fact that we still support jurassic IE versions, some
616
  // compatibility wrappers are needed.
617
 
618
  function e_preventDefault(e) {
619
    if (e.preventDefault) { e.preventDefault(); }
620
    else { e.returnValue = false; }
621
  }
622
  function e_stopPropagation(e) {
623
    if (e.stopPropagation) { e.stopPropagation(); }
624
    else { e.cancelBubble = true; }
625
  }
626
  function e_defaultPrevented(e) {
627
    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
628
  }
629
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
630
 
631
  function e_target(e) {return e.target || e.srcElement}
632
  function e_button(e) {
633
    var b = e.which;
634
    if (b == null) {
635
      if (e.button & 1) { b = 1; }
636
      else if (e.button & 2) { b = 3; }
637
      else if (e.button & 4) { b = 2; }
638
    }
639
    if (mac && e.ctrlKey && b == 1) { b = 3; }
640
    return b
641
  }
642
 
643
  // Detect drag-and-drop
644
  var dragAndDrop = function() {
645
    // There is *some* kind of drag-and-drop support in IE6-8, but I
646
    // couldn't get it to work yet.
647
    if (ie && ie_version < 9) { return false }
648
    var div = elt('div');
649
    return "draggable" in div || "dragDrop" in div
650
  }();
651
 
652
  var zwspSupported;
653
  function zeroWidthElement(measure) {
654
    if (zwspSupported == null) {
655
      var test = elt("span", "\u200b");
656
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
657
      if (measure.firstChild.offsetHeight != 0)
658
        { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
659
    }
660
    var node = zwspSupported ? elt("span", "\u200b") :
661
      elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
662
    node.setAttribute("cm-text", "");
663
    return node
664
  }
665
 
666
  // Feature-detect IE's crummy client rect reporting for bidi text
667
  var badBidiRects;
668
  function hasBadBidiRects(measure) {
669
    if (badBidiRects != null) { return badBidiRects }
670
    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
671
    var r0 = range(txt, 0, 1).getBoundingClientRect();
672
    var r1 = range(txt, 1, 2).getBoundingClientRect();
673
    removeChildren(measure);
674
    if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
675
    return badBidiRects = (r1.right - r0.right < 3)
676
  }
677
 
678
  // See if "".split is the broken IE version, if so, provide an
679
  // alternative way to split lines.
680
  var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
681
    var pos = 0, result = [], l = string.length;
682
    while (pos <= l) {
683
      var nl = string.indexOf("\n", pos);
684
      if (nl == -1) { nl = string.length; }
685
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
686
      var rt = line.indexOf("\r");
687
      if (rt != -1) {
688
        result.push(line.slice(0, rt));
689
        pos += rt + 1;
690
      } else {
691
        result.push(line);
692
        pos = nl + 1;
693
      }
694
    }
695
    return result
696
  } : function (string) { return string.split(/\r\n?|\n/); };
697
 
698
  var hasSelection = window.getSelection ? function (te) {
699
    try { return te.selectionStart != te.selectionEnd }
700
    catch(e) { return false }
701
  } : function (te) {
15152 obado 702
    var range;
703
    try {range = te.ownerDocument.selection.createRange();}
14283 obado 704
    catch(e) {}
15152 obado 705
    if (!range || range.parentElement() != te) { return false }
706
    return range.compareEndPoints("StartToEnd", range) != 0
14283 obado 707
  };
708
 
709
  var hasCopyEvent = (function () {
710
    var e = elt("div");
711
    if ("oncopy" in e) { return true }
712
    e.setAttribute("oncopy", "return;");
713
    return typeof e.oncopy == "function"
714
  })();
715
 
716
  var badZoomedRects = null;
717
  function hasBadZoomedRects(measure) {
718
    if (badZoomedRects != null) { return badZoomedRects }
719
    var node = removeChildrenAndAdd(measure, elt("span", "x"));
720
    var normal = node.getBoundingClientRect();
721
    var fromRange = range(node, 0, 1).getBoundingClientRect();
722
    return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
723
  }
724
 
725
  // Known modes, by name and by MIME
726
  var modes = {}, mimeModes = {};
727
 
728
  // Extra arguments are stored as the mode's dependencies, which is
729
  // used by (legacy) mechanisms like loadmode.js to automatically
730
  // load a mode. (Preferred mechanism is the require/define calls.)
731
  function defineMode(name, mode) {
732
    if (arguments.length > 2)
733
      { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
734
    modes[name] = mode;
735
  }
736
 
737
  function defineMIME(mime, spec) {
738
    mimeModes[mime] = spec;
739
  }
740
 
741
  // Given a MIME type, a {name, ...options} config object, or a name
742
  // string, return a mode config object.
743
  function resolveMode(spec) {
744
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
745
      spec = mimeModes[spec];
746
    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
747
      var found = mimeModes[spec.name];
748
      if (typeof found == "string") { found = {name: found}; }
749
      spec = createObj(found, spec);
750
      spec.name = found.name;
751
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
752
      return resolveMode("application/xml")
753
    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
754
      return resolveMode("application/json")
755
    }
756
    if (typeof spec == "string") { return {name: spec} }
757
    else { return spec || {name: "null"} }
758
  }
759
 
760
  // Given a mode spec (anything that resolveMode accepts), find and
761
  // initialize an actual mode object.
762
  function getMode(options, spec) {
763
    spec = resolveMode(spec);
764
    var mfactory = modes[spec.name];
765
    if (!mfactory) { return getMode(options, "text/plain") }
766
    var modeObj = mfactory(options, spec);
767
    if (modeExtensions.hasOwnProperty(spec.name)) {
768
      var exts = modeExtensions[spec.name];
769
      for (var prop in exts) {
770
        if (!exts.hasOwnProperty(prop)) { continue }
771
        if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
772
        modeObj[prop] = exts[prop];
773
      }
774
    }
775
    modeObj.name = spec.name;
776
    if (spec.helperType) { modeObj.helperType = spec.helperType; }
777
    if (spec.modeProps) { for (var prop$1 in spec.modeProps)
778
      { modeObj[prop$1] = spec.modeProps[prop$1]; } }
779
 
780
    return modeObj
781
  }
782
 
783
  // This can be used to attach properties to mode objects from
784
  // outside the actual mode definition.
785
  var modeExtensions = {};
786
  function extendMode(mode, properties) {
787
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
788
    copyObj(properties, exts);
789
  }
790
 
791
  function copyState(mode, state) {
792
    if (state === true) { return state }
793
    if (mode.copyState) { return mode.copyState(state) }
794
    var nstate = {};
795
    for (var n in state) {
796
      var val = state[n];
797
      if (val instanceof Array) { val = val.concat([]); }
798
      nstate[n] = val;
799
    }
800
    return nstate
801
  }
802
 
803
  // Given a mode and a state (for that mode), find the inner mode and
804
  // state at the position that the state refers to.
805
  function innerMode(mode, state) {
806
    var info;
807
    while (mode.innerMode) {
808
      info = mode.innerMode(state);
809
      if (!info || info.mode == mode) { break }
810
      state = info.state;
811
      mode = info.mode;
812
    }
813
    return info || {mode: mode, state: state}
814
  }
815
 
816
  function startState(mode, a1, a2) {
817
    return mode.startState ? mode.startState(a1, a2) : true
818
  }
819
 
820
  // STRING STREAM
821
 
822
  // Fed to the mode parsers, provides helper functions to make
823
  // parsers more succinct.
824
 
825
  var StringStream = function(string, tabSize, lineOracle) {
826
    this.pos = this.start = 0;
827
    this.string = string;
828
    this.tabSize = tabSize || 8;
829
    this.lastColumnPos = this.lastColumnValue = 0;
830
    this.lineStart = 0;
831
    this.lineOracle = lineOracle;
832
  };
833
 
834
  StringStream.prototype.eol = function () {return this.pos >= this.string.length};
835
  StringStream.prototype.sol = function () {return this.pos == this.lineStart};
836
  StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
837
  StringStream.prototype.next = function () {
838
    if (this.pos < this.string.length)
839
      { return this.string.charAt(this.pos++) }
840
  };
841
  StringStream.prototype.eat = function (match) {
842
    var ch = this.string.charAt(this.pos);
843
    var ok;
844
    if (typeof match == "string") { ok = ch == match; }
845
    else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
846
    if (ok) {++this.pos; return ch}
847
  };
848
  StringStream.prototype.eatWhile = function (match) {
849
    var start = this.pos;
850
    while (this.eat(match)){}
851
    return this.pos > start
852
  };
853
  StringStream.prototype.eatSpace = function () {
854
    var start = this.pos;
15152 obado 855
    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
14283 obado 856
    return this.pos > start
857
  };
858
  StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
859
  StringStream.prototype.skipTo = function (ch) {
860
    var found = this.string.indexOf(ch, this.pos);
861
    if (found > -1) {this.pos = found; return true}
862
  };
863
  StringStream.prototype.backUp = function (n) {this.pos -= n;};
864
  StringStream.prototype.column = function () {
865
    if (this.lastColumnPos < this.start) {
866
      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
867
      this.lastColumnPos = this.start;
868
    }
869
    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
870
  };
871
  StringStream.prototype.indentation = function () {
872
    return countColumn(this.string, null, this.tabSize) -
873
      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
874
  };
875
  StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
876
    if (typeof pattern == "string") {
877
      var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
878
      var substr = this.string.substr(this.pos, pattern.length);
879
      if (cased(substr) == cased(pattern)) {
880
        if (consume !== false) { this.pos += pattern.length; }
881
        return true
882
      }
883
    } else {
884
      var match = this.string.slice(this.pos).match(pattern);
885
      if (match && match.index > 0) { return null }
886
      if (match && consume !== false) { this.pos += match[0].length; }
887
      return match
888
    }
889
  };
890
  StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
891
  StringStream.prototype.hideFirstChars = function (n, inner) {
892
    this.lineStart += n;
893
    try { return inner() }
894
    finally { this.lineStart -= n; }
895
  };
896
  StringStream.prototype.lookAhead = function (n) {
897
    var oracle = this.lineOracle;
898
    return oracle && oracle.lookAhead(n)
899
  };
900
  StringStream.prototype.baseToken = function () {
901
    var oracle = this.lineOracle;
902
    return oracle && oracle.baseToken(this.pos)
903
  };
904
 
905
  // Find the line object corresponding to the given line number.
906
  function getLine(doc, n) {
907
    n -= doc.first;
908
    if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
909
    var chunk = doc;
910
    while (!chunk.lines) {
911
      for (var i = 0;; ++i) {
912
        var child = chunk.children[i], sz = child.chunkSize();
913
        if (n < sz) { chunk = child; break }
914
        n -= sz;
915
      }
916
    }
917
    return chunk.lines[n]
918
  }
919
 
920
  // Get the part of a document between two positions, as an array of
921
  // strings.
922
  function getBetween(doc, start, end) {
923
    var out = [], n = start.line;
924
    doc.iter(start.line, end.line + 1, function (line) {
925
      var text = line.text;
926
      if (n == end.line) { text = text.slice(0, end.ch); }
927
      if (n == start.line) { text = text.slice(start.ch); }
928
      out.push(text);
929
      ++n;
930
    });
931
    return out
932
  }
933
  // Get the lines between from and to, as array of strings.
934
  function getLines(doc, from, to) {
935
    var out = [];
936
    doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
937
    return out
938
  }
939
 
940
  // Update the height of a line, propagating the height change
941
  // upwards to parent nodes.
942
  function updateLineHeight(line, height) {
943
    var diff = height - line.height;
944
    if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
945
  }
946
 
947
  // Given a line object, find its line number by walking up through
948
  // its parent links.
949
  function lineNo(line) {
950
    if (line.parent == null) { return null }
951
    var cur = line.parent, no = indexOf(cur.lines, line);
952
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
953
      for (var i = 0;; ++i) {
954
        if (chunk.children[i] == cur) { break }
955
        no += chunk.children[i].chunkSize();
956
      }
957
    }
958
    return no + cur.first
959
  }
960
 
961
  // Find the line at the given vertical position, using the height
962
  // information in the document tree.
963
  function lineAtHeight(chunk, h) {
964
    var n = chunk.first;
965
    outer: do {
966
      for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
967
        var child = chunk.children[i$1], ch = child.height;
968
        if (h < ch) { chunk = child; continue outer }
969
        h -= ch;
970
        n += child.chunkSize();
971
      }
972
      return n
973
    } while (!chunk.lines)
974
    var i = 0;
975
    for (; i < chunk.lines.length; ++i) {
976
      var line = chunk.lines[i], lh = line.height;
977
      if (h < lh) { break }
978
      h -= lh;
979
    }
980
    return n + i
981
  }
982
 
983
  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
984
 
985
  function lineNumberFor(options, i) {
986
    return String(options.lineNumberFormatter(i + options.firstLineNumber))
987
  }
988
 
989
  // A Pos instance represents a position within the text.
990
  function Pos(line, ch, sticky) {
991
    if ( sticky === void 0 ) sticky = null;
992
 
993
    if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
994
    this.line = line;
995
    this.ch = ch;
996
    this.sticky = sticky;
997
  }
998
 
999
  // Compare two positions, return 0 if they are the same, a negative
1000
  // number when a is less, and a positive number otherwise.
1001
  function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
1002
 
1003
  function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
1004
 
1005
  function copyPos(x) {return Pos(x.line, x.ch)}
1006
  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
1007
  function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
1008
 
1009
  // Most of the external API clips given positions to make sure they
1010
  // actually exist within the document.
1011
  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
1012
  function clipPos(doc, pos) {
1013
    if (pos.line < doc.first) { return Pos(doc.first, 0) }
1014
    var last = doc.first + doc.size - 1;
1015
    if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
1016
    return clipToLen(pos, getLine(doc, pos.line).text.length)
1017
  }
1018
  function clipToLen(pos, linelen) {
1019
    var ch = pos.ch;
1020
    if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
1021
    else if (ch < 0) { return Pos(pos.line, 0) }
1022
    else { return pos }
1023
  }
1024
  function clipPosArray(doc, array) {
1025
    var out = [];
1026
    for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
1027
    return out
1028
  }
1029
 
1030
  var SavedContext = function(state, lookAhead) {
1031
    this.state = state;
1032
    this.lookAhead = lookAhead;
1033
  };
1034
 
1035
  var Context = function(doc, state, line, lookAhead) {
1036
    this.state = state;
1037
    this.doc = doc;
1038
    this.line = line;
1039
    this.maxLookAhead = lookAhead || 0;
1040
    this.baseTokens = null;
1041
    this.baseTokenPos = 1;
1042
  };
1043
 
1044
  Context.prototype.lookAhead = function (n) {
1045
    var line = this.doc.getLine(this.line + n);
1046
    if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
1047
    return line
1048
  };
1049
 
1050
  Context.prototype.baseToken = function (n) {
1051
    if (!this.baseTokens) { return null }
1052
    while (this.baseTokens[this.baseTokenPos] <= n)
15152 obado 1053
      { this.baseTokenPos += 2; }
14283 obado 1054
    var type = this.baseTokens[this.baseTokenPos + 1];
1055
    return {type: type && type.replace(/( |^)overlay .*/, ""),
1056
            size: this.baseTokens[this.baseTokenPos] - n}
1057
  };
1058
 
1059
  Context.prototype.nextLine = function () {
1060
    this.line++;
1061
    if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1062
  };
1063
 
1064
  Context.fromSaved = function (doc, saved, line) {
1065
    if (saved instanceof SavedContext)
1066
      { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
1067
    else
1068
      { return new Context(doc, copyState(doc.mode, saved), line) }
1069
  };
1070
 
1071
  Context.prototype.save = function (copy) {
1072
    var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
1073
    return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
1074
  };
1075
 
1076
 
1077
  // Compute a style array (an array starting with a mode generation
1078
  // -- for invalidation -- followed by pairs of end positions and
1079
  // style strings), which is used to highlight the tokens on the
1080
  // line.
1081
  function highlightLine(cm, line, context, forceToEnd) {
1082
    // A styles array always starts with a number identifying the
1083
    // mode/overlays that it is based on (for easy invalidation).
1084
    var st = [cm.state.modeGen], lineClasses = {};
1085
    // Compute the base array of styles
1086
    runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
1087
            lineClasses, forceToEnd);
1088
    var state = context.state;
1089
 
1090
    // Run overlays, adjust style array.
1091
    var loop = function ( o ) {
1092
      context.baseTokens = st;
1093
      var overlay = cm.state.overlays[o], i = 1, at = 0;
1094
      context.state = true;
1095
      runMode(cm, line.text, overlay.mode, context, function (end, style) {
1096
        var start = i;
1097
        // Ensure there's a token end at the current position, and that i points at it
1098
        while (at < end) {
1099
          var i_end = st[i];
1100
          if (i_end > end)
1101
            { st.splice(i, 1, end, st[i+1], i_end); }
1102
          i += 2;
1103
          at = Math.min(end, i_end);
1104
        }
1105
        if (!style) { return }
1106
        if (overlay.opaque) {
1107
          st.splice(start, i - start, end, "overlay " + style);
1108
          i = start + 2;
1109
        } else {
1110
          for (; start < i; start += 2) {
1111
            var cur = st[start+1];
1112
            st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
1113
          }
1114
        }
1115
      }, lineClasses);
1116
      context.state = state;
1117
      context.baseTokens = null;
1118
      context.baseTokenPos = 1;
1119
    };
1120
 
1121
    for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1122
 
1123
    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
1124
  }
1125
 
1126
  function getLineStyles(cm, line, updateFrontier) {
1127
    if (!line.styles || line.styles[0] != cm.state.modeGen) {
1128
      var context = getContextBefore(cm, lineNo(line));
1129
      var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
1130
      var result = highlightLine(cm, line, context);
1131
      if (resetState) { context.state = resetState; }
1132
      line.stateAfter = context.save(!resetState);
1133
      line.styles = result.styles;
1134
      if (result.classes) { line.styleClasses = result.classes; }
1135
      else if (line.styleClasses) { line.styleClasses = null; }
1136
      if (updateFrontier === cm.doc.highlightFrontier)
1137
        { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
1138
    }
1139
    return line.styles
1140
  }
1141
 
1142
  function getContextBefore(cm, n, precise) {
1143
    var doc = cm.doc, display = cm.display;
1144
    if (!doc.mode.startState) { return new Context(doc, true, n) }
1145
    var start = findStartLine(cm, n, precise);
1146
    var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
1147
    var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
1148
 
1149
    doc.iter(start, n, function (line) {
1150
      processLine(cm, line.text, context);
1151
      var pos = context.line;
1152
      line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
1153
      context.nextLine();
1154
    });
1155
    if (precise) { doc.modeFrontier = context.line; }
1156
    return context
1157
  }
1158
 
1159
  // Lightweight form of highlight -- proceed over this line and
1160
  // update state, but don't save a style array. Used for lines that
1161
  // aren't currently visible.
1162
  function processLine(cm, text, context, startAt) {
1163
    var mode = cm.doc.mode;
1164
    var stream = new StringStream(text, cm.options.tabSize, context);
1165
    stream.start = stream.pos = startAt || 0;
1166
    if (text == "") { callBlankLine(mode, context.state); }
1167
    while (!stream.eol()) {
1168
      readToken(mode, stream, context.state);
1169
      stream.start = stream.pos;
1170
    }
1171
  }
1172
 
1173
  function callBlankLine(mode, state) {
1174
    if (mode.blankLine) { return mode.blankLine(state) }
1175
    if (!mode.innerMode) { return }
1176
    var inner = innerMode(mode, state);
1177
    if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
1178
  }
1179
 
1180
  function readToken(mode, stream, state, inner) {
1181
    for (var i = 0; i < 10; i++) {
1182
      if (inner) { inner[0] = innerMode(mode, state).mode; }
1183
      var style = mode.token(stream, state);
1184
      if (stream.pos > stream.start) { return style }
1185
    }
1186
    throw new Error("Mode " + mode.name + " failed to advance stream.")
1187
  }
1188
 
1189
  var Token = function(stream, type, state) {
1190
    this.start = stream.start; this.end = stream.pos;
1191
    this.string = stream.current();
1192
    this.type = type || null;
1193
    this.state = state;
1194
  };
1195
 
1196
  // Utility for getTokenAt and getLineTokens
1197
  function takeToken(cm, pos, precise, asArray) {
1198
    var doc = cm.doc, mode = doc.mode, style;
1199
    pos = clipPos(doc, pos);
1200
    var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
1201
    var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
1202
    if (asArray) { tokens = []; }
1203
    while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
1204
      stream.start = stream.pos;
1205
      style = readToken(mode, stream, context.state);
1206
      if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
1207
    }
1208
    return asArray ? tokens : new Token(stream, style, context.state)
1209
  }
1210
 
1211
  function extractLineClasses(type, output) {
1212
    if (type) { for (;;) {
1213
      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
1214
      if (!lineClass) { break }
1215
      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
1216
      var prop = lineClass[1] ? "bgClass" : "textClass";
1217
      if (output[prop] == null)
1218
        { output[prop] = lineClass[2]; }
15152 obado 1219
      else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
14283 obado 1220
        { output[prop] += " " + lineClass[2]; }
1221
    } }
1222
    return type
1223
  }
1224
 
1225
  // Run the given mode's parser over a line, calling f for each token.
1226
  function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
1227
    var flattenSpans = mode.flattenSpans;
1228
    if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
1229
    var curStart = 0, curStyle = null;
1230
    var stream = new StringStream(text, cm.options.tabSize, context), style;
1231
    var inner = cm.options.addModeClass && [null];
1232
    if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
1233
    while (!stream.eol()) {
1234
      if (stream.pos > cm.options.maxHighlightLength) {
1235
        flattenSpans = false;
1236
        if (forceToEnd) { processLine(cm, text, context, stream.pos); }
1237
        stream.pos = text.length;
1238
        style = null;
1239
      } else {
1240
        style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
1241
      }
1242
      if (inner) {
1243
        var mName = inner[0].name;
1244
        if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
1245
      }
1246
      if (!flattenSpans || curStyle != style) {
1247
        while (curStart < stream.start) {
1248
          curStart = Math.min(stream.start, curStart + 5000);
1249
          f(curStart, curStyle);
1250
        }
1251
        curStyle = style;
1252
      }
1253
      stream.start = stream.pos;
1254
    }
1255
    while (curStart < stream.pos) {
1256
      // Webkit seems to refuse to render text nodes longer than 57444
1257
      // characters, and returns inaccurate measurements in nodes
1258
      // starting around 5000 chars.
1259
      var pos = Math.min(stream.pos, curStart + 5000);
1260
      f(pos, curStyle);
1261
      curStart = pos;
1262
    }
1263
  }
1264
 
1265
  // Finds the line to start with when starting a parse. Tries to
1266
  // find a line with a stateAfter, so that it can start with a
1267
  // valid state. If that fails, it returns the line with the
1268
  // smallest indentation, which tends to need the least context to
1269
  // parse correctly.
1270
  function findStartLine(cm, n, precise) {
1271
    var minindent, minline, doc = cm.doc;
1272
    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1273
    for (var search = n; search > lim; --search) {
1274
      if (search <= doc.first) { return doc.first }
1275
      var line = getLine(doc, search - 1), after = line.stateAfter;
1276
      if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
1277
        { return search }
1278
      var indented = countColumn(line.text, null, cm.options.tabSize);
1279
      if (minline == null || minindent > indented) {
1280
        minline = search - 1;
1281
        minindent = indented;
1282
      }
1283
    }
1284
    return minline
1285
  }
1286
 
1287
  function retreatFrontier(doc, n) {
1288
    doc.modeFrontier = Math.min(doc.modeFrontier, n);
1289
    if (doc.highlightFrontier < n - 10) { return }
1290
    var start = doc.first;
1291
    for (var line = n - 1; line > start; line--) {
1292
      var saved = getLine(doc, line).stateAfter;
1293
      // change is on 3
1294
      // state on line 1 looked ahead 2 -- so saw 3
1295
      // test 1 + 2 < 3 should cover this
1296
      if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
1297
        start = line + 1;
1298
        break
1299
      }
1300
    }
1301
    doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1302
  }
1303
 
1304
  // Optimize some code when these features are not used.
1305
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
1306
 
1307
  function seeReadOnlySpans() {
1308
    sawReadOnlySpans = true;
1309
  }
1310
 
1311
  function seeCollapsedSpans() {
1312
    sawCollapsedSpans = true;
1313
  }
1314
 
1315
  // TEXTMARKER SPANS
1316
 
1317
  function MarkedSpan(marker, from, to) {
1318
    this.marker = marker;
1319
    this.from = from; this.to = to;
1320
  }
1321
 
1322
  // Search an array of spans for a span matching the given marker.
1323
  function getMarkedSpanFor(spans, marker) {
1324
    if (spans) { for (var i = 0; i < spans.length; ++i) {
1325
      var span = spans[i];
1326
      if (span.marker == marker) { return span }
1327
    } }
1328
  }
16493 obado 1329
 
14283 obado 1330
  // Remove a span from an array, returning undefined if no spans are
1331
  // left (we don't store arrays for lines without spans).
1332
  function removeMarkedSpan(spans, span) {
1333
    var r;
1334
    for (var i = 0; i < spans.length; ++i)
1335
      { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
1336
    return r
1337
  }
16493 obado 1338
 
14283 obado 1339
  // Add a span to a line.
16493 obado 1340
  function addMarkedSpan(line, span, op) {
1341
    var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
16859 obado 1342
    if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
16493 obado 1343
      line.markedSpans.push(span);
1344
    } else {
1345
      line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
1346
      if (inThisOp) { inThisOp.add(line.markedSpans); }
1347
    }
14283 obado 1348
    span.marker.attachLine(line);
1349
  }
1350
 
1351
  // Used for the algorithm that adjusts markers for a change in the
1352
  // document. These functions cut an array of spans at a given
1353
  // character position, returning an array of remaining chunks (or
1354
  // undefined if nothing remains).
1355
  function markedSpansBefore(old, startCh, isInsert) {
1356
    var nw;
1357
    if (old) { for (var i = 0; i < old.length; ++i) {
1358
      var span = old[i], marker = span.marker;
1359
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
1360
      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
1361
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
1362
        ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
1363
      }
1364
    } }
1365
    return nw
1366
  }
1367
  function markedSpansAfter(old, endCh, isInsert) {
1368
    var nw;
1369
    if (old) { for (var i = 0; i < old.length; ++i) {
1370
      var span = old[i], marker = span.marker;
1371
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
1372
      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
1373
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
1374
        ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
1375
                                              span.to == null ? null : span.to - endCh));
1376
      }
1377
    } }
1378
    return nw
1379
  }
1380
 
1381
  // Given a change object, compute the new set of marker spans that
1382
  // cover the line in which the change took place. Removes spans
1383
  // entirely within the change, reconnects spans belonging to the
1384
  // same marker that appear on both sides of the change, and cuts off
1385
  // spans partially within the change. Returns an array of span
1386
  // arrays with one element for each line in (after) the change.
1387
  function stretchSpansOverChange(doc, change) {
1388
    if (change.full) { return null }
1389
    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
1390
    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
1391
    if (!oldFirst && !oldLast) { return null }
1392
 
1393
    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
1394
    // Get the spans that 'stick out' on both sides
1395
    var first = markedSpansBefore(oldFirst, startCh, isInsert);
1396
    var last = markedSpansAfter(oldLast, endCh, isInsert);
1397
 
1398
    // Next, merge those two ends
1399
    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
1400
    if (first) {
1401
      // Fix up .to properties of first
1402
      for (var i = 0; i < first.length; ++i) {
1403
        var span = first[i];
1404
        if (span.to == null) {
1405
          var found = getMarkedSpanFor(last, span.marker);
1406
          if (!found) { span.to = startCh; }
1407
          else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
1408
        }
1409
      }
1410
    }
1411
    if (last) {
1412
      // Fix up .from in last (or move them into first in case of sameLine)
1413
      for (var i$1 = 0; i$1 < last.length; ++i$1) {
1414
        var span$1 = last[i$1];
1415
        if (span$1.to != null) { span$1.to += offset; }
1416
        if (span$1.from == null) {
1417
          var found$1 = getMarkedSpanFor(first, span$1.marker);
1418
          if (!found$1) {
1419
            span$1.from = offset;
1420
            if (sameLine) { (first || (first = [])).push(span$1); }
1421
          }
1422
        } else {
1423
          span$1.from += offset;
1424
          if (sameLine) { (first || (first = [])).push(span$1); }
1425
        }
1426
      }
1427
    }
1428
    // Make sure we didn't create any zero-length spans
1429
    if (first) { first = clearEmptySpans(first); }
1430
    if (last && last != first) { last = clearEmptySpans(last); }
1431
 
1432
    var newMarkers = [first];
1433
    if (!sameLine) {
1434
      // Fill gap with whole-line-spans
1435
      var gap = change.text.length - 2, gapMarkers;
1436
      if (gap > 0 && first)
1437
        { for (var i$2 = 0; i$2 < first.length; ++i$2)
1438
          { if (first[i$2].to == null)
1439
            { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
1440
      for (var i$3 = 0; i$3 < gap; ++i$3)
1441
        { newMarkers.push(gapMarkers); }
1442
      newMarkers.push(last);
1443
    }
1444
    return newMarkers
1445
  }
1446
 
1447
  // Remove spans that are empty and don't have a clearWhenEmpty
1448
  // option of false.
1449
  function clearEmptySpans(spans) {
1450
    for (var i = 0; i < spans.length; ++i) {
1451
      var span = spans[i];
1452
      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
1453
        { spans.splice(i--, 1); }
1454
    }
1455
    if (!spans.length) { return null }
1456
    return spans
1457
  }
1458
 
1459
  // Used to 'clip' out readOnly ranges when making a change.
1460
  function removeReadOnlyRanges(doc, from, to) {
1461
    var markers = null;
1462
    doc.iter(from.line, to.line + 1, function (line) {
1463
      if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
1464
        var mark = line.markedSpans[i].marker;
1465
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
1466
          { (markers || (markers = [])).push(mark); }
1467
      } }
1468
    });
1469
    if (!markers) { return null }
1470
    var parts = [{from: from, to: to}];
1471
    for (var i = 0; i < markers.length; ++i) {
1472
      var mk = markers[i], m = mk.find(0);
1473
      for (var j = 0; j < parts.length; ++j) {
1474
        var p = parts[j];
1475
        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
1476
        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
1477
        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
1478
          { newParts.push({from: p.from, to: m.from}); }
1479
        if (dto > 0 || !mk.inclusiveRight && !dto)
1480
          { newParts.push({from: m.to, to: p.to}); }
1481
        parts.splice.apply(parts, newParts);
1482
        j += newParts.length - 3;
1483
      }
1484
    }
1485
    return parts
1486
  }
1487
 
1488
  // Connect or disconnect spans from a line.
1489
  function detachMarkedSpans(line) {
1490
    var spans = line.markedSpans;
1491
    if (!spans) { return }
1492
    for (var i = 0; i < spans.length; ++i)
1493
      { spans[i].marker.detachLine(line); }
1494
    line.markedSpans = null;
1495
  }
1496
  function attachMarkedSpans(line, spans) {
1497
    if (!spans) { return }
1498
    for (var i = 0; i < spans.length; ++i)
1499
      { spans[i].marker.attachLine(line); }
1500
    line.markedSpans = spans;
1501
  }
1502
 
1503
  // Helpers used when computing which overlapping collapsed span
1504
  // counts as the larger one.
1505
  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
1506
  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
1507
 
1508
  // Returns a number indicating which of two overlapping collapsed
1509
  // spans is larger (and thus includes the other). Falls back to
1510
  // comparing ids when the spans cover exactly the same range.
1511
  function compareCollapsedMarkers(a, b) {
1512
    var lenDiff = a.lines.length - b.lines.length;
1513
    if (lenDiff != 0) { return lenDiff }
1514
    var aPos = a.find(), bPos = b.find();
1515
    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
1516
    if (fromCmp) { return -fromCmp }
1517
    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
1518
    if (toCmp) { return toCmp }
1519
    return b.id - a.id
1520
  }
1521
 
1522
  // Find out whether a line ends or starts in a collapsed span. If
1523
  // so, return the marker for that span.
1524
  function collapsedSpanAtSide(line, start) {
1525
    var sps = sawCollapsedSpans && line.markedSpans, found;
1526
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1527
      sp = sps[i];
1528
      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
1529
          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
1530
        { found = sp.marker; }
1531
    } }
1532
    return found
1533
  }
1534
  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
1535
  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
1536
 
1537
  function collapsedSpanAround(line, ch) {
1538
    var sps = sawCollapsedSpans && line.markedSpans, found;
1539
    if (sps) { for (var i = 0; i < sps.length; ++i) {
1540
      var sp = sps[i];
1541
      if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
1542
          (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
1543
    } }
1544
    return found
1545
  }
1546
 
1547
  // Test whether there exists a collapsed span that partially
1548
  // overlaps (covers the start or end, but not both) of a new span.
1549
  // Such overlap is not allowed.
15152 obado 1550
  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
1551
    var line = getLine(doc, lineNo);
14283 obado 1552
    var sps = sawCollapsedSpans && line.markedSpans;
1553
    if (sps) { for (var i = 0; i < sps.length; ++i) {
1554
      var sp = sps[i];
1555
      if (!sp.marker.collapsed) { continue }
1556
      var found = sp.marker.find(0);
1557
      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
1558
      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
1559
      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
1560
      if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
1561
          fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
1562
        { return true }
1563
    } }
1564
  }
1565
 
1566
  // A visual line is a line as drawn on the screen. Folding, for
1567
  // example, can cause multiple logical lines to appear on the same
1568
  // visual line. This finds the start of the visual line that the
1569
  // given line is part of (usually that is the line itself).
1570
  function visualLine(line) {
1571
    var merged;
1572
    while (merged = collapsedSpanAtStart(line))
1573
      { line = merged.find(-1, true).line; }
1574
    return line
1575
  }
1576
 
1577
  function visualLineEnd(line) {
1578
    var merged;
1579
    while (merged = collapsedSpanAtEnd(line))
1580
      { line = merged.find(1, true).line; }
1581
    return line
1582
  }
1583
 
1584
  // Returns an array of logical lines that continue the visual line
1585
  // started by the argument, or undefined if there are no such lines.
1586
  function visualLineContinued(line) {
1587
    var merged, lines;
1588
    while (merged = collapsedSpanAtEnd(line)) {
1589
      line = merged.find(1, true).line
1590
      ;(lines || (lines = [])).push(line);
1591
    }
1592
    return lines
1593
  }
1594
 
1595
  // Get the line number of the start of the visual line that the
1596
  // given line number is part of.
1597
  function visualLineNo(doc, lineN) {
1598
    var line = getLine(doc, lineN), vis = visualLine(line);
1599
    if (line == vis) { return lineN }
1600
    return lineNo(vis)
1601
  }
1602
 
1603
  // Get the line number of the start of the next visual line after
1604
  // the given line.
1605
  function visualLineEndNo(doc, lineN) {
1606
    if (lineN > doc.lastLine()) { return lineN }
1607
    var line = getLine(doc, lineN), merged;
1608
    if (!lineIsHidden(doc, line)) { return lineN }
1609
    while (merged = collapsedSpanAtEnd(line))
1610
      { line = merged.find(1, true).line; }
1611
    return lineNo(line) + 1
1612
  }
1613
 
1614
  // Compute whether a line is hidden. Lines count as hidden when they
1615
  // are part of a visual line that starts with another line, or when
1616
  // they are entirely covered by collapsed, non-widget span.
1617
  function lineIsHidden(doc, line) {
1618
    var sps = sawCollapsedSpans && line.markedSpans;
1619
    if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1620
      sp = sps[i];
1621
      if (!sp.marker.collapsed) { continue }
1622
      if (sp.from == null) { return true }
1623
      if (sp.marker.widgetNode) { continue }
1624
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
1625
        { return true }
1626
    } }
1627
  }
1628
  function lineIsHiddenInner(doc, line, span) {
1629
    if (span.to == null) {
1630
      var end = span.marker.find(1, true);
1631
      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
1632
    }
1633
    if (span.marker.inclusiveRight && span.to == line.text.length)
1634
      { return true }
1635
    for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
1636
      sp = line.markedSpans[i];
1637
      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
1638
          (sp.to == null || sp.to != span.from) &&
1639
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
1640
          lineIsHiddenInner(doc, line, sp)) { return true }
1641
    }
1642
  }
1643
 
1644
  // Find the height above the given line.
1645
  function heightAtLine(lineObj) {
1646
    lineObj = visualLine(lineObj);
1647
 
1648
    var h = 0, chunk = lineObj.parent;
1649
    for (var i = 0; i < chunk.lines.length; ++i) {
1650
      var line = chunk.lines[i];
1651
      if (line == lineObj) { break }
1652
      else { h += line.height; }
1653
    }
1654
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
1655
      for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
1656
        var cur = p.children[i$1];
1657
        if (cur == chunk) { break }
1658
        else { h += cur.height; }
1659
      }
1660
    }
1661
    return h
1662
  }
1663
 
1664
  // Compute the character length of a line, taking into account
1665
  // collapsed ranges (see markText) that might hide parts, and join
1666
  // other lines onto it.
1667
  function lineLength(line) {
1668
    if (line.height == 0) { return 0 }
1669
    var len = line.text.length, merged, cur = line;
1670
    while (merged = collapsedSpanAtStart(cur)) {
1671
      var found = merged.find(0, true);
1672
      cur = found.from.line;
1673
      len += found.from.ch - found.to.ch;
1674
    }
1675
    cur = line;
1676
    while (merged = collapsedSpanAtEnd(cur)) {
1677
      var found$1 = merged.find(0, true);
1678
      len -= cur.text.length - found$1.from.ch;
1679
      cur = found$1.to.line;
1680
      len += cur.text.length - found$1.to.ch;
1681
    }
1682
    return len
1683
  }
1684
 
1685
  // Find the longest line in the document.
1686
  function findMaxLine(cm) {
1687
    var d = cm.display, doc = cm.doc;
1688
    d.maxLine = getLine(doc, doc.first);
1689
    d.maxLineLength = lineLength(d.maxLine);
1690
    d.maxLineChanged = true;
1691
    doc.iter(function (line) {
1692
      var len = lineLength(line);
1693
      if (len > d.maxLineLength) {
1694
        d.maxLineLength = len;
1695
        d.maxLine = line;
1696
      }
1697
    });
1698
  }
1699
 
1700
  // LINE DATA STRUCTURE
1701
 
1702
  // Line objects. These hold state related to a line, including
1703
  // highlighting info (the styles array).
1704
  var Line = function(text, markedSpans, estimateHeight) {
1705
    this.text = text;
1706
    attachMarkedSpans(this, markedSpans);
1707
    this.height = estimateHeight ? estimateHeight(this) : 1;
1708
  };
1709
 
1710
  Line.prototype.lineNo = function () { return lineNo(this) };
1711
  eventMixin(Line);
1712
 
1713
  // Change the content (text, markers) of a line. Automatically
1714
  // invalidates cached information and tries to re-estimate the
1715
  // line's height.
1716
  function updateLine(line, text, markedSpans, estimateHeight) {
1717
    line.text = text;
1718
    if (line.stateAfter) { line.stateAfter = null; }
1719
    if (line.styles) { line.styles = null; }
1720
    if (line.order != null) { line.order = null; }
1721
    detachMarkedSpans(line);
1722
    attachMarkedSpans(line, markedSpans);
1723
    var estHeight = estimateHeight ? estimateHeight(line) : 1;
1724
    if (estHeight != line.height) { updateLineHeight(line, estHeight); }
1725
  }
1726
 
1727
  // Detach a line from the document tree and its markers.
1728
  function cleanUpLine(line) {
1729
    line.parent = null;
1730
    detachMarkedSpans(line);
1731
  }
1732
 
1733
  // Convert a style as returned by a mode (either null, or a string
1734
  // containing one or more styles) to a CSS style. This is cached,
1735
  // and also looks for line-wide styles.
1736
  var styleToClassCache = {}, styleToClassCacheWithMode = {};
1737
  function interpretTokenStyle(style, options) {
1738
    if (!style || /^\s*$/.test(style)) { return null }
1739
    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
1740
    return cache[style] ||
1741
      (cache[style] = style.replace(/\S+/g, "cm-$&"))
1742
  }
1743
 
1744
  // Render the DOM representation of the text of a line. Also builds
1745
  // up a 'line map', which points at the DOM nodes that represent
1746
  // specific stretches of text, and is used by the measuring code.
1747
  // The returned object contains the DOM node, this map, and
1748
  // information about line-wide styles that were set by the mode.
1749
  function buildLineContent(cm, lineView) {
1750
    // The padding-right forces the element to have a 'border', which
1751
    // is needed on Webkit to be able to get line-level bounding
1752
    // rectangles for it (in measureChar).
1753
    var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
1754
    var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
1755
                   col: 0, pos: 0, cm: cm,
1756
                   trailingSpace: false,
1757
                   splitSpaces: cm.getOption("lineWrapping")};
1758
    lineView.measure = {};
1759
 
1760
    // Iterate over the logical lines that make up this visual line.
1761
    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
1762
      var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
1763
      builder.pos = 0;
1764
      builder.addToken = buildToken;
1765
      // Optionally wire in some hacks into the token-rendering
1766
      // algorithm, to deal with browser quirks.
1767
      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
1768
        { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
1769
      builder.map = [];
1770
      var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
1771
      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
1772
      if (line.styleClasses) {
1773
        if (line.styleClasses.bgClass)
1774
          { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
1775
        if (line.styleClasses.textClass)
1776
          { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
1777
      }
1778
 
1779
      // Ensure at least a single node is present, for measuring.
1780
      if (builder.map.length == 0)
1781
        { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
1782
 
1783
      // Store the map and a cache object for the current logical line
1784
      if (i == 0) {
1785
        lineView.measure.map = builder.map;
1786
        lineView.measure.cache = {};
1787
      } else {
1788
  (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
1789
        ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
1790
      }
1791
    }
1792
 
1793
    // See issue #2901
1794
    if (webkit) {
1795
      var last = builder.content.lastChild;
1796
      if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
1797
        { builder.content.className = "cm-tab-wrap-hack"; }
1798
    }
1799
 
1800
    signal(cm, "renderLine", cm, lineView.line, builder.pre);
1801
    if (builder.pre.className)
1802
      { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1803
 
1804
    return builder
1805
  }
1806
 
1807
  function defaultSpecialCharPlaceholder(ch) {
1808
    var token = elt("span", "\u2022", "cm-invalidchar");
1809
    token.title = "\\u" + ch.charCodeAt(0).toString(16);
1810
    token.setAttribute("aria-label", token.title);
1811
    return token
1812
  }
1813
 
1814
  // Build up the DOM representation for a single token, and add it to
1815
  // the line map. Takes care to render special characters separately.
1816
  function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
1817
    if (!text) { return }
1818
    var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
1819
    var special = builder.cm.state.specialChars, mustWrap = false;
1820
    var content;
1821
    if (!special.test(text)) {
1822
      builder.col += text.length;
1823
      content = document.createTextNode(displayText);
1824
      builder.map.push(builder.pos, builder.pos + text.length, content);
1825
      if (ie && ie_version < 9) { mustWrap = true; }
1826
      builder.pos += text.length;
1827
    } else {
1828
      content = document.createDocumentFragment();
1829
      var pos = 0;
1830
      while (true) {
1831
        special.lastIndex = pos;
1832
        var m = special.exec(text);
1833
        var skipped = m ? m.index - pos : text.length - pos;
1834
        if (skipped) {
1835
          var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
1836
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
1837
          else { content.appendChild(txt); }
1838
          builder.map.push(builder.pos, builder.pos + skipped, txt);
1839
          builder.col += skipped;
1840
          builder.pos += skipped;
1841
        }
1842
        if (!m) { break }
1843
        pos += skipped + 1;
1844
        var txt$1 = (void 0);
1845
        if (m[0] == "\t") {
1846
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
1847
          txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
1848
          txt$1.setAttribute("role", "presentation");
1849
          txt$1.setAttribute("cm-text", "\t");
1850
          builder.col += tabWidth;
1851
        } else if (m[0] == "\r" || m[0] == "\n") {
1852
          txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
1853
          txt$1.setAttribute("cm-text", m[0]);
1854
          builder.col += 1;
1855
        } else {
1856
          txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
1857
          txt$1.setAttribute("cm-text", m[0]);
1858
          if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
1859
          else { content.appendChild(txt$1); }
1860
          builder.col += 1;
1861
        }
1862
        builder.map.push(builder.pos, builder.pos + 1, txt$1);
1863
        builder.pos++;
1864
      }
1865
    }
1866
    builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
16493 obado 1867
    if (style || startStyle || endStyle || mustWrap || css || attributes) {
14283 obado 1868
      var fullStyle = style || "";
1869
      if (startStyle) { fullStyle += startStyle; }
1870
      if (endStyle) { fullStyle += endStyle; }
1871
      var token = elt("span", [content], fullStyle, css);
1872
      if (attributes) {
1873
        for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
1874
          { token.setAttribute(attr, attributes[attr]); } }
1875
      }
1876
      return builder.content.appendChild(token)
1877
    }
1878
    builder.content.appendChild(content);
1879
  }
1880
 
1881
  // Change some spaces to NBSP to prevent the browser from collapsing
1882
  // trailing spaces at the end of a line when rendering text (issue #1362).
1883
  function splitSpaces(text, trailingBefore) {
1884
    if (text.length > 1 && !/  /.test(text)) { return text }
1885
    var spaceBefore = trailingBefore, result = "";
1886
    for (var i = 0; i < text.length; i++) {
1887
      var ch = text.charAt(i);
1888
      if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
1889
        { ch = "\u00a0"; }
1890
      result += ch;
1891
      spaceBefore = ch == " ";
1892
    }
1893
    return result
1894
  }
1895
 
1896
  // Work around nonsense dimensions being reported for stretches of
1897
  // right-to-left text.
1898
  function buildTokenBadBidi(inner, order) {
1899
    return function (builder, text, style, startStyle, endStyle, css, attributes) {
1900
      style = style ? style + " cm-force-border" : "cm-force-border";
1901
      var start = builder.pos, end = start + text.length;
1902
      for (;;) {
1903
        // Find the part that overlaps with the start of this text
1904
        var part = (void 0);
1905
        for (var i = 0; i < order.length; i++) {
1906
          part = order[i];
1907
          if (part.to > start && part.from <= start) { break }
1908
        }
1909
        if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
1910
        inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
1911
        startStyle = null;
1912
        text = text.slice(part.to - start);
1913
        start = part.to;
1914
      }
1915
    }
1916
  }
1917
 
1918
  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
1919
    var widget = !ignoreWidget && marker.widgetNode;
1920
    if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
1921
    if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
1922
      if (!widget)
1923
        { widget = builder.content.appendChild(document.createElement("span")); }
1924
      widget.setAttribute("cm-marker", marker.id);
1925
    }
1926
    if (widget) {
1927
      builder.cm.display.input.setUneditable(widget);
1928
      builder.content.appendChild(widget);
1929
    }
1930
    builder.pos += size;
1931
    builder.trailingSpace = false;
1932
  }
1933
 
1934
  // Outputs a number of spans to make up a line, taking highlighting
1935
  // and marked text into account.
1936
  function insertLineContent(line, builder, styles) {
1937
    var spans = line.markedSpans, allText = line.text, at = 0;
1938
    if (!spans) {
1939
      for (var i$1 = 1; i$1 < styles.length; i$1+=2)
1940
        { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
1941
      return
1942
    }
1943
 
1944
    var len = allText.length, pos = 0, i = 1, text = "", style, css;
1945
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
1946
    for (;;) {
1947
      if (nextChange == pos) { // Update current marker set
1948
        spanStyle = spanEndStyle = spanStartStyle = css = "";
1949
        attributes = null;
1950
        collapsed = null; nextChange = Infinity;
1951
        var foundBookmarks = [], endStyles = (void 0);
1952
        for (var j = 0; j < spans.length; ++j) {
1953
          var sp = spans[j], m = sp.marker;
1954
          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
1955
            foundBookmarks.push(m);
1956
          } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
1957
            if (sp.to != null && sp.to != pos && nextChange > sp.to) {
1958
              nextChange = sp.to;
1959
              spanEndStyle = "";
1960
            }
1961
            if (m.className) { spanStyle += " " + m.className; }
1962
            if (m.css) { css = (css ? css + ";" : "") + m.css; }
1963
            if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
1964
            if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
1965
            // support for the old title property
1966
            // https://github.com/codemirror/CodeMirror/pull/5673
1967
            if (m.title) { (attributes || (attributes = {})).title = m.title; }
1968
            if (m.attributes) {
1969
              for (var attr in m.attributes)
1970
                { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
1971
            }
1972
            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
1973
              { collapsed = sp; }
1974
          } else if (sp.from > pos && nextChange > sp.from) {
1975
            nextChange = sp.from;
1976
          }
1977
        }
1978
        if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
1979
          { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
1980
 
1981
        if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
1982
          { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
1983
        if (collapsed && (collapsed.from || 0) == pos) {
1984
          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
1985
                             collapsed.marker, collapsed.from == null);
1986
          if (collapsed.to == null) { return }
1987
          if (collapsed.to == pos) { collapsed = false; }
1988
        }
1989
      }
1990
      if (pos >= len) { break }
1991
 
1992
      var upto = Math.min(len, nextChange);
1993
      while (true) {
1994
        if (text) {
1995
          var end = pos + text.length;
1996
          if (!collapsed) {
1997
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
1998
            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
1999
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
2000
          }
2001
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
2002
          pos = end;
2003
          spanStartStyle = "";
2004
        }
2005
        text = allText.slice(at, at = styles[i++]);
2006
        style = interpretTokenStyle(styles[i++], builder.cm.options);
2007
      }
2008
    }
2009
  }
2010
 
2011
 
2012
  // These objects are used to represent the visible (currently drawn)
2013
  // part of the document. A LineView may correspond to multiple
2014
  // logical lines, if those are connected by collapsed ranges.
2015
  function LineView(doc, line, lineN) {
2016
    // The starting line
2017
    this.line = line;
2018
    // Continuing lines, if any
2019
    this.rest = visualLineContinued(line);
2020
    // Number of logical lines in this visual line
2021
    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
2022
    this.node = this.text = null;
2023
    this.hidden = lineIsHidden(doc, line);
2024
  }
2025
 
2026
  // Create a range of LineView objects for the given lines.
2027
  function buildViewArray(cm, from, to) {
2028
    var array = [], nextPos;
2029
    for (var pos = from; pos < to; pos = nextPos) {
2030
      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2031
      nextPos = pos + view.size;
2032
      array.push(view);
2033
    }
2034
    return array
2035
  }
2036
 
2037
  var operationGroup = null;
2038
 
2039
  function pushOperation(op) {
2040
    if (operationGroup) {
2041
      operationGroup.ops.push(op);
2042
    } else {
2043
      op.ownsGroup = operationGroup = {
2044
        ops: [op],
2045
        delayedCallbacks: []
2046
      };
2047
    }
2048
  }
2049
 
2050
  function fireCallbacksForOps(group) {
2051
    // Calls delayed callbacks and cursorActivity handlers until no
2052
    // new ones appear
2053
    var callbacks = group.delayedCallbacks, i = 0;
2054
    do {
2055
      for (; i < callbacks.length; i++)
2056
        { callbacks[i].call(null); }
2057
      for (var j = 0; j < group.ops.length; j++) {
2058
        var op = group.ops[j];
2059
        if (op.cursorActivityHandlers)
2060
          { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2061
            { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
2062
      }
2063
    } while (i < callbacks.length)
2064
  }
2065
 
2066
  function finishOperation(op, endCb) {
2067
    var group = op.ownsGroup;
2068
    if (!group) { return }
2069
 
2070
    try { fireCallbacksForOps(group); }
2071
    finally {
2072
      operationGroup = null;
2073
      endCb(group);
2074
    }
2075
  }
2076
 
2077
  var orphanDelayedCallbacks = null;
2078
 
2079
  // Often, we want to signal events at a point where we are in the
2080
  // middle of some work, but don't want the handler to start calling
2081
  // other methods on the editor, which might be in an inconsistent
2082
  // state or simply not expect any other events to happen.
2083
  // signalLater looks whether there are any handlers, and schedules
2084
  // them to be executed when the last operation ends, or, if no
2085
  // operation is active, when a timeout fires.
2086
  function signalLater(emitter, type /*, values...*/) {
2087
    var arr = getHandlers(emitter, type);
2088
    if (!arr.length) { return }
2089
    var args = Array.prototype.slice.call(arguments, 2), list;
2090
    if (operationGroup) {
2091
      list = operationGroup.delayedCallbacks;
2092
    } else if (orphanDelayedCallbacks) {
2093
      list = orphanDelayedCallbacks;
2094
    } else {
2095
      list = orphanDelayedCallbacks = [];
2096
      setTimeout(fireOrphanDelayed, 0);
2097
    }
2098
    var loop = function ( i ) {
2099
      list.push(function () { return arr[i].apply(null, args); });
2100
    };
2101
 
2102
    for (var i = 0; i < arr.length; ++i)
2103
      loop( i );
2104
  }
2105
 
2106
  function fireOrphanDelayed() {
2107
    var delayed = orphanDelayedCallbacks;
2108
    orphanDelayedCallbacks = null;
2109
    for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
2110
  }
2111
 
2112
  // When an aspect of a line changes, a string is added to
2113
  // lineView.changes. This updates the relevant part of the line's
2114
  // DOM structure.
2115
  function updateLineForChanges(cm, lineView, lineN, dims) {
2116
    for (var j = 0; j < lineView.changes.length; j++) {
2117
      var type = lineView.changes[j];
2118
      if (type == "text") { updateLineText(cm, lineView); }
2119
      else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
2120
      else if (type == "class") { updateLineClasses(cm, lineView); }
2121
      else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
2122
    }
2123
    lineView.changes = null;
2124
  }
2125
 
2126
  // Lines with gutter elements, widgets or a background class need to
2127
  // be wrapped, and have the extra elements added to the wrapper div
2128
  function ensureLineWrapped(lineView) {
2129
    if (lineView.node == lineView.text) {
2130
      lineView.node = elt("div", null, null, "position: relative");
2131
      if (lineView.text.parentNode)
2132
        { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
2133
      lineView.node.appendChild(lineView.text);
2134
      if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
2135
    }
2136
    return lineView.node
2137
  }
2138
 
2139
  function updateLineBackground(cm, lineView) {
2140
    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
2141
    if (cls) { cls += " CodeMirror-linebackground"; }
2142
    if (lineView.background) {
2143
      if (cls) { lineView.background.className = cls; }
2144
      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
2145
    } else if (cls) {
2146
      var wrap = ensureLineWrapped(lineView);
2147
      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
2148
      cm.display.input.setUneditable(lineView.background);
2149
    }
2150
  }
2151
 
2152
  // Wrapper around buildLineContent which will reuse the structure
2153
  // in display.externalMeasured when possible.
2154
  function getLineContent(cm, lineView) {
2155
    var ext = cm.display.externalMeasured;
2156
    if (ext && ext.line == lineView.line) {
2157
      cm.display.externalMeasured = null;
2158
      lineView.measure = ext.measure;
2159
      return ext.built
2160
    }
2161
    return buildLineContent(cm, lineView)
2162
  }
2163
 
2164
  // Redraw the line's text. Interacts with the background and text
2165
  // classes because the mode may output tokens that influence these
2166
  // classes.
2167
  function updateLineText(cm, lineView) {
2168
    var cls = lineView.text.className;
2169
    var built = getLineContent(cm, lineView);
2170
    if (lineView.text == lineView.node) { lineView.node = built.pre; }
2171
    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
2172
    lineView.text = built.pre;
2173
    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
2174
      lineView.bgClass = built.bgClass;
2175
      lineView.textClass = built.textClass;
2176
      updateLineClasses(cm, lineView);
2177
    } else if (cls) {
2178
      lineView.text.className = cls;
2179
    }
2180
  }
2181
 
2182
  function updateLineClasses(cm, lineView) {
2183
    updateLineBackground(cm, lineView);
2184
    if (lineView.line.wrapClass)
2185
      { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
2186
    else if (lineView.node != lineView.text)
2187
      { lineView.node.className = ""; }
2188
    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
2189
    lineView.text.className = textClass || "";
2190
  }
2191
 
2192
  function updateLineGutter(cm, lineView, lineN, dims) {
2193
    if (lineView.gutter) {
2194
      lineView.node.removeChild(lineView.gutter);
2195
      lineView.gutter = null;
2196
    }
2197
    if (lineView.gutterBackground) {
2198
      lineView.node.removeChild(lineView.gutterBackground);
2199
      lineView.gutterBackground = null;
2200
    }
2201
    if (lineView.line.gutterClass) {
2202
      var wrap = ensureLineWrapped(lineView);
2203
      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
2204
                                      ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
2205
      cm.display.input.setUneditable(lineView.gutterBackground);
2206
      wrap.insertBefore(lineView.gutterBackground, lineView.text);
2207
    }
2208
    var markers = lineView.line.gutterMarkers;
2209
    if (cm.options.lineNumbers || markers) {
2210
      var wrap$1 = ensureLineWrapped(lineView);
2211
      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
16493 obado 2212
      gutterWrap.setAttribute("aria-hidden", "true");
14283 obado 2213
      cm.display.input.setUneditable(gutterWrap);
2214
      wrap$1.insertBefore(gutterWrap, lineView.text);
2215
      if (lineView.line.gutterClass)
2216
        { gutterWrap.className += " " + lineView.line.gutterClass; }
2217
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
2218
        { lineView.lineNumber = gutterWrap.appendChild(
2219
          elt("div", lineNumberFor(cm.options, lineN),
2220
              "CodeMirror-linenumber CodeMirror-gutter-elt",
2221
              ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
2222
      if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
2223
        var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
2224
        if (found)
2225
          { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
2226
                                     ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
2227
      } }
2228
    }
2229
  }
2230
 
2231
  function updateLineWidgets(cm, lineView, dims) {
2232
    if (lineView.alignable) { lineView.alignable = null; }
15152 obado 2233
    var isWidget = classTest("CodeMirror-linewidget");
14283 obado 2234
    for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
2235
      next = node.nextSibling;
15152 obado 2236
      if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
14283 obado 2237
    }
2238
    insertLineWidgets(cm, lineView, dims);
2239
  }
2240
 
2241
  // Build a line's DOM representation from scratch
2242
  function buildLineElement(cm, lineView, lineN, dims) {
2243
    var built = getLineContent(cm, lineView);
2244
    lineView.text = lineView.node = built.pre;
2245
    if (built.bgClass) { lineView.bgClass = built.bgClass; }
2246
    if (built.textClass) { lineView.textClass = built.textClass; }
2247
 
2248
    updateLineClasses(cm, lineView);
2249
    updateLineGutter(cm, lineView, lineN, dims);
2250
    insertLineWidgets(cm, lineView, dims);
2251
    return lineView.node
2252
  }
2253
 
2254
  // A lineView may contain multiple logical lines (when merged by
2255
  // collapsed spans). The widgets for all of them need to be drawn.
2256
  function insertLineWidgets(cm, lineView, dims) {
2257
    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
2258
    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2259
      { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
2260
  }
2261
 
2262
  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
2263
    if (!line.widgets) { return }
2264
    var wrap = ensureLineWrapped(lineView);
2265
    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
15152 obado 2266
      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
14283 obado 2267
      if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
2268
      positionLineWidget(widget, node, lineView, dims);
2269
      cm.display.input.setUneditable(node);
2270
      if (allowAbove && widget.above)
2271
        { wrap.insertBefore(node, lineView.gutter || lineView.text); }
2272
      else
2273
        { wrap.appendChild(node); }
2274
      signalLater(widget, "redraw");
2275
    }
2276
  }
2277
 
2278
  function positionLineWidget(widget, node, lineView, dims) {
2279
    if (widget.noHScroll) {
2280
  (lineView.alignable || (lineView.alignable = [])).push(node);
2281
      var width = dims.wrapperWidth;
2282
      node.style.left = dims.fixedPos + "px";
2283
      if (!widget.coverGutter) {
2284
        width -= dims.gutterTotalWidth;
2285
        node.style.paddingLeft = dims.gutterTotalWidth + "px";
2286
      }
2287
      node.style.width = width + "px";
2288
    }
2289
    if (widget.coverGutter) {
2290
      node.style.zIndex = 5;
2291
      node.style.position = "relative";
2292
      if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2293
    }
2294
  }
2295
 
2296
  function widgetHeight(widget) {
2297
    if (widget.height != null) { return widget.height }
2298
    var cm = widget.doc.cm;
2299
    if (!cm) { return 0 }
2300
    if (!contains(document.body, widget.node)) {
2301
      var parentStyle = "position: relative;";
2302
      if (widget.coverGutter)
2303
        { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
2304
      if (widget.noHScroll)
2305
        { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
2306
      removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
2307
    }
2308
    return widget.height = widget.node.parentNode.offsetHeight
2309
  }
2310
 
2311
  // Return true when the given mouse event happened in a widget
2312
  function eventInWidget(display, e) {
2313
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2314
      if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
2315
          (n.parentNode == display.sizer && n != display.mover))
2316
        { return true }
2317
    }
2318
  }
2319
 
2320
  // POSITION MEASUREMENT
2321
 
2322
  function paddingTop(display) {return display.lineSpace.offsetTop}
2323
  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
2324
  function paddingH(display) {
2325
    if (display.cachedPaddingH) { return display.cachedPaddingH }
2326
    var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
2327
    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2328
    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2329
    if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
2330
    return data
2331
  }
2332
 
2333
  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
2334
  function displayWidth(cm) {
2335
    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
2336
  }
2337
  function displayHeight(cm) {
2338
    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
2339
  }
2340
 
2341
  // Ensure the lineView.wrapping.heights array is populated. This is
2342
  // an array of bottom offsets for the lines that make up a drawn
2343
  // line. When lineWrapping is on, there might be more than one
2344
  // height.
2345
  function ensureLineHeights(cm, lineView, rect) {
2346
    var wrapping = cm.options.lineWrapping;
2347
    var curWidth = wrapping && displayWidth(cm);
2348
    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2349
      var heights = lineView.measure.heights = [];
2350
      if (wrapping) {
2351
        lineView.measure.width = curWidth;
2352
        var rects = lineView.text.firstChild.getClientRects();
2353
        for (var i = 0; i < rects.length - 1; i++) {
2354
          var cur = rects[i], next = rects[i + 1];
2355
          if (Math.abs(cur.bottom - next.bottom) > 2)
2356
            { heights.push((cur.bottom + next.top) / 2 - rect.top); }
2357
        }
2358
      }
2359
      heights.push(rect.bottom - rect.top);
2360
    }
2361
  }
2362
 
2363
  // Find a line map (mapping character offsets to text nodes) and a
2364
  // measurement cache for the given line number. (A line view might
2365
  // contain multiple lines when collapsed ranges are present.)
2366
  function mapFromLineView(lineView, line, lineN) {
2367
    if (lineView.line == line)
2368
      { return {map: lineView.measure.map, cache: lineView.measure.cache} }
16493 obado 2369
    if (lineView.rest) {
2370
      for (var i = 0; i < lineView.rest.length; i++)
2371
        { if (lineView.rest[i] == line)
2372
          { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
2373
      for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
2374
        { if (lineNo(lineView.rest[i$1]) > lineN)
2375
          { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
2376
    }
14283 obado 2377
  }
2378
 
2379
  // Render a line into the hidden node display.externalMeasured. Used
2380
  // when measurement is needed for a line that's not in the viewport.
2381
  function updateExternalMeasurement(cm, line) {
2382
    line = visualLine(line);
2383
    var lineN = lineNo(line);
2384
    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2385
    view.lineN = lineN;
2386
    var built = view.built = buildLineContent(cm, view);
2387
    view.text = built.pre;
2388
    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2389
    return view
2390
  }
2391
 
2392
  // Get a {top, bottom, left, right} box (in line-local coordinates)
2393
  // for a given character.
2394
  function measureChar(cm, line, ch, bias) {
2395
    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
2396
  }
2397
 
2398
  // Find a line view that corresponds to the given line number.
2399
  function findViewForLine(cm, lineN) {
2400
    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2401
      { return cm.display.view[findViewIndex(cm, lineN)] }
2402
    var ext = cm.display.externalMeasured;
2403
    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2404
      { return ext }
2405
  }
2406
 
2407
  // Measurement can be split in two steps, the set-up work that
2408
  // applies to the whole line, and the measurement of the actual
2409
  // character. Functions like coordsChar, that need to do a lot of
2410
  // measurements in a row, can thus ensure that the set-up work is
2411
  // only done once.
2412
  function prepareMeasureForLine(cm, line) {
2413
    var lineN = lineNo(line);
2414
    var view = findViewForLine(cm, lineN);
2415
    if (view && !view.text) {
2416
      view = null;
2417
    } else if (view && view.changes) {
2418
      updateLineForChanges(cm, view, lineN, getDimensions(cm));
2419
      cm.curOp.forceUpdate = true;
2420
    }
2421
    if (!view)
2422
      { view = updateExternalMeasurement(cm, line); }
2423
 
2424
    var info = mapFromLineView(view, line, lineN);
2425
    return {
2426
      line: line, view: view, rect: null,
2427
      map: info.map, cache: info.cache, before: info.before,
2428
      hasHeights: false
2429
    }
2430
  }
2431
 
2432
  // Given a prepared measurement object, measures the position of an
2433
  // actual character (or fetches it from the cache).
2434
  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2435
    if (prepared.before) { ch = -1; }
2436
    var key = ch + (bias || ""), found;
2437
    if (prepared.cache.hasOwnProperty(key)) {
2438
      found = prepared.cache[key];
2439
    } else {
2440
      if (!prepared.rect)
2441
        { prepared.rect = prepared.view.text.getBoundingClientRect(); }
2442
      if (!prepared.hasHeights) {
2443
        ensureLineHeights(cm, prepared.view, prepared.rect);
2444
        prepared.hasHeights = true;
2445
      }
2446
      found = measureCharInner(cm, prepared, ch, bias);
2447
      if (!found.bogus) { prepared.cache[key] = found; }
2448
    }
2449
    return {left: found.left, right: found.right,
2450
            top: varHeight ? found.rtop : found.top,
2451
            bottom: varHeight ? found.rbottom : found.bottom}
2452
  }
2453
 
2454
  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2455
 
15152 obado 2456
  function nodeAndOffsetInLineMap(map, ch, bias) {
14283 obado 2457
    var node, start, end, collapse, mStart, mEnd;
2458
    // First, search the line map for the text node corresponding to,
2459
    // or closest to, the target character.
15152 obado 2460
    for (var i = 0; i < map.length; i += 3) {
2461
      mStart = map[i];
2462
      mEnd = map[i + 1];
14283 obado 2463
      if (ch < mStart) {
2464
        start = 0; end = 1;
2465
        collapse = "left";
2466
      } else if (ch < mEnd) {
2467
        start = ch - mStart;
2468
        end = start + 1;
15152 obado 2469
      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
14283 obado 2470
        end = mEnd - mStart;
2471
        start = end - 1;
2472
        if (ch >= mEnd) { collapse = "right"; }
2473
      }
2474
      if (start != null) {
15152 obado 2475
        node = map[i + 2];
14283 obado 2476
        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2477
          { collapse = bias; }
2478
        if (bias == "left" && start == 0)
15152 obado 2479
          { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2480
            node = map[(i -= 3) + 2];
14283 obado 2481
            collapse = "left";
2482
          } }
2483
        if (bias == "right" && start == mEnd - mStart)
15152 obado 2484
          { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2485
            node = map[(i += 3) + 2];
14283 obado 2486
            collapse = "right";
2487
          } }
2488
        break
2489
      }
2490
    }
2491
    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
2492
  }
2493
 
2494
  function getUsefulRect(rects, bias) {
2495
    var rect = nullRect;
2496
    if (bias == "left") { for (var i = 0; i < rects.length; i++) {
2497
      if ((rect = rects[i]).left != rect.right) { break }
2498
    } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
2499
      if ((rect = rects[i$1]).left != rect.right) { break }
2500
    } }
2501
    return rect
2502
  }
2503
 
2504
  function measureCharInner(cm, prepared, ch, bias) {
2505
    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2506
    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2507
 
2508
    var rect;
2509
    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2510
      for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2511
        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
2512
        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
2513
        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2514
          { rect = node.parentNode.getBoundingClientRect(); }
2515
        else
2516
          { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
2517
        if (rect.left || rect.right || start == 0) { break }
2518
        end = start;
2519
        start = start - 1;
2520
        collapse = "right";
2521
      }
2522
      if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
2523
    } else { // If it is a widget, simply get the box for the whole widget.
2524
      if (start > 0) { collapse = bias = "right"; }
2525
      var rects;
2526
      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2527
        { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
2528
      else
2529
        { rect = node.getBoundingClientRect(); }
2530
    }
2531
    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2532
      var rSpan = node.parentNode.getClientRects()[0];
2533
      if (rSpan)
2534
        { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
2535
      else
2536
        { rect = nullRect; }
2537
    }
2538
 
2539
    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2540
    var mid = (rtop + rbot) / 2;
2541
    var heights = prepared.view.measure.heights;
2542
    var i = 0;
2543
    for (; i < heights.length - 1; i++)
2544
      { if (mid < heights[i]) { break } }
2545
    var top = i ? heights[i - 1] : 0, bot = heights[i];
2546
    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2547
                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2548
                  top: top, bottom: bot};
2549
    if (!rect.left && !rect.right) { result.bogus = true; }
2550
    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2551
 
2552
    return result
2553
  }
2554
 
2555
  // Work around problem with bounding client rects on ranges being
2556
  // returned incorrectly when zoomed on IE10 and below.
2557
  function maybeUpdateRectForZooming(measure, rect) {
2558
    if (!window.screen || screen.logicalXDPI == null ||
2559
        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2560
      { return rect }
2561
    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2562
    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2563
    return {left: rect.left * scaleX, right: rect.right * scaleX,
2564
            top: rect.top * scaleY, bottom: rect.bottom * scaleY}
2565
  }
2566
 
2567
  function clearLineMeasurementCacheFor(lineView) {
2568
    if (lineView.measure) {
2569
      lineView.measure.cache = {};
2570
      lineView.measure.heights = null;
2571
      if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2572
        { lineView.measure.caches[i] = {}; } }
2573
    }
2574
  }
2575
 
2576
  function clearLineMeasurementCache(cm) {
2577
    cm.display.externalMeasure = null;
2578
    removeChildren(cm.display.lineMeasure);
2579
    for (var i = 0; i < cm.display.view.length; i++)
2580
      { clearLineMeasurementCacheFor(cm.display.view[i]); }
2581
  }
2582
 
2583
  function clearCaches(cm) {
2584
    clearLineMeasurementCache(cm);
2585
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2586
    if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
2587
    cm.display.lineNumChars = null;
2588
  }
2589
 
17702 obado 2590
  function pageScrollX(doc) {
14283 obado 2591
    // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
2592
    // which causes page_Offset and bounding client rects to use
2593
    // different reference viewports and invalidate our calculations.
17702 obado 2594
    if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
2595
    return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
14283 obado 2596
  }
17702 obado 2597
  function pageScrollY(doc) {
2598
    if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
2599
    return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
14283 obado 2600
  }
2601
 
2602
  function widgetTopHeight(lineObj) {
16493 obado 2603
    var ref = visualLine(lineObj);
2604
    var widgets = ref.widgets;
14283 obado 2605
    var height = 0;
16493 obado 2606
    if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
2607
      { height += widgetHeight(widgets[i]); } } }
14283 obado 2608
    return height
2609
  }
2610
 
2611
  // Converts a {top, bottom, left, right} box from line-local
2612
  // coordinates into another coordinate system. Context may be one of
2613
  // "line", "div" (display.lineDiv), "local"./null (editor), "window",
2614
  // or "page".
2615
  function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
2616
    if (!includeWidgets) {
2617
      var height = widgetTopHeight(lineObj);
2618
      rect.top += height; rect.bottom += height;
2619
    }
2620
    if (context == "line") { return rect }
2621
    if (!context) { context = "local"; }
2622
    var yOff = heightAtLine(lineObj);
2623
    if (context == "local") { yOff += paddingTop(cm.display); }
2624
    else { yOff -= cm.display.viewOffset; }
2625
    if (context == "page" || context == "window") {
2626
      var lOff = cm.display.lineSpace.getBoundingClientRect();
17702 obado 2627
      yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
2628
      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
14283 obado 2629
      rect.left += xOff; rect.right += xOff;
2630
    }
2631
    rect.top += yOff; rect.bottom += yOff;
2632
    return rect
2633
  }
2634
 
2635
  // Coverts a box from "div" coords to another coordinate system.
2636
  // Context may be "window", "page", "div", or "local"./null.
2637
  function fromCoordSystem(cm, coords, context) {
2638
    if (context == "div") { return coords }
2639
    var left = coords.left, top = coords.top;
2640
    // First move into "page" coordinate system
2641
    if (context == "page") {
17702 obado 2642
      left -= pageScrollX(doc(cm));
2643
      top -= pageScrollY(doc(cm));
14283 obado 2644
    } else if (context == "local" || !context) {
2645
      var localBox = cm.display.sizer.getBoundingClientRect();
2646
      left += localBox.left;
2647
      top += localBox.top;
2648
    }
2649
 
2650
    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2651
    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
2652
  }
2653
 
2654
  function charCoords(cm, pos, context, lineObj, bias) {
2655
    if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
2656
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
2657
  }
2658
 
2659
  // Returns a box for a given cursor position, which may have an
2660
  // 'other' property containing the position of the secondary cursor
2661
  // on a bidi boundary.
2662
  // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
2663
  // and after `char - 1` in writing order of `char - 1`
2664
  // A cursor Pos(line, char, "after") is on the same visual line as `char`
2665
  // and before `char` in writing order of `char`
2666
  // Examples (upper-case letters are RTL, lower-case are LTR):
2667
  //     Pos(0, 1, ...)
2668
  //     before   after
2669
  // ab     a|b     a|b
2670
  // aB     a|B     aB|
2671
  // Ab     |Ab     A|b
2672
  // AB     B|A     B|A
2673
  // Every position after the last character on a line is considered to stick
2674
  // to the last character on the line.
2675
  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2676
    lineObj = lineObj || getLine(cm.doc, pos.line);
2677
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2678
    function get(ch, right) {
2679
      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2680
      if (right) { m.left = m.right; } else { m.right = m.left; }
2681
      return intoCoordSystem(cm, lineObj, m, context)
2682
    }
2683
    var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
2684
    if (ch >= lineObj.text.length) {
2685
      ch = lineObj.text.length;
2686
      sticky = "before";
2687
    } else if (ch <= 0) {
2688
      ch = 0;
2689
      sticky = "after";
2690
    }
2691
    if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
2692
 
2693
    function getBidi(ch, partPos, invert) {
2694
      var part = order[partPos], right = part.level == 1;
2695
      return get(invert ? ch - 1 : ch, right != invert)
2696
    }
2697
    var partPos = getBidiPartAt(order, ch, sticky);
2698
    var other = bidiOther;
2699
    var val = getBidi(ch, partPos, sticky == "before");
2700
    if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
2701
    return val
2702
  }
2703
 
2704
  // Used to cheaply estimate the coordinates for a position. Used for
2705
  // intermediate scroll updates.
2706
  function estimateCoords(cm, pos) {
2707
    var left = 0;
2708
    pos = clipPos(cm.doc, pos);
2709
    if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
2710
    var lineObj = getLine(cm.doc, pos.line);
2711
    var top = heightAtLine(lineObj) + paddingTop(cm.display);
2712
    return {left: left, right: left, top: top, bottom: top + lineObj.height}
2713
  }
2714
 
2715
  // Positions returned by coordsChar contain some extra information.
2716
  // xRel is the relative x position of the input coordinates compared
2717
  // to the found position (so xRel > 0 means the coordinates are to
2718
  // the right of the character position, for example). When outside
2719
  // is true, that means the coordinates lie outside the line's
2720
  // vertical range.
2721
  function PosWithInfo(line, ch, sticky, outside, xRel) {
2722
    var pos = Pos(line, ch, sticky);
2723
    pos.xRel = xRel;
2724
    if (outside) { pos.outside = outside; }
2725
    return pos
2726
  }
2727
 
2728
  // Compute the character position closest to the given coordinates.
2729
  // Input must be lineSpace-local ("div" coordinate system).
2730
  function coordsChar(cm, x, y) {
2731
    var doc = cm.doc;
2732
    y += cm.display.viewOffset;
2733
    if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
2734
    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2735
    if (lineN > last)
2736
      { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
2737
    if (x < 0) { x = 0; }
2738
 
2739
    var lineObj = getLine(doc, lineN);
2740
    for (;;) {
2741
      var found = coordsCharInner(cm, lineObj, lineN, x, y);
2742
      var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
2743
      if (!collapsed) { return found }
2744
      var rangeEnd = collapsed.find(1);
2745
      if (rangeEnd.line == lineN) { return rangeEnd }
2746
      lineObj = getLine(doc, lineN = rangeEnd.line);
2747
    }
2748
  }
2749
 
2750
  function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
2751
    y -= widgetTopHeight(lineObj);
2752
    var end = lineObj.text.length;
2753
    var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
2754
    end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
2755
    return {begin: begin, end: end}
2756
  }
2757
 
2758
  function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
2759
    if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2760
    var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
2761
    return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
2762
  }
2763
 
2764
  // Returns true if the given side of a box is after the given
2765
  // coordinates, in top-to-bottom, left-to-right order.
2766
  function boxIsAfter(box, x, y, left) {
2767
    return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
2768
  }
2769
 
15152 obado 2770
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
14283 obado 2771
    // Move y into line-local coordinate space
2772
    y -= heightAtLine(lineObj);
2773
    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2774
    // When directly calling `measureCharPrepared`, we have to adjust
2775
    // for the widgets at this line.
15152 obado 2776
    var widgetHeight = widgetTopHeight(lineObj);
14283 obado 2777
    var begin = 0, end = lineObj.text.length, ltr = true;
2778
 
2779
    var order = getOrder(lineObj, cm.doc.direction);
2780
    // If the line isn't plain left-to-right text, first figure out
2781
    // which bidi section the coordinates fall into.
2782
    if (order) {
2783
      var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
15152 obado 2784
                   (cm, lineObj, lineNo, preparedMeasure, order, x, y);
14283 obado 2785
      ltr = part.level != 1;
2786
      // The awkward -1 offsets are needed because findFirst (called
2787
      // on these below) will treat its first bound as inclusive,
2788
      // second as exclusive, but we want to actually address the
2789
      // characters in the part's range
2790
      begin = ltr ? part.from : part.to - 1;
2791
      end = ltr ? part.to : part.from - 1;
2792
    }
2793
 
2794
    // A binary search to find the first character whose bounding box
2795
    // starts after the coordinates. If we run across any whose box wrap
2796
    // the coordinates, store that.
2797
    var chAround = null, boxAround = null;
2798
    var ch = findFirst(function (ch) {
2799
      var box = measureCharPrepared(cm, preparedMeasure, ch);
15152 obado 2800
      box.top += widgetHeight; box.bottom += widgetHeight;
14283 obado 2801
      if (!boxIsAfter(box, x, y, false)) { return false }
2802
      if (box.top <= y && box.left <= x) {
2803
        chAround = ch;
2804
        boxAround = box;
2805
      }
2806
      return true
2807
    }, begin, end);
2808
 
2809
    var baseX, sticky, outside = false;
2810
    // If a box around the coordinates was found, use that
2811
    if (boxAround) {
2812
      // Distinguish coordinates nearer to the left or right side of the box
2813
      var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
2814
      ch = chAround + (atStart ? 0 : 1);
2815
      sticky = atStart ? "after" : "before";
2816
      baseX = atLeft ? boxAround.left : boxAround.right;
2817
    } else {
2818
      // (Adjust for extended bound, if necessary.)
2819
      if (!ltr && (ch == end || ch == begin)) { ch++; }
2820
      // To determine which side to associate with, get the box to the
2821
      // left of the character and compare it's vertical position to the
2822
      // coordinates
2823
      sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
15152 obado 2824
        (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
14283 obado 2825
        "after" : "before";
2826
      // Now get accurate coordinates for this place, in order to get a
2827
      // base X position
15152 obado 2828
      var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
14283 obado 2829
      baseX = coords.left;
2830
      outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
2831
    }
2832
 
2833
    ch = skipExtendingChars(lineObj.text, ch, 1);
15152 obado 2834
    return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
14283 obado 2835
  }
2836
 
15152 obado 2837
  function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
14283 obado 2838
    // Bidi parts are sorted left-to-right, and in a non-line-wrapping
2839
    // situation, we can take this ordering to correspond to the visual
2840
    // ordering. This finds the first part whose end is after the given
2841
    // coordinates.
2842
    var index = findFirst(function (i) {
2843
      var part = order[i], ltr = part.level != 1;
15152 obado 2844
      return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
14283 obado 2845
                                     "line", lineObj, preparedMeasure), x, y, true)
2846
    }, 0, order.length - 1);
2847
    var part = order[index];
2848
    // If this isn't the first part, the part's start is also after
2849
    // the coordinates, and the coordinates aren't on the same line as
2850
    // that start, move one part back.
2851
    if (index > 0) {
2852
      var ltr = part.level != 1;
15152 obado 2853
      var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
14283 obado 2854
                               "line", lineObj, preparedMeasure);
2855
      if (boxIsAfter(start, x, y, true) && start.top > y)
2856
        { part = order[index - 1]; }
2857
    }
2858
    return part
2859
  }
2860
 
2861
  function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
2862
    // In a wrapped line, rtl text on wrapping boundaries can do things
2863
    // that don't correspond to the ordering in our `order` array at
2864
    // all, so a binary search doesn't work, and we want to return a
2865
    // part that only spans one line so that the binary search in
2866
    // coordsCharInner is safe. As such, we first find the extent of the
2867
    // wrapped line, and then do a flat search in which we discard any
2868
    // spans that aren't on the line.
2869
    var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
2870
    var begin = ref.begin;
2871
    var end = ref.end;
2872
    if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
2873
    var part = null, closestDist = null;
2874
    for (var i = 0; i < order.length; i++) {
2875
      var p = order[i];
2876
      if (p.from >= end || p.to <= begin) { continue }
2877
      var ltr = p.level != 1;
2878
      var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
2879
      // Weigh against spans ending before this, so that they are only
2880
      // picked if nothing ends after
2881
      var dist = endX < x ? x - endX + 1e9 : endX - x;
2882
      if (!part || closestDist > dist) {
2883
        part = p;
2884
        closestDist = dist;
2885
      }
2886
    }
2887
    if (!part) { part = order[order.length - 1]; }
2888
    // Clip the part to the wrapped line.
2889
    if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
2890
    if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
2891
    return part
2892
  }
2893
 
2894
  var measureText;
2895
  // Compute the default text height.
2896
  function textHeight(display) {
2897
    if (display.cachedTextHeight != null) { return display.cachedTextHeight }
2898
    if (measureText == null) {
2899
      measureText = elt("pre", null, "CodeMirror-line-like");
2900
      // Measure a bunch of lines, for browsers that compute
2901
      // fractional heights.
2902
      for (var i = 0; i < 49; ++i) {
2903
        measureText.appendChild(document.createTextNode("x"));
2904
        measureText.appendChild(elt("br"));
2905
      }
2906
      measureText.appendChild(document.createTextNode("x"));
2907
    }
2908
    removeChildrenAndAdd(display.measure, measureText);
2909
    var height = measureText.offsetHeight / 50;
2910
    if (height > 3) { display.cachedTextHeight = height; }
2911
    removeChildren(display.measure);
2912
    return height || 1
2913
  }
2914
 
2915
  // Compute the default character width.
2916
  function charWidth(display) {
2917
    if (display.cachedCharWidth != null) { return display.cachedCharWidth }
2918
    var anchor = elt("span", "xxxxxxxxxx");
2919
    var pre = elt("pre", [anchor], "CodeMirror-line-like");
2920
    removeChildrenAndAdd(display.measure, pre);
2921
    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2922
    if (width > 2) { display.cachedCharWidth = width; }
2923
    return width || 10
2924
  }
2925
 
2926
  // Do a bulk-read of the DOM positions and sizes needed to draw the
2927
  // view, so that we don't interleave reading and writing to the DOM.
2928
  function getDimensions(cm) {
2929
    var d = cm.display, left = {}, width = {};
2930
    var gutterLeft = d.gutters.clientLeft;
2931
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
2932
      var id = cm.display.gutterSpecs[i].className;
2933
      left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
2934
      width[id] = n.clientWidth;
2935
    }
2936
    return {fixedPos: compensateForHScroll(d),
2937
            gutterTotalWidth: d.gutters.offsetWidth,
2938
            gutterLeft: left,
2939
            gutterWidth: width,
2940
            wrapperWidth: d.wrapper.clientWidth}
2941
  }
2942
 
2943
  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
2944
  // but using getBoundingClientRect to get a sub-pixel-accurate
2945
  // result.
2946
  function compensateForHScroll(display) {
2947
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
2948
  }
2949
 
2950
  // Returns a function that estimates the height of a line, to use as
2951
  // first approximation until the line becomes visible (and is thus
2952
  // properly measurable).
2953
  function estimateHeight(cm) {
2954
    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
2955
    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
2956
    return function (line) {
2957
      if (lineIsHidden(cm.doc, line)) { return 0 }
2958
 
2959
      var widgetsHeight = 0;
2960
      if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
2961
        if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
2962
      } }
2963
 
2964
      if (wrapping)
2965
        { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
2966
      else
2967
        { return widgetsHeight + th }
2968
    }
2969
  }
2970
 
2971
  function estimateLineHeights(cm) {
2972
    var doc = cm.doc, est = estimateHeight(cm);
2973
    doc.iter(function (line) {
2974
      var estHeight = est(line);
2975
      if (estHeight != line.height) { updateLineHeight(line, estHeight); }
2976
    });
2977
  }
2978
 
2979
  // Given a mouse event, find the corresponding position. If liberal
2980
  // is false, it checks whether a gutter or scrollbar was clicked,
2981
  // and returns null if it was. forRect is used by rectangular
2982
  // selections, and tries to estimate a character position even for
2983
  // coordinates beyond the right of the text.
2984
  function posFromMouse(cm, e, liberal, forRect) {
2985
    var display = cm.display;
2986
    if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
2987
 
2988
    var x, y, space = display.lineSpace.getBoundingClientRect();
2989
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
2990
    try { x = e.clientX - space.left; y = e.clientY - space.top; }
15332 obado 2991
    catch (e$1) { return null }
14283 obado 2992
    var coords = coordsChar(cm, x, y), line;
15152 obado 2993
    if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
14283 obado 2994
      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
2995
      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
2996
    }
2997
    return coords
2998
  }
2999
 
3000
  // Find the view element corresponding to a given line. Return null
3001
  // when the line isn't visible.
3002
  function findViewIndex(cm, n) {
3003
    if (n >= cm.display.viewTo) { return null }
3004
    n -= cm.display.viewFrom;
3005
    if (n < 0) { return null }
3006
    var view = cm.display.view;
3007
    for (var i = 0; i < view.length; i++) {
3008
      n -= view[i].size;
3009
      if (n < 0) { return i }
3010
    }
3011
  }
3012
 
3013
  // Updates the display.view data structure for a given change to the
3014
  // document. From and to are in pre-change coordinates. Lendiff is
3015
  // the amount of lines added or subtracted by the change. This is
3016
  // used for changes that span multiple lines, or change the way
3017
  // lines are divided into visual lines. regLineChange (below)
3018
  // registers single-line changes.
3019
  function regChange(cm, from, to, lendiff) {
3020
    if (from == null) { from = cm.doc.first; }
3021
    if (to == null) { to = cm.doc.first + cm.doc.size; }
3022
    if (!lendiff) { lendiff = 0; }
3023
 
3024
    var display = cm.display;
3025
    if (lendiff && to < display.viewTo &&
3026
        (display.updateLineNumbers == null || display.updateLineNumbers > from))
3027
      { display.updateLineNumbers = from; }
3028
 
3029
    cm.curOp.viewChanged = true;
3030
 
3031
    if (from >= display.viewTo) { // Change after
3032
      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3033
        { resetView(cm); }
3034
    } else if (to <= display.viewFrom) { // Change before
3035
      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3036
        resetView(cm);
3037
      } else {
3038
        display.viewFrom += lendiff;
3039
        display.viewTo += lendiff;
3040
      }
3041
    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3042
      resetView(cm);
3043
    } else if (from <= display.viewFrom) { // Top overlap
3044
      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3045
      if (cut) {
3046
        display.view = display.view.slice(cut.index);
3047
        display.viewFrom = cut.lineN;
3048
        display.viewTo += lendiff;
3049
      } else {
3050
        resetView(cm);
3051
      }
3052
    } else if (to >= display.viewTo) { // Bottom overlap
3053
      var cut$1 = viewCuttingPoint(cm, from, from, -1);
3054
      if (cut$1) {
3055
        display.view = display.view.slice(0, cut$1.index);
3056
        display.viewTo = cut$1.lineN;
3057
      } else {
3058
        resetView(cm);
3059
      }
3060
    } else { // Gap in the middle
3061
      var cutTop = viewCuttingPoint(cm, from, from, -1);
3062
      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3063
      if (cutTop && cutBot) {
3064
        display.view = display.view.slice(0, cutTop.index)
3065
          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3066
          .concat(display.view.slice(cutBot.index));
3067
        display.viewTo += lendiff;
3068
      } else {
3069
        resetView(cm);
3070
      }
3071
    }
3072
 
3073
    var ext = display.externalMeasured;
3074
    if (ext) {
3075
      if (to < ext.lineN)
3076
        { ext.lineN += lendiff; }
3077
      else if (from < ext.lineN + ext.size)
3078
        { display.externalMeasured = null; }
3079
    }
3080
  }
3081
 
3082
  // Register a change to a single line. Type must be one of "text",
3083
  // "gutter", "class", "widget"
3084
  function regLineChange(cm, line, type) {
3085
    cm.curOp.viewChanged = true;
3086
    var display = cm.display, ext = cm.display.externalMeasured;
3087
    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3088
      { display.externalMeasured = null; }
3089
 
3090
    if (line < display.viewFrom || line >= display.viewTo) { return }
3091
    var lineView = display.view[findViewIndex(cm, line)];
3092
    if (lineView.node == null) { return }
3093
    var arr = lineView.changes || (lineView.changes = []);
3094
    if (indexOf(arr, type) == -1) { arr.push(type); }
3095
  }
3096
 
3097
  // Clear the view.
3098
  function resetView(cm) {
3099
    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3100
    cm.display.view = [];
3101
    cm.display.viewOffset = 0;
3102
  }
3103
 
3104
  function viewCuttingPoint(cm, oldN, newN, dir) {
3105
    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3106
    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3107
      { return {index: index, lineN: newN} }
3108
    var n = cm.display.viewFrom;
3109
    for (var i = 0; i < index; i++)
3110
      { n += view[i].size; }
3111
    if (n != oldN) {
3112
      if (dir > 0) {
3113
        if (index == view.length - 1) { return null }
3114
        diff = (n + view[index].size) - oldN;
3115
        index++;
3116
      } else {
3117
        diff = n - oldN;
3118
      }
3119
      oldN += diff; newN += diff;
3120
    }
3121
    while (visualLineNo(cm.doc, newN) != newN) {
3122
      if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
3123
      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3124
      index += dir;
3125
    }
3126
    return {index: index, lineN: newN}
3127
  }
3128
 
3129
  // Force the view to cover a given range, adding empty view element
3130
  // or clipping off existing ones as needed.
3131
  function adjustView(cm, from, to) {
3132
    var display = cm.display, view = display.view;
3133
    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3134
      display.view = buildViewArray(cm, from, to);
3135
      display.viewFrom = from;
3136
    } else {
3137
      if (display.viewFrom > from)
3138
        { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
3139
      else if (display.viewFrom < from)
3140
        { display.view = display.view.slice(findViewIndex(cm, from)); }
3141
      display.viewFrom = from;
3142
      if (display.viewTo < to)
3143
        { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
3144
      else if (display.viewTo > to)
3145
        { display.view = display.view.slice(0, findViewIndex(cm, to)); }
3146
    }
3147
    display.viewTo = to;
3148
  }
3149
 
3150
  // Count the number of lines in the view whose DOM representation is
3151
  // out of date (or nonexistent).
3152
  function countDirtyView(cm) {
3153
    var view = cm.display.view, dirty = 0;
3154
    for (var i = 0; i < view.length; i++) {
3155
      var lineView = view[i];
3156
      if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
3157
    }
3158
    return dirty
3159
  }
3160
 
3161
  function updateSelection(cm) {
3162
    cm.display.input.showSelection(cm.display.input.prepareSelection());
3163
  }
3164
 
3165
  function prepareSelection(cm, primary) {
3166
    if ( primary === void 0 ) primary = true;
3167
 
3168
    var doc = cm.doc, result = {};
3169
    var curFragment = result.cursors = document.createDocumentFragment();
3170
    var selFragment = result.selection = document.createDocumentFragment();
3171
 
16493 obado 3172
    var customCursor = cm.options.$customCursor;
3173
    if (customCursor) { primary = true; }
14283 obado 3174
    for (var i = 0; i < doc.sel.ranges.length; i++) {
3175
      if (!primary && i == doc.sel.primIndex) { continue }
15152 obado 3176
      var range = doc.sel.ranges[i];
3177
      if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
3178
      var collapsed = range.empty();
16493 obado 3179
      if (customCursor) {
3180
        var head = customCursor(cm, range);
3181
        if (head) { drawSelectionCursor(cm, head, curFragment); }
3182
      } else if (collapsed || cm.options.showCursorWhenSelecting) {
3183
        drawSelectionCursor(cm, range.head, curFragment);
3184
      }
14283 obado 3185
      if (!collapsed)
15152 obado 3186
        { drawSelectionRange(cm, range, selFragment); }
14283 obado 3187
    }
3188
    return result
3189
  }
3190
 
3191
  // Draws a cursor for the given range
3192
  function drawSelectionCursor(cm, head, output) {
3193
    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
3194
 
3195
    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
3196
    cursor.style.left = pos.left + "px";
3197
    cursor.style.top = pos.top + "px";
3198
    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
3199
 
16493 obado 3200
    if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
3201
      var charPos = charCoords(cm, head, "div", null, null);
3202
      var width = charPos.right - charPos.left;
3203
      cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
3204
    }
3205
 
14283 obado 3206
    if (pos.other) {
3207
      // Secondary cursor, shown when on a 'jump' in bi-directional text
3208
      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
3209
      otherCursor.style.display = "";
3210
      otherCursor.style.left = pos.other.left + "px";
3211
      otherCursor.style.top = pos.other.top + "px";
3212
      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
3213
    }
3214
  }
3215
 
3216
  function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3217
 
3218
  // Draws the given range as a highlighted selection
15152 obado 3219
  function drawSelectionRange(cm, range, output) {
14283 obado 3220
    var display = cm.display, doc = cm.doc;
3221
    var fragment = document.createDocumentFragment();
3222
    var padding = paddingH(cm.display), leftSide = padding.left;
3223
    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
3224
    var docLTR = doc.direction == "ltr";
3225
 
3226
    function add(left, top, width, bottom) {
3227
      if (top < 0) { top = 0; }
3228
      top = Math.round(top);
3229
      bottom = Math.round(bottom);
3230
      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")));
3231
    }
3232
 
3233
    function drawForLine(line, fromArg, toArg) {
3234
      var lineObj = getLine(doc, line);
3235
      var lineLen = lineObj.text.length;
3236
      var start, end;
3237
      function coords(ch, bias) {
3238
        return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
3239
      }
3240
 
3241
      function wrapX(pos, dir, side) {
3242
        var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
3243
        var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
3244
        var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
3245
        return coords(ch, prop)[prop]
3246
      }
3247
 
3248
      var order = getOrder(lineObj, doc.direction);
3249
      iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
3250
        var ltr = dir == "ltr";
3251
        var fromPos = coords(from, ltr ? "left" : "right");
3252
        var toPos = coords(to - 1, ltr ? "right" : "left");
3253
 
3254
        var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
3255
        var first = i == 0, last = !order || i == order.length - 1;
3256
        if (toPos.top - fromPos.top <= 3) { // Single line
3257
          var openLeft = (docLTR ? openStart : openEnd) && first;
3258
          var openRight = (docLTR ? openEnd : openStart) && last;
3259
          var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
3260
          var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
3261
          add(left, fromPos.top, right - left, fromPos.bottom);
3262
        } else { // Multiple lines
3263
          var topLeft, topRight, botLeft, botRight;
3264
          if (ltr) {
3265
            topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
3266
            topRight = docLTR ? rightSide : wrapX(from, dir, "before");
3267
            botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
3268
            botRight = docLTR && openEnd && last ? rightSide : toPos.right;
3269
          } else {
3270
            topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
3271
            topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
3272
            botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
3273
            botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
3274
          }
3275
          add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
3276
          if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
3277
          add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
3278
        }
3279
 
3280
        if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
3281
        if (cmpCoords(toPos, start) < 0) { start = toPos; }
3282
        if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
3283
        if (cmpCoords(toPos, end) < 0) { end = toPos; }
3284
      });
3285
      return {start: start, end: end}
3286
    }
3287
 
15152 obado 3288
    var sFrom = range.from(), sTo = range.to();
14283 obado 3289
    if (sFrom.line == sTo.line) {
3290
      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
3291
    } else {
3292
      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3293
      var singleVLine = visualLine(fromLine) == visualLine(toLine);
3294
      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
3295
      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
3296
      if (singleVLine) {
3297
        if (leftEnd.top < rightStart.top - 2) {
3298
          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
3299
          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
3300
        } else {
3301
          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
3302
        }
3303
      }
3304
      if (leftEnd.bottom < rightStart.top)
3305
        { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3306
    }
3307
 
3308
    output.appendChild(fragment);
3309
  }
3310
 
3311
  // Cursor-blinking
3312
  function restartBlink(cm) {
3313
    if (!cm.state.focused) { return }
3314
    var display = cm.display;
3315
    clearInterval(display.blinker);
3316
    var on = true;
3317
    display.cursorDiv.style.visibility = "";
3318
    if (cm.options.cursorBlinkRate > 0)
16493 obado 3319
      { display.blinker = setInterval(function () {
3320
        if (!cm.hasFocus()) { onBlur(cm); }
3321
        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
3322
      }, cm.options.cursorBlinkRate); }
14283 obado 3323
    else if (cm.options.cursorBlinkRate < 0)
3324
      { display.cursorDiv.style.visibility = "hidden"; }
3325
  }
3326
 
3327
  function ensureFocus(cm) {
16493 obado 3328
    if (!cm.hasFocus()) {
3329
      cm.display.input.focus();
3330
      if (!cm.state.focused) { onFocus(cm); }
3331
    }
14283 obado 3332
  }
3333
 
3334
  function delayBlurEvent(cm) {
3335
    cm.state.delayingBlurEvent = true;
3336
    setTimeout(function () { if (cm.state.delayingBlurEvent) {
3337
      cm.state.delayingBlurEvent = false;
16493 obado 3338
      if (cm.state.focused) { onBlur(cm); }
14283 obado 3339
    } }, 100);
3340
  }
3341
 
3342
  function onFocus(cm, e) {
16493 obado 3343
    if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
14283 obado 3344
 
3345
    if (cm.options.readOnly == "nocursor") { return }
3346
    if (!cm.state.focused) {
3347
      signal(cm, "focus", cm, e);
3348
      cm.state.focused = true;
3349
      addClass(cm.display.wrapper, "CodeMirror-focused");
3350
      // This test prevents this from firing when a context
3351
      // menu is closed (since the input reset would kill the
3352
      // select-all detection hack)
3353
      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3354
        cm.display.input.reset();
3355
        if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
3356
      }
3357
      cm.display.input.receivedFocus();
3358
    }
3359
    restartBlink(cm);
3360
  }
3361
  function onBlur(cm, e) {
3362
    if (cm.state.delayingBlurEvent) { return }
3363
 
3364
    if (cm.state.focused) {
3365
      signal(cm, "blur", cm, e);
3366
      cm.state.focused = false;
3367
      rmClass(cm.display.wrapper, "CodeMirror-focused");
3368
    }
3369
    clearInterval(cm.display.blinker);
3370
    setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3371
  }
3372
 
3373
  // Read the actual heights of the rendered lines, and update their
3374
  // stored heights to match.
3375
  function updateHeightsInViewport(cm) {
3376
    var display = cm.display;
3377
    var prevBottom = display.lineDiv.offsetTop;
16493 obado 3378
    var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
3379
    var oldHeight = display.lineDiv.getBoundingClientRect().top;
3380
    var mustScroll = 0;
14283 obado 3381
    for (var i = 0; i < display.view.length; i++) {
3382
      var cur = display.view[i], wrapping = cm.options.lineWrapping;
3383
      var height = (void 0), width = 0;
3384
      if (cur.hidden) { continue }
16493 obado 3385
      oldHeight += cur.line.height;
14283 obado 3386
      if (ie && ie_version < 8) {
3387
        var bot = cur.node.offsetTop + cur.node.offsetHeight;
3388
        height = bot - prevBottom;
3389
        prevBottom = bot;
3390
      } else {
3391
        var box = cur.node.getBoundingClientRect();
3392
        height = box.bottom - box.top;
3393
        // Check that lines don't extend past the right of the current
3394
        // editor width
3395
        if (!wrapping && cur.text.firstChild)
3396
          { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
3397
      }
3398
      var diff = cur.line.height - height;
3399
      if (diff > .005 || diff < -.005) {
16493 obado 3400
        if (oldHeight < viewTop) { mustScroll -= diff; }
14283 obado 3401
        updateLineHeight(cur.line, height);
3402
        updateWidgetHeight(cur.line);
3403
        if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
3404
          { updateWidgetHeight(cur.rest[j]); } }
3405
      }
3406
      if (width > cm.display.sizerWidth) {
3407
        var chWidth = Math.ceil(width / charWidth(cm.display));
3408
        if (chWidth > cm.display.maxLineLength) {
3409
          cm.display.maxLineLength = chWidth;
3410
          cm.display.maxLine = cur.line;
3411
          cm.display.maxLineChanged = true;
3412
        }
3413
      }
3414
    }
16493 obado 3415
    if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
14283 obado 3416
  }
3417
 
3418
  // Read and store the height of line widgets associated with the
3419
  // given line.
3420
  function updateWidgetHeight(line) {
3421
    if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
3422
      var w = line.widgets[i], parent = w.node.parentNode;
3423
      if (parent) { w.height = parent.offsetHeight; }
3424
    } }
3425
  }
3426
 
3427
  // Compute the lines that are visible in a given viewport (defaults
3428
  // the the current scroll position). viewport may contain top,
3429
  // height, and ensure (see op.scrollToPos) properties.
3430
  function visibleLines(display, doc, viewport) {
3431
    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
3432
    top = Math.floor(top - paddingTop(display));
3433
    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
3434
 
3435
    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
3436
    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
3437
    // forces those lines into the viewport (if possible).
3438
    if (viewport && viewport.ensure) {
3439
      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
3440
      if (ensureFrom < from) {
3441
        from = ensureFrom;
3442
        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
3443
      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
3444
        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
3445
        to = ensureTo;
3446
      }
3447
    }
3448
    return {from: from, to: Math.max(to, from + 1)}
3449
  }
3450
 
3451
  // SCROLLING THINGS INTO VIEW
3452
 
3453
  // If an editor sits on the top or bottom of the window, partially
3454
  // scrolled out of view, this ensures that the cursor is visible.
3455
  function maybeScrollWindow(cm, rect) {
3456
    if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
3457
 
3458
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
17702 obado 3459
    var doc = display.wrapper.ownerDocument;
14283 obado 3460
    if (rect.top + box.top < 0) { doScroll = true; }
17702 obado 3461
    else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
14283 obado 3462
    if (doScroll != null && !phantom) {
3463
      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;"));
3464
      cm.display.lineSpace.appendChild(scrollNode);
3465
      scrollNode.scrollIntoView(doScroll);
3466
      cm.display.lineSpace.removeChild(scrollNode);
3467
    }
3468
  }
3469
 
3470
  // Scroll a given position into view (immediately), verifying that
3471
  // it actually became visible (as line heights are accurately
3472
  // measured, the position of something may 'drift' during drawing).
3473
  function scrollPosIntoView(cm, pos, end, margin) {
3474
    if (margin == null) { margin = 0; }
3475
    var rect;
3476
    if (!cm.options.lineWrapping && pos == end) {
3477
      // Set pos and end to the cursor positions around the character pos sticks to
3478
      // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
3479
      // If pos == Pos(_, 0, "before"), pos and end are unchanged
16493 obado 3480
      end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
14283 obado 3481
      pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
3482
    }
3483
    for (var limit = 0; limit < 5; limit++) {
3484
      var changed = false;
3485
      var coords = cursorCoords(cm, pos);
3486
      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3487
      rect = {left: Math.min(coords.left, endCoords.left),
3488
              top: Math.min(coords.top, endCoords.top) - margin,
3489
              right: Math.max(coords.left, endCoords.left),
3490
              bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
3491
      var scrollPos = calculateScrollPos(cm, rect);
3492
      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3493
      if (scrollPos.scrollTop != null) {
3494
        updateScrollTop(cm, scrollPos.scrollTop);
3495
        if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
3496
      }
3497
      if (scrollPos.scrollLeft != null) {
3498
        setScrollLeft(cm, scrollPos.scrollLeft);
3499
        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3500
      }
3501
      if (!changed) { break }
3502
    }
3503
    return rect
3504
  }
3505
 
3506
  // Scroll a given set of coordinates into view (immediately).
3507
  function scrollIntoView(cm, rect) {
3508
    var scrollPos = calculateScrollPos(cm, rect);
3509
    if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
3510
    if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
3511
  }
3512
 
3513
  // Calculate a new scroll position needed to scroll the given
3514
  // rectangle into view. Returns an object with scrollTop and
3515
  // scrollLeft properties. When these are undefined, the
3516
  // vertical/horizontal position does not need to be adjusted.
3517
  function calculateScrollPos(cm, rect) {
3518
    var display = cm.display, snapMargin = textHeight(cm.display);
3519
    if (rect.top < 0) { rect.top = 0; }
3520
    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3521
    var screen = displayHeight(cm), result = {};
3522
    if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
3523
    var docBottom = cm.doc.height + paddingVert(display);
3524
    var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
3525
    if (rect.top < screentop) {
3526
      result.scrollTop = atTop ? 0 : rect.top;
3527
    } else if (rect.bottom > screentop + screen) {
3528
      var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
3529
      if (newTop != screentop) { result.scrollTop = newTop; }
3530
    }
3531
 
16493 obado 3532
    var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
3533
    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
3534
    var screenw = displayWidth(cm) - display.gutters.offsetWidth;
14283 obado 3535
    var tooWide = rect.right - rect.left > screenw;
3536
    if (tooWide) { rect.right = rect.left + screenw; }
3537
    if (rect.left < 10)
3538
      { result.scrollLeft = 0; }
3539
    else if (rect.left < screenleft)
16493 obado 3540
      { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
14283 obado 3541
    else if (rect.right > screenw + screenleft - 3)
3542
      { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
3543
    return result
3544
  }
3545
 
3546
  // Store a relative adjustment to the scroll position in the current
3547
  // operation (to be applied when the operation finishes).
3548
  function addToScrollTop(cm, top) {
3549
    if (top == null) { return }
3550
    resolveScrollToPos(cm);
3551
    cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3552
  }
3553
 
3554
  // Make sure that at the end of the operation the current cursor is
3555
  // shown.
3556
  function ensureCursorVisible(cm) {
3557
    resolveScrollToPos(cm);
3558
    var cur = cm.getCursor();
3559
    cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
3560
  }
3561
 
3562
  function scrollToCoords(cm, x, y) {
3563
    if (x != null || y != null) { resolveScrollToPos(cm); }
3564
    if (x != null) { cm.curOp.scrollLeft = x; }
3565
    if (y != null) { cm.curOp.scrollTop = y; }
3566
  }
3567
 
15152 obado 3568
  function scrollToRange(cm, range) {
14283 obado 3569
    resolveScrollToPos(cm);
15152 obado 3570
    cm.curOp.scrollToPos = range;
14283 obado 3571
  }
3572
 
3573
  // When an operation has its scrollToPos property set, and another
3574
  // scroll action is applied before the end of the operation, this
3575
  // 'simulates' scrolling that position into view in a cheap way, so
3576
  // that the effect of intermediate scroll commands is not ignored.
3577
  function resolveScrollToPos(cm) {
15152 obado 3578
    var range = cm.curOp.scrollToPos;
3579
    if (range) {
14283 obado 3580
      cm.curOp.scrollToPos = null;
15152 obado 3581
      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
3582
      scrollToCoordsRange(cm, from, to, range.margin);
14283 obado 3583
    }
3584
  }
3585
 
3586
  function scrollToCoordsRange(cm, from, to, margin) {
3587
    var sPos = calculateScrollPos(cm, {
3588
      left: Math.min(from.left, to.left),
3589
      top: Math.min(from.top, to.top) - margin,
3590
      right: Math.max(from.right, to.right),
3591
      bottom: Math.max(from.bottom, to.bottom) + margin
3592
    });
3593
    scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
3594
  }
3595
 
3596
  // Sync the scrollable area and scrollbars, ensure the viewport
3597
  // covers the visible area.
3598
  function updateScrollTop(cm, val) {
3599
    if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
3600
    if (!gecko) { updateDisplaySimple(cm, {top: val}); }
3601
    setScrollTop(cm, val, true);
3602
    if (gecko) { updateDisplaySimple(cm); }
3603
    startWorker(cm, 100);
3604
  }
3605
 
3606
  function setScrollTop(cm, val, forceScroll) {
15152 obado 3607
    val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
14283 obado 3608
    if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
3609
    cm.doc.scrollTop = val;
3610
    cm.display.scrollbars.setScrollTop(val);
3611
    if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
3612
  }
3613
 
3614
  // Sync scroller and scrollbar, ensure the gutter elements are
3615
  // aligned.
3616
  function setScrollLeft(cm, val, isScroller, forceScroll) {
15152 obado 3617
    val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
14283 obado 3618
    if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
3619
    cm.doc.scrollLeft = val;
3620
    alignHorizontally(cm);
3621
    if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
3622
    cm.display.scrollbars.setScrollLeft(val);
3623
  }
3624
 
3625
  // SCROLLBARS
3626
 
3627
  // Prepare DOM reads needed to update the scrollbars. Done in one
3628
  // shot to minimize update/measure roundtrips.
3629
  function measureForScrollbars(cm) {
3630
    var d = cm.display, gutterW = d.gutters.offsetWidth;
3631
    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
3632
    return {
3633
      clientHeight: d.scroller.clientHeight,
3634
      viewHeight: d.wrapper.clientHeight,
3635
      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
3636
      viewWidth: d.wrapper.clientWidth,
3637
      barLeft: cm.options.fixedGutter ? gutterW : 0,
3638
      docHeight: docH,
3639
      scrollHeight: docH + scrollGap(cm) + d.barHeight,
3640
      nativeBarWidth: d.nativeBarWidth,
3641
      gutterWidth: gutterW
3642
    }
3643
  }
3644
 
3645
  var NativeScrollbars = function(place, scroll, cm) {
3646
    this.cm = cm;
3647
    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
3648
    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
3649
    vert.tabIndex = horiz.tabIndex = -1;
3650
    place(vert); place(horiz);
3651
 
3652
    on(vert, "scroll", function () {
3653
      if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
3654
    });
3655
    on(horiz, "scroll", function () {
3656
      if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
3657
    });
3658
 
3659
    this.checkedZeroWidth = false;
3660
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
3661
    if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
3662
  };
3663
 
3664
  NativeScrollbars.prototype.update = function (measure) {
3665
    var needsH = measure.scrollWidth > measure.clientWidth + 1;
3666
    var needsV = measure.scrollHeight > measure.clientHeight + 1;
3667
    var sWidth = measure.nativeBarWidth;
3668
 
3669
    if (needsV) {
3670
      this.vert.style.display = "block";
3671
      this.vert.style.bottom = needsH ? sWidth + "px" : "0";
3672
      var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
3673
      // A bug in IE8 can cause this value to be negative, so guard it.
3674
      this.vert.firstChild.style.height =
3675
        Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
3676
    } else {
16493 obado 3677
      this.vert.scrollTop = 0;
14283 obado 3678
      this.vert.style.display = "";
3679
      this.vert.firstChild.style.height = "0";
3680
    }
3681
 
3682
    if (needsH) {
3683
      this.horiz.style.display = "block";
3684
      this.horiz.style.right = needsV ? sWidth + "px" : "0";
3685
      this.horiz.style.left = measure.barLeft + "px";
3686
      var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
3687
      this.horiz.firstChild.style.width =
3688
        Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
3689
    } else {
3690
      this.horiz.style.display = "";
3691
      this.horiz.firstChild.style.width = "0";
3692
    }
3693
 
3694
    if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3695
      if (sWidth == 0) { this.zeroWidthHack(); }
3696
      this.checkedZeroWidth = true;
3697
    }
3698
 
3699
    return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3700
  };
3701
 
3702
  NativeScrollbars.prototype.setScrollLeft = function (pos) {
3703
    if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
3704
    if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
3705
  };
3706
 
3707
  NativeScrollbars.prototype.setScrollTop = function (pos) {
3708
    if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
3709
    if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
3710
  };
3711
 
3712
  NativeScrollbars.prototype.zeroWidthHack = function () {
3713
    var w = mac && !mac_geMountainLion ? "12px" : "18px";
3714
    this.horiz.style.height = this.vert.style.width = w;
16859 obado 3715
    this.horiz.style.visibility = this.vert.style.visibility = "hidden";
14283 obado 3716
    this.disableHoriz = new Delayed;
3717
    this.disableVert = new Delayed;
3718
  };
3719
 
3720
  NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
16859 obado 3721
    bar.style.visibility = "";
14283 obado 3722
    function maybeDisable() {
3723
      // To find out whether the scrollbar is still visible, we
3724
      // check whether the element under the pixel in the bottom
3725
      // right corner of the scrollbar box is the scrollbar box
3726
      // itself (when the bar is still visible) or its filler child
3727
      // (when the bar is hidden). If it is still visible, we keep
3728
      // it enabled, if it's hidden, we disable pointer events.
3729
      var box = bar.getBoundingClientRect();
15152 obado 3730
      var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
14283 obado 3731
          : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
16859 obado 3732
      if (elt != bar) { bar.style.visibility = "hidden"; }
14283 obado 3733
      else { delay.set(1000, maybeDisable); }
3734
    }
3735
    delay.set(1000, maybeDisable);
3736
  };
3737
 
3738
  NativeScrollbars.prototype.clear = function () {
3739
    var parent = this.horiz.parentNode;
3740
    parent.removeChild(this.horiz);
3741
    parent.removeChild(this.vert);
3742
  };
3743
 
3744
  var NullScrollbars = function () {};
3745
 
3746
  NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
3747
  NullScrollbars.prototype.setScrollLeft = function () {};
3748
  NullScrollbars.prototype.setScrollTop = function () {};
3749
  NullScrollbars.prototype.clear = function () {};
3750
 
3751
  function updateScrollbars(cm, measure) {
3752
    if (!measure) { measure = measureForScrollbars(cm); }
3753
    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
3754
    updateScrollbarsInner(cm, measure);
3755
    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
3756
      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
3757
        { updateHeightsInViewport(cm); }
3758
      updateScrollbarsInner(cm, measureForScrollbars(cm));
3759
      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
3760
    }
3761
  }
3762
 
3763
  // Re-synchronize the fake scrollbars with the actual size of the
3764
  // content.
3765
  function updateScrollbarsInner(cm, measure) {
3766
    var d = cm.display;
3767
    var sizes = d.scrollbars.update(measure);
3768
 
3769
    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
3770
    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
3771
    d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
3772
 
3773
    if (sizes.right && sizes.bottom) {
3774
      d.scrollbarFiller.style.display = "block";
3775
      d.scrollbarFiller.style.height = sizes.bottom + "px";
3776
      d.scrollbarFiller.style.width = sizes.right + "px";
3777
    } else { d.scrollbarFiller.style.display = ""; }
3778
    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
3779
      d.gutterFiller.style.display = "block";
3780
      d.gutterFiller.style.height = sizes.bottom + "px";
3781
      d.gutterFiller.style.width = measure.gutterWidth + "px";
3782
    } else { d.gutterFiller.style.display = ""; }
3783
  }
3784
 
3785
  var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3786
 
3787
  function initScrollbars(cm) {
3788
    if (cm.display.scrollbars) {
3789
      cm.display.scrollbars.clear();
3790
      if (cm.display.scrollbars.addClass)
3791
        { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3792
    }
3793
 
3794
    cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
3795
      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
3796
      // Prevent clicks in the scrollbars from killing focus
3797
      on(node, "mousedown", function () {
3798
        if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
3799
      });
3800
      node.setAttribute("cm-not-content", "true");
3801
    }, function (pos, axis) {
3802
      if (axis == "horizontal") { setScrollLeft(cm, pos); }
3803
      else { updateScrollTop(cm, pos); }
3804
    }, cm);
3805
    if (cm.display.scrollbars.addClass)
3806
      { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3807
  }
3808
 
3809
  // Operations are used to wrap a series of changes to the editor
3810
  // state in such a way that each change won't have to update the
3811
  // cursor and display (which would be awkward, slow, and
3812
  // error-prone). Instead, display updates are batched and then all
3813
  // combined and executed at once.
3814
 
3815
  var nextOpId = 0;
3816
  // Start a new operation.
3817
  function startOperation(cm) {
3818
    cm.curOp = {
3819
      cm: cm,
3820
      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
3821
      startHeight: cm.doc.height, // Used to detect need to update scrollbar
3822
      forceUpdate: false,      // Used to force a redraw
3823
      updateInput: 0,       // Whether to reset the input textarea
3824
      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
3825
      changeObjs: null,        // Accumulated changes, for firing change events
3826
      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3827
      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3828
      selectionChanged: false, // Whether the selection needs to be redrawn
3829
      updateMaxLine: false,    // Set when the widest line needs to be determined anew
3830
      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3831
      scrollToPos: null,       // Used to scroll to a specific position
3832
      focus: false,
16493 obado 3833
      id: ++nextOpId,          // Unique ID
3834
      markArrays: null         // Used by addMarkedSpan
14283 obado 3835
    };
3836
    pushOperation(cm.curOp);
3837
  }
3838
 
3839
  // Finish an operation, updating the display and signalling delayed events
3840
  function endOperation(cm) {
3841
    var op = cm.curOp;
3842
    if (op) { finishOperation(op, function (group) {
3843
      for (var i = 0; i < group.ops.length; i++)
3844
        { group.ops[i].cm.curOp = null; }
3845
      endOperations(group);
3846
    }); }
3847
  }
3848
 
3849
  // The DOM updates done when an operation finishes are batched so
3850
  // that the minimum number of relayouts are required.
3851
  function endOperations(group) {
3852
    var ops = group.ops;
3853
    for (var i = 0; i < ops.length; i++) // Read DOM
3854
      { endOperation_R1(ops[i]); }
3855
    for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
3856
      { endOperation_W1(ops[i$1]); }
3857
    for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
3858
      { endOperation_R2(ops[i$2]); }
3859
    for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
3860
      { endOperation_W2(ops[i$3]); }
3861
    for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
3862
      { endOperation_finish(ops[i$4]); }
3863
  }
3864
 
3865
  function endOperation_R1(op) {
3866
    var cm = op.cm, display = cm.display;
3867
    maybeClipScrollbars(cm);
3868
    if (op.updateMaxLine) { findMaxLine(cm); }
3869
 
3870
    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3871
      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3872
                         op.scrollToPos.to.line >= display.viewTo) ||
3873
      display.maxLineChanged && cm.options.lineWrapping;
3874
    op.update = op.mustUpdate &&
3875
      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3876
  }
3877
 
3878
  function endOperation_W1(op) {
3879
    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3880
  }
3881
 
3882
  function endOperation_R2(op) {
3883
    var cm = op.cm, display = cm.display;
3884
    if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3885
 
3886
    op.barMeasure = measureForScrollbars(cm);
3887
 
3888
    // If the max line changed since it was last measured, measure it,
3889
    // and ensure the document's width matches it.
3890
    // updateDisplay_W2 will use these properties to do the actual resizing
3891
    if (display.maxLineChanged && !cm.options.lineWrapping) {
3892
      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3893
      cm.display.sizerWidth = op.adjustWidthTo;
3894
      op.barMeasure.scrollWidth =
3895
        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3896
      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3897
    }
3898
 
3899
    if (op.updatedDisplay || op.selectionChanged)
3900
      { op.preparedSelection = display.input.prepareSelection(); }
3901
  }
3902
 
3903
  function endOperation_W2(op) {
3904
    var cm = op.cm;
3905
 
3906
    if (op.adjustWidthTo != null) {
3907
      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3908
      if (op.maxScrollLeft < cm.doc.scrollLeft)
3909
        { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
3910
      cm.display.maxLineChanged = false;
3911
    }
3912
 
18249 obado 3913
    var takeFocus = op.focus && op.focus == activeElt(root(cm));
14283 obado 3914
    if (op.preparedSelection)
3915
      { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
3916
    if (op.updatedDisplay || op.startHeight != cm.doc.height)
3917
      { updateScrollbars(cm, op.barMeasure); }
3918
    if (op.updatedDisplay)
3919
      { setDocumentHeight(cm, op.barMeasure); }
3920
 
3921
    if (op.selectionChanged) { restartBlink(cm); }
3922
 
3923
    if (cm.state.focused && op.updateInput)
3924
      { cm.display.input.reset(op.typing); }
3925
    if (takeFocus) { ensureFocus(op.cm); }
3926
  }
3927
 
3928
  function endOperation_finish(op) {
3929
    var cm = op.cm, display = cm.display, doc = cm.doc;
3930
 
3931
    if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3932
 
3933
    // Abort mouse wheel delta measurement, when scrolling explicitly
3934
    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3935
      { display.wheelStartX = display.wheelStartY = null; }
3936
 
3937
    // Propagate the scroll position to the actual DOM scroller
3938
    if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
3939
 
3940
    if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
3941
    // If we need to scroll a specific position into view, do so.
3942
    if (op.scrollToPos) {
3943
      var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3944
                                   clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3945
      maybeScrollWindow(cm, rect);
3946
    }
3947
 
3948
    // Fire events for markers that are hidden/unidden by editing or
3949
    // undoing
3950
    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3951
    if (hidden) { for (var i = 0; i < hidden.length; ++i)
3952
      { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
3953
    if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
3954
      { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
3955
 
3956
    if (display.wrapper.offsetHeight)
3957
      { doc.scrollTop = cm.display.scroller.scrollTop; }
3958
 
3959
    // Fire change events, and delayed event handlers
3960
    if (op.changeObjs)
3961
      { signal(cm, "changes", cm, op.changeObjs); }
3962
    if (op.update)
3963
      { op.update.finish(); }
3964
  }
3965
 
3966
  // Run the given function in an operation
3967
  function runInOp(cm, f) {
3968
    if (cm.curOp) { return f() }
3969
    startOperation(cm);
3970
    try { return f() }
3971
    finally { endOperation(cm); }
3972
  }
3973
  // Wraps a function in an operation. Returns the wrapped function.
3974
  function operation(cm, f) {
3975
    return function() {
3976
      if (cm.curOp) { return f.apply(cm, arguments) }
3977
      startOperation(cm);
3978
      try { return f.apply(cm, arguments) }
3979
      finally { endOperation(cm); }
3980
    }
3981
  }
3982
  // Used to add methods to editor and doc instances, wrapping them in
3983
  // operations.
3984
  function methodOp(f) {
3985
    return function() {
3986
      if (this.curOp) { return f.apply(this, arguments) }
3987
      startOperation(this);
3988
      try { return f.apply(this, arguments) }
3989
      finally { endOperation(this); }
3990
    }
3991
  }
3992
  function docMethodOp(f) {
3993
    return function() {
3994
      var cm = this.cm;
3995
      if (!cm || cm.curOp) { return f.apply(this, arguments) }
3996
      startOperation(cm);
3997
      try { return f.apply(this, arguments) }
3998
      finally { endOperation(cm); }
3999
    }
4000
  }
4001
 
4002
  // HIGHLIGHT WORKER
4003
 
4004
  function startWorker(cm, time) {
4005
    if (cm.doc.highlightFrontier < cm.display.viewTo)
4006
      { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
4007
  }
4008
 
4009
  function highlightWorker(cm) {
4010
    var doc = cm.doc;
4011
    if (doc.highlightFrontier >= cm.display.viewTo) { return }
4012
    var end = +new Date + cm.options.workTime;
4013
    var context = getContextBefore(cm, doc.highlightFrontier);
4014
    var changedLines = [];
4015
 
4016
    doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
4017
      if (context.line >= cm.display.viewFrom) { // Visible
4018
        var oldStyles = line.styles;
4019
        var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
4020
        var highlighted = highlightLine(cm, line, context, true);
4021
        if (resetState) { context.state = resetState; }
4022
        line.styles = highlighted.styles;
4023
        var oldCls = line.styleClasses, newCls = highlighted.classes;
4024
        if (newCls) { line.styleClasses = newCls; }
4025
        else if (oldCls) { line.styleClasses = null; }
4026
        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
4027
          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
4028
        for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
4029
        if (ischange) { changedLines.push(context.line); }
4030
        line.stateAfter = context.save();
4031
        context.nextLine();
4032
      } else {
4033
        if (line.text.length <= cm.options.maxHighlightLength)
4034
          { processLine(cm, line.text, context); }
4035
        line.stateAfter = context.line % 5 == 0 ? context.save() : null;
4036
        context.nextLine();
4037
      }
4038
      if (+new Date > end) {
4039
        startWorker(cm, cm.options.workDelay);
4040
        return true
4041
      }
4042
    });
4043
    doc.highlightFrontier = context.line;
4044
    doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
4045
    if (changedLines.length) { runInOp(cm, function () {
4046
      for (var i = 0; i < changedLines.length; i++)
4047
        { regLineChange(cm, changedLines[i], "text"); }
4048
    }); }
4049
  }
4050
 
4051
  // DISPLAY DRAWING
4052
 
4053
  var DisplayUpdate = function(cm, viewport, force) {
4054
    var display = cm.display;
4055
 
4056
    this.viewport = viewport;
4057
    // Store some values that we'll need later (but don't want to force a relayout for)
4058
    this.visible = visibleLines(display, cm.doc, viewport);
4059
    this.editorIsHidden = !display.wrapper.offsetWidth;
4060
    this.wrapperHeight = display.wrapper.clientHeight;
4061
    this.wrapperWidth = display.wrapper.clientWidth;
4062
    this.oldDisplayWidth = displayWidth(cm);
4063
    this.force = force;
4064
    this.dims = getDimensions(cm);
4065
    this.events = [];
4066
  };
4067
 
4068
  DisplayUpdate.prototype.signal = function (emitter, type) {
4069
    if (hasHandler(emitter, type))
4070
      { this.events.push(arguments); }
4071
  };
4072
  DisplayUpdate.prototype.finish = function () {
4073
    for (var i = 0; i < this.events.length; i++)
15152 obado 4074
      { signal.apply(null, this.events[i]); }
14283 obado 4075
  };
4076
 
4077
  function maybeClipScrollbars(cm) {
4078
    var display = cm.display;
4079
    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
4080
      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
4081
      display.heightForcer.style.height = scrollGap(cm) + "px";
4082
      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
4083
      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
4084
      display.scrollbarsClipped = true;
4085
    }
4086
  }
4087
 
4088
  function selectionSnapshot(cm) {
4089
    if (cm.hasFocus()) { return null }
18249 obado 4090
    var active = activeElt(root(cm));
14283 obado 4091
    if (!active || !contains(cm.display.lineDiv, active)) { return null }
4092
    var result = {activeElt: active};
4093
    if (window.getSelection) {
17702 obado 4094
      var sel = win(cm).getSelection();
14283 obado 4095
      if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
4096
        result.anchorNode = sel.anchorNode;
4097
        result.anchorOffset = sel.anchorOffset;
4098
        result.focusNode = sel.focusNode;
4099
        result.focusOffset = sel.focusOffset;
4100
      }
4101
    }
4102
    return result
4103
  }
4104
 
4105
  function restoreSelection(snapshot) {
18249 obado 4106
    if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(rootNode(snapshot.activeElt))) { return }
14283 obado 4107
    snapshot.activeElt.focus();
15152 obado 4108
    if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
4109
        snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
17702 obado 4110
      var doc = snapshot.activeElt.ownerDocument;
4111
      var sel = doc.defaultView.getSelection(), range = doc.createRange();
15152 obado 4112
      range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
4113
      range.collapse(false);
14283 obado 4114
      sel.removeAllRanges();
15152 obado 4115
      sel.addRange(range);
14283 obado 4116
      sel.extend(snapshot.focusNode, snapshot.focusOffset);
4117
    }
4118
  }
4119
 
4120
  // Does the actual updating of the line display. Bails out
4121
  // (returning false) when there is nothing to be done and forced is
4122
  // false.
4123
  function updateDisplayIfNeeded(cm, update) {
4124
    var display = cm.display, doc = cm.doc;
4125
 
4126
    if (update.editorIsHidden) {
4127
      resetView(cm);
4128
      return false
4129
    }
4130
 
4131
    // Bail out if the visible area is already rendered and nothing changed.
4132
    if (!update.force &&
4133
        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
4134
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
4135
        display.renderedView == display.view && countDirtyView(cm) == 0)
4136
      { return false }
4137
 
4138
    if (maybeUpdateLineNumberWidth(cm)) {
4139
      resetView(cm);
4140
      update.dims = getDimensions(cm);
4141
    }
4142
 
4143
    // Compute a suitable new viewport (from & to)
4144
    var end = doc.first + doc.size;
4145
    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
4146
    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
4147
    if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
4148
    if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
4149
    if (sawCollapsedSpans) {
4150
      from = visualLineNo(cm.doc, from);
4151
      to = visualLineEndNo(cm.doc, to);
4152
    }
4153
 
4154
    var different = from != display.viewFrom || to != display.viewTo ||
4155
      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
4156
    adjustView(cm, from, to);
4157
 
4158
    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
4159
    // Position the mover div to align with the current scroll position
4160
    cm.display.mover.style.top = display.viewOffset + "px";
4161
 
4162
    var toUpdate = countDirtyView(cm);
4163
    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
4164
        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
4165
      { return false }
4166
 
4167
    // For big changes, we hide the enclosing element during the
4168
    // update, since that speeds up the operations on most browsers.
4169
    var selSnapshot = selectionSnapshot(cm);
4170
    if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
4171
    patchDisplay(cm, display.updateLineNumbers, update.dims);
4172
    if (toUpdate > 4) { display.lineDiv.style.display = ""; }
4173
    display.renderedView = display.view;
4174
    // There might have been a widget with a focused element that got
4175
    // hidden or updated, if so re-focus it.
4176
    restoreSelection(selSnapshot);
4177
 
4178
    // Prevent selection and cursors from interfering with the scroll
4179
    // width and height.
4180
    removeChildren(display.cursorDiv);
4181
    removeChildren(display.selectionDiv);
4182
    display.gutters.style.height = display.sizer.style.minHeight = 0;
4183
 
4184
    if (different) {
4185
      display.lastWrapHeight = update.wrapperHeight;
4186
      display.lastWrapWidth = update.wrapperWidth;
4187
      startWorker(cm, 400);
4188
    }
4189
 
4190
    display.updateLineNumbers = null;
4191
 
4192
    return true
4193
  }
4194
 
4195
  function postUpdateDisplay(cm, update) {
4196
    var viewport = update.viewport;
4197
 
4198
    for (var first = true;; first = false) {
4199
      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
4200
        // Clip forced viewport to actual scrollable area.
4201
        if (viewport && viewport.top != null)
4202
          { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
4203
        // Updated line heights might result in the drawn area not
4204
        // actually covering the viewport. Keep looping until it does.
4205
        update.visible = visibleLines(cm.display, cm.doc, viewport);
4206
        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
4207
          { break }
15152 obado 4208
      } else if (first) {
4209
        update.visible = visibleLines(cm.display, cm.doc, viewport);
14283 obado 4210
      }
4211
      if (!updateDisplayIfNeeded(cm, update)) { break }
4212
      updateHeightsInViewport(cm);
4213
      var barMeasure = measureForScrollbars(cm);
4214
      updateSelection(cm);
4215
      updateScrollbars(cm, barMeasure);
4216
      setDocumentHeight(cm, barMeasure);
4217
      update.force = false;
4218
    }
4219
 
4220
    update.signal(cm, "update", cm);
4221
    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
4222
      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
4223
      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
4224
    }
4225
  }
4226
 
4227
  function updateDisplaySimple(cm, viewport) {
4228
    var update = new DisplayUpdate(cm, viewport);
4229
    if (updateDisplayIfNeeded(cm, update)) {
4230
      updateHeightsInViewport(cm);
4231
      postUpdateDisplay(cm, update);
4232
      var barMeasure = measureForScrollbars(cm);
4233
      updateSelection(cm);
4234
      updateScrollbars(cm, barMeasure);
4235
      setDocumentHeight(cm, barMeasure);
4236
      update.finish();
4237
    }
4238
  }
4239
 
4240
  // Sync the actual display DOM structure with display.view, removing
4241
  // nodes for lines that are no longer in view, and creating the ones
4242
  // that are not there yet, and updating the ones that are out of
4243
  // date.
4244
  function patchDisplay(cm, updateNumbersFrom, dims) {
4245
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
4246
    var container = display.lineDiv, cur = container.firstChild;
4247
 
4248
    function rm(node) {
4249
      var next = node.nextSibling;
4250
      // Works around a throw-scroll bug in OS X Webkit
4251
      if (webkit && mac && cm.display.currentWheelTarget == node)
4252
        { node.style.display = "none"; }
4253
      else
4254
        { node.parentNode.removeChild(node); }
4255
      return next
4256
    }
4257
 
4258
    var view = display.view, lineN = display.viewFrom;
4259
    // Loop over the elements in the view, syncing cur (the DOM nodes
4260
    // in display.lineDiv) with the view as we go.
4261
    for (var i = 0; i < view.length; i++) {
4262
      var lineView = view[i];
4263
      if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
4264
        var node = buildLineElement(cm, lineView, lineN, dims);
4265
        container.insertBefore(node, cur);
4266
      } else { // Already drawn
4267
        while (cur != lineView.node) { cur = rm(cur); }
4268
        var updateNumber = lineNumbers && updateNumbersFrom != null &&
4269
          updateNumbersFrom <= lineN && lineView.lineNumber;
4270
        if (lineView.changes) {
4271
          if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
4272
          updateLineForChanges(cm, lineView, lineN, dims);
4273
        }
4274
        if (updateNumber) {
4275
          removeChildren(lineView.lineNumber);
4276
          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4277
        }
4278
        cur = lineView.node.nextSibling;
4279
      }
4280
      lineN += lineView.size;
4281
    }
4282
    while (cur) { cur = rm(cur); }
4283
  }
4284
 
4285
  function updateGutterSpace(display) {
4286
    var width = display.gutters.offsetWidth;
4287
    display.sizer.style.marginLeft = width + "px";
16493 obado 4288
    // Send an event to consumers responding to changes in gutter width.
4289
    signalLater(display, "gutterChanged", display);
14283 obado 4290
  }
4291
 
4292
  function setDocumentHeight(cm, measure) {
4293
    cm.display.sizer.style.minHeight = measure.docHeight + "px";
4294
    cm.display.heightForcer.style.top = measure.docHeight + "px";
4295
    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
4296
  }
4297
 
4298
  // Re-align line numbers and gutter marks to compensate for
4299
  // horizontal scrolling.
4300
  function alignHorizontally(cm) {
4301
    var display = cm.display, view = display.view;
4302
    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
4303
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
4304
    var gutterW = display.gutters.offsetWidth, left = comp + "px";
4305
    for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
4306
      if (cm.options.fixedGutter) {
4307
        if (view[i].gutter)
4308
          { view[i].gutter.style.left = left; }
4309
        if (view[i].gutterBackground)
4310
          { view[i].gutterBackground.style.left = left; }
4311
      }
4312
      var align = view[i].alignable;
4313
      if (align) { for (var j = 0; j < align.length; j++)
4314
        { align[j].style.left = left; } }
4315
    } }
4316
    if (cm.options.fixedGutter)
4317
      { display.gutters.style.left = (comp + gutterW) + "px"; }
4318
  }
4319
 
4320
  // Used to ensure that the line number gutter is still the right
4321
  // size for the current document size. Returns true when an update
4322
  // is needed.
4323
  function maybeUpdateLineNumberWidth(cm) {
4324
    if (!cm.options.lineNumbers) { return false }
4325
    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
4326
    if (last.length != display.lineNumChars) {
4327
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
4328
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
4329
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
4330
      display.lineGutter.style.width = "";
4331
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
4332
      display.lineNumWidth = display.lineNumInnerWidth + padding;
4333
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
4334
      display.lineGutter.style.width = display.lineNumWidth + "px";
4335
      updateGutterSpace(cm.display);
4336
      return true
4337
    }
4338
    return false
4339
  }
4340
 
4341
  function getGutters(gutters, lineNumbers) {
4342
    var result = [], sawLineNumbers = false;
4343
    for (var i = 0; i < gutters.length; i++) {
4344
      var name = gutters[i], style = null;
4345
      if (typeof name != "string") { style = name.style; name = name.className; }
4346
      if (name == "CodeMirror-linenumbers") {
4347
        if (!lineNumbers) { continue }
4348
        else { sawLineNumbers = true; }
4349
      }
4350
      result.push({className: name, style: style});
4351
    }
4352
    if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
4353
    return result
4354
  }
4355
 
4356
  // Rebuild the gutter elements, ensure the margin to the left of the
4357
  // code matches their width.
4358
  function renderGutters(display) {
4359
    var gutters = display.gutters, specs = display.gutterSpecs;
4360
    removeChildren(gutters);
4361
    display.lineGutter = null;
4362
    for (var i = 0; i < specs.length; ++i) {
4363
      var ref = specs[i];
4364
      var className = ref.className;
4365
      var style = ref.style;
4366
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
4367
      if (style) { gElt.style.cssText = style; }
4368
      if (className == "CodeMirror-linenumbers") {
4369
        display.lineGutter = gElt;
4370
        gElt.style.width = (display.lineNumWidth || 1) + "px";
4371
      }
4372
    }
4373
    gutters.style.display = specs.length ? "" : "none";
4374
    updateGutterSpace(display);
4375
  }
4376
 
4377
  function updateGutters(cm) {
4378
    renderGutters(cm.display);
4379
    regChange(cm);
4380
    alignHorizontally(cm);
4381
  }
4382
 
4383
  // The display handles the DOM integration, both for input reading
4384
  // and content drawing. It holds references to DOM nodes and
4385
  // display-related state.
4386
 
4387
  function Display(place, doc, input, options) {
4388
    var d = this;
4389
    this.input = input;
4390
 
4391
    // Covers bottom-right square when both scrollbars are present.
4392
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
4393
    d.scrollbarFiller.setAttribute("cm-not-content", "true");
4394
    // Covers bottom of gutter when coverGutterNextToScrollbar is on
4395
    // and h scrollbar is present.
4396
    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
4397
    d.gutterFiller.setAttribute("cm-not-content", "true");
4398
    // Will contain the actual code, positioned to cover the viewport.
4399
    d.lineDiv = eltP("div", null, "CodeMirror-code");
4400
    // Elements are added to these to represent selection and cursors.
4401
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
4402
    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
4403
    // A visibility: hidden element used to find the size of things.
4404
    d.measure = elt("div", null, "CodeMirror-measure");
4405
    // When lines outside of the viewport are measured, they are drawn in this.
4406
    d.lineMeasure = elt("div", null, "CodeMirror-measure");
4407
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
4408
    d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
4409
                      null, "position: relative; outline: none");
4410
    var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
4411
    // Moved around its parent to cover visible view.
4412
    d.mover = elt("div", [lines], null, "position: relative");
4413
    // Set to the height of the document, allowing scrolling.
4414
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
4415
    d.sizerWidth = null;
4416
    // Behavior of elts with overflow: auto and padding is
4417
    // inconsistent across browsers. This is used to ensure the
4418
    // scrollable area is big enough.
4419
    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
4420
    // Will contain the gutters, if any.
4421
    d.gutters = elt("div", null, "CodeMirror-gutters");
4422
    d.lineGutter = null;
4423
    // Actual scrollable element.
4424
    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
4425
    d.scroller.setAttribute("tabIndex", "-1");
4426
    // The element in which the editor lives.
4427
    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
17702 obado 4428
    // See #6982. FIXME remove when this has been fixed for a while in Chrome
4429
    if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }
14283 obado 4430
 
16493 obado 4431
    // This attribute is respected by automatic translation systems such as Google Translate,
4432
    // and may also be respected by tools used by human translators.
4433
    d.wrapper.setAttribute('translate', 'no');
4434
 
14283 obado 4435
    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
4436
    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
4437
    if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
4438
 
4439
    if (place) {
4440
      if (place.appendChild) { place.appendChild(d.wrapper); }
4441
      else { place(d.wrapper); }
4442
    }
4443
 
4444
    // Current rendered range (may be bigger than the view window).
4445
    d.viewFrom = d.viewTo = doc.first;
4446
    d.reportedViewFrom = d.reportedViewTo = doc.first;
4447
    // Information about the rendered lines.
4448
    d.view = [];
4449
    d.renderedView = null;
4450
    // Holds info about a single rendered line when it was rendered
4451
    // for measurement, while not in view.
4452
    d.externalMeasured = null;
4453
    // Empty space (in pixels) above the view
4454
    d.viewOffset = 0;
4455
    d.lastWrapHeight = d.lastWrapWidth = 0;
4456
    d.updateLineNumbers = null;
4457
 
4458
    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
4459
    d.scrollbarsClipped = false;
4460
 
4461
    // Used to only resize the line number gutter when necessary (when
4462
    // the amount of lines crosses a boundary that makes its width change)
4463
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
4464
    // Set to true when a non-horizontal-scrolling line widget is
4465
    // added. As an optimization, line widget aligning is skipped when
4466
    // this is false.
4467
    d.alignWidgets = false;
4468
 
4469
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
4470
 
4471
    // Tracks the maximum line length so that the horizontal scrollbar
4472
    // can be kept static when scrolling.
4473
    d.maxLine = null;
4474
    d.maxLineLength = 0;
4475
    d.maxLineChanged = false;
4476
 
4477
    // Used for measuring wheel scrolling granularity
4478
    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
4479
 
4480
    // True when shift is held down.
4481
    d.shift = false;
4482
 
4483
    // Used to track whether anything happened since the context menu
4484
    // was opened.
4485
    d.selForContextMenu = null;
4486
 
4487
    d.activeTouch = null;
4488
 
4489
    d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
4490
    renderGutters(d);
4491
 
4492
    input.init(d);
4493
  }
4494
 
4495
  // Since the delta values reported on mouse wheel events are
4496
  // unstandardized between browsers and even browser versions, and
4497
  // generally horribly unpredictable, this code starts by measuring
4498
  // the scroll effect that the first few mouse wheel events have,
4499
  // and, from that, detects the way it can convert deltas to pixel
4500
  // offsets afterwards.
4501
  //
4502
  // The reason we want to know the amount a wheel event will scroll
4503
  // is that it gives us a chance to update the display before the
4504
  // actual scrolling happens, reducing flickering.
4505
 
4506
  var wheelSamples = 0, wheelPixelsPerUnit = null;
4507
  // Fill in a browser-detected starting value on browsers where we
4508
  // know one. These don't have to be accurate -- the result of them
4509
  // being wrong would just be a slight flicker on the first wheel
4510
  // scroll (if it is large enough).
4511
  if (ie) { wheelPixelsPerUnit = -.53; }
4512
  else if (gecko) { wheelPixelsPerUnit = 15; }
4513
  else if (chrome) { wheelPixelsPerUnit = -.7; }
4514
  else if (safari) { wheelPixelsPerUnit = -1/3; }
4515
 
4516
  function wheelEventDelta(e) {
4517
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4518
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
4519
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
4520
    else if (dy == null) { dy = e.wheelDelta; }
4521
    return {x: dx, y: dy}
4522
  }
4523
  function wheelEventPixels(e) {
4524
    var delta = wheelEventDelta(e);
4525
    delta.x *= wheelPixelsPerUnit;
4526
    delta.y *= wheelPixelsPerUnit;
4527
    return delta
4528
  }
4529
 
4530
  function onScrollWheel(cm, e) {
16859 obado 4531
    // On Chrome 102, viewport updates somehow stop wheel-based
4532
    // scrolling. Turning off pointer events during the scroll seems
4533
    // to avoid the issue.
17702 obado 4534
    if (chrome && chrome_version == 102) {
16859 obado 4535
      if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
4536
      else { clearTimeout(cm.display.chromeScrollHack); }
4537
      cm.display.chromeScrollHack = setTimeout(function () {
4538
        cm.display.chromeScrollHack = null;
4539
        cm.display.sizer.style.pointerEvents = "";
4540
      }, 100);
4541
    }
14283 obado 4542
    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
16493 obado 4543
    var pixelsPerUnit = wheelPixelsPerUnit;
4544
    if (e.deltaMode === 0) {
4545
      dx = e.deltaX;
4546
      dy = e.deltaY;
4547
      pixelsPerUnit = 1;
4548
    }
14283 obado 4549
 
4550
    var display = cm.display, scroll = display.scroller;
4551
    // Quit if there's nothing to scroll here
4552
    var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4553
    var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4554
    if (!(dx && canScrollX || dy && canScrollY)) { return }
4555
 
4556
    // Webkit browsers on OS X abort momentum scrolls when the target
4557
    // of the scroll event is removed from the scrollable element.
4558
    // This hack (see related code in patchDisplay) makes sure the
4559
    // element is kept around.
4560
    if (dy && mac && webkit) {
4561
      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4562
        for (var i = 0; i < view.length; i++) {
4563
          if (view[i].node == cur) {
4564
            cm.display.currentWheelTarget = cur;
4565
            break outer
4566
          }
4567
        }
4568
      }
4569
    }
4570
 
4571
    // On some browsers, horizontal scrolling will cause redraws to
4572
    // happen before the gutter has been realigned, causing it to
4573
    // wriggle around in a most unseemly way. When we have an
4574
    // estimated pixels/delta value, we just handle horizontal
4575
    // scrolling entirely here. It'll be slightly off from native, but
4576
    // better than glitching out.
16493 obado 4577
    if (dx && !gecko && !presto && pixelsPerUnit != null) {
14283 obado 4578
      if (dy && canScrollY)
16493 obado 4579
        { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
4580
      setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
14283 obado 4581
      // Only prevent default scrolling if vertical scrolling is
4582
      // actually possible. Otherwise, it causes vertical scroll
4583
      // jitter on OSX trackpads when deltaX is small and deltaY
4584
      // is large (issue #3579)
4585
      if (!dy || (dy && canScrollY))
4586
        { e_preventDefault(e); }
4587
      display.wheelStartX = null; // Abort measurement, if in progress
4588
      return
4589
    }
4590
 
4591
    // 'Project' the visible viewport to cover the area that is being
4592
    // scrolled into view (if we know enough to estimate it).
16493 obado 4593
    if (dy && pixelsPerUnit != null) {
4594
      var pixels = dy * pixelsPerUnit;
14283 obado 4595
      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4596
      if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
4597
      else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
4598
      updateDisplaySimple(cm, {top: top, bottom: bot});
4599
    }
4600
 
16493 obado 4601
    if (wheelSamples < 20 && e.deltaMode !== 0) {
14283 obado 4602
      if (display.wheelStartX == null) {
4603
        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4604
        display.wheelDX = dx; display.wheelDY = dy;
4605
        setTimeout(function () {
4606
          if (display.wheelStartX == null) { return }
4607
          var movedX = scroll.scrollLeft - display.wheelStartX;
4608
          var movedY = scroll.scrollTop - display.wheelStartY;
4609
          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4610
            (movedX && display.wheelDX && movedX / display.wheelDX);
4611
          display.wheelStartX = display.wheelStartY = null;
4612
          if (!sample) { return }
4613
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4614
          ++wheelSamples;
4615
        }, 200);
4616
      } else {
4617
        display.wheelDX += dx; display.wheelDY += dy;
4618
      }
4619
    }
4620
  }
4621
 
4622
  // Selection objects are immutable. A new one is created every time
4623
  // the selection changes. A selection is one or more non-overlapping
4624
  // (and non-touching) ranges, sorted, and an integer that indicates
4625
  // which one is the primary selection (the one that's scrolled into
4626
  // view, that getCursor returns, etc).
4627
  var Selection = function(ranges, primIndex) {
4628
    this.ranges = ranges;
4629
    this.primIndex = primIndex;
4630
  };
4631
 
4632
  Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
4633
 
4634
  Selection.prototype.equals = function (other) {
4635
    if (other == this) { return true }
4636
    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
4637
    for (var i = 0; i < this.ranges.length; i++) {
15152 obado 4638
      var here = this.ranges[i], there = other.ranges[i];
14283 obado 4639
      if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
4640
    }
4641
    return true
4642
  };
4643
 
4644
  Selection.prototype.deepCopy = function () {
4645
    var out = [];
4646
    for (var i = 0; i < this.ranges.length; i++)
15152 obado 4647
      { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
14283 obado 4648
    return new Selection(out, this.primIndex)
4649
  };
4650
 
4651
  Selection.prototype.somethingSelected = function () {
4652
    for (var i = 0; i < this.ranges.length; i++)
15152 obado 4653
      { if (!this.ranges[i].empty()) { return true } }
14283 obado 4654
    return false
4655
  };
4656
 
4657
  Selection.prototype.contains = function (pos, end) {
4658
    if (!end) { end = pos; }
4659
    for (var i = 0; i < this.ranges.length; i++) {
15152 obado 4660
      var range = this.ranges[i];
14283 obado 4661
      if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
4662
        { return i }
4663
    }
4664
    return -1
4665
  };
4666
 
4667
  var Range = function(anchor, head) {
4668
    this.anchor = anchor; this.head = head;
4669
  };
4670
 
4671
  Range.prototype.from = function () { return minPos(this.anchor, this.head) };
4672
  Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
4673
  Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
4674
 
4675
  // Take an unsorted, potentially overlapping set of ranges, and
4676
  // build a selection out of it. 'Consumes' ranges array (modifying
4677
  // it).
4678
  function normalizeSelection(cm, ranges, primIndex) {
4679
    var mayTouch = cm && cm.options.selectionsMayTouch;
4680
    var prim = ranges[primIndex];
4681
    ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
4682
    primIndex = indexOf(ranges, prim);
4683
    for (var i = 1; i < ranges.length; i++) {
4684
      var cur = ranges[i], prev = ranges[i - 1];
4685
      var diff = cmp(prev.to(), cur.from());
4686
      if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
4687
        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
4688
        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
4689
        if (i <= primIndex) { --primIndex; }
4690
        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
4691
      }
4692
    }
4693
    return new Selection(ranges, primIndex)
4694
  }
4695
 
4696
  function simpleSelection(anchor, head) {
4697
    return new Selection([new Range(anchor, head || anchor)], 0)
4698
  }
4699
 
4700
  // Compute the position of the end of a change (its 'to' property
4701
  // refers to the pre-change end).
4702
  function changeEnd(change) {
4703
    if (!change.text) { return change.to }
4704
    return Pos(change.from.line + change.text.length - 1,
4705
               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
4706
  }
4707
 
4708
  // Adjust a position to refer to the post-change position of the
4709
  // same text, or the end of the change if the change covers it.
4710
  function adjustForChange(pos, change) {
4711
    if (cmp(pos, change.from) < 0) { return pos }
4712
    if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
4713
 
4714
    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4715
    if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
4716
    return Pos(line, ch)
4717
  }
4718
 
4719
  function computeSelAfterChange(doc, change) {
4720
    var out = [];
4721
    for (var i = 0; i < doc.sel.ranges.length; i++) {
4722
      var range = doc.sel.ranges[i];
4723
      out.push(new Range(adjustForChange(range.anchor, change),
4724
                         adjustForChange(range.head, change)));
4725
    }
4726
    return normalizeSelection(doc.cm, out, doc.sel.primIndex)
4727
  }
4728
 
4729
  function offsetPos(pos, old, nw) {
4730
    if (pos.line == old.line)
4731
      { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
4732
    else
4733
      { return Pos(nw.line + (pos.line - old.line), pos.ch) }
4734
  }
4735
 
4736
  // Used by replaceSelections to allow moving the selection to the
4737
  // start or around the replaced test. Hint may be "start" or "around".
4738
  function computeReplacedSel(doc, changes, hint) {
4739
    var out = [];
4740
    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4741
    for (var i = 0; i < changes.length; i++) {
4742
      var change = changes[i];
4743
      var from = offsetPos(change.from, oldPrev, newPrev);
4744
      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4745
      oldPrev = change.to;
4746
      newPrev = to;
4747
      if (hint == "around") {
4748
        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4749
        out[i] = new Range(inv ? to : from, inv ? from : to);
4750
      } else {
4751
        out[i] = new Range(from, from);
4752
      }
4753
    }
4754
    return new Selection(out, doc.sel.primIndex)
4755
  }
4756
 
4757
  // Used to get the editor into a consistent state again when options change.
4758
 
4759
  function loadMode(cm) {
4760
    cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4761
    resetModeState(cm);
4762
  }
4763
 
4764
  function resetModeState(cm) {
4765
    cm.doc.iter(function (line) {
4766
      if (line.stateAfter) { line.stateAfter = null; }
4767
      if (line.styles) { line.styles = null; }
4768
    });
4769
    cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
4770
    startWorker(cm, 100);
4771
    cm.state.modeGen++;
4772
    if (cm.curOp) { regChange(cm); }
4773
  }
4774
 
4775
  // DOCUMENT DATA STRUCTURE
4776
 
4777
  // By default, updates that start and end at the beginning of a line
4778
  // are treated specially, in order to make the association of line
4779
  // widgets and marker elements with the text behave more intuitive.
4780
  function isWholeLineUpdate(doc, change) {
4781
    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
4782
      (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
4783
  }
4784
 
4785
  // Perform a change on the document data structure.
15152 obado 4786
  function updateDoc(doc, change, markedSpans, estimateHeight) {
14283 obado 4787
    function spansFor(n) {return markedSpans ? markedSpans[n] : null}
4788
    function update(line, text, spans) {
15152 obado 4789
      updateLine(line, text, spans, estimateHeight);
14283 obado 4790
      signalLater(line, "change", line, change);
4791
    }
4792
    function linesFor(start, end) {
4793
      var result = [];
4794
      for (var i = start; i < end; ++i)
15152 obado 4795
        { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
14283 obado 4796
      return result
4797
    }
4798
 
4799
    var from = change.from, to = change.to, text = change.text;
4800
    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4801
    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4802
 
4803
    // Adjust the line structure
4804
    if (change.full) {
4805
      doc.insert(0, linesFor(0, text.length));
4806
      doc.remove(text.length, doc.size - text.length);
4807
    } else if (isWholeLineUpdate(doc, change)) {
4808
      // This is a whole-line replace. Treated specially to make
4809
      // sure line objects move the way they are supposed to.
4810
      var added = linesFor(0, text.length - 1);
4811
      update(lastLine, lastLine.text, lastSpans);
4812
      if (nlines) { doc.remove(from.line, nlines); }
4813
      if (added.length) { doc.insert(from.line, added); }
4814
    } else if (firstLine == lastLine) {
4815
      if (text.length == 1) {
4816
        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4817
      } else {
4818
        var added$1 = linesFor(1, text.length - 1);
15152 obado 4819
        added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
14283 obado 4820
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4821
        doc.insert(from.line + 1, added$1);
4822
      }
4823
    } else if (text.length == 1) {
4824
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4825
      doc.remove(from.line + 1, nlines);
4826
    } else {
4827
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4828
      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4829
      var added$2 = linesFor(1, text.length - 1);
4830
      if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
4831
      doc.insert(from.line + 1, added$2);
4832
    }
4833
 
4834
    signalLater(doc, "change", doc, change);
4835
  }
4836
 
4837
  // Call f for all linked documents.
4838
  function linkedDocs(doc, f, sharedHistOnly) {
4839
    function propagate(doc, skip, sharedHist) {
4840
      if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
4841
        var rel = doc.linked[i];
4842
        if (rel.doc == skip) { continue }
4843
        var shared = sharedHist && rel.sharedHist;
4844
        if (sharedHistOnly && !shared) { continue }
4845
        f(rel.doc, shared);
4846
        propagate(rel.doc, doc, shared);
4847
      } }
4848
    }
4849
    propagate(doc, null, true);
4850
  }
4851
 
4852
  // Attach a document to an editor.
4853
  function attachDoc(cm, doc) {
4854
    if (doc.cm) { throw new Error("This document is already in use.") }
4855
    cm.doc = doc;
4856
    doc.cm = cm;
4857
    estimateLineHeights(cm);
4858
    loadMode(cm);
4859
    setDirectionClass(cm);
16493 obado 4860
    cm.options.direction = doc.direction;
14283 obado 4861
    if (!cm.options.lineWrapping) { findMaxLine(cm); }
4862
    cm.options.mode = doc.modeOption;
4863
    regChange(cm);
4864
  }
4865
 
4866
  function setDirectionClass(cm) {
4867
  (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
4868
  }
4869
 
4870
  function directionChanged(cm) {
4871
    runInOp(cm, function () {
4872
      setDirectionClass(cm);
4873
      regChange(cm);
4874
    });
4875
  }
4876
 
16493 obado 4877
  function History(prev) {
14283 obado 4878
    // Arrays of change events and selections. Doing something adds an
4879
    // event to done and clears undo. Undoing moves events from done
4880
    // to undone, redoing moves them in the other direction.
4881
    this.done = []; this.undone = [];
16493 obado 4882
    this.undoDepth = prev ? prev.undoDepth : Infinity;
14283 obado 4883
    // Used to track when changes can be merged into a single undo
4884
    // event
4885
    this.lastModTime = this.lastSelTime = 0;
4886
    this.lastOp = this.lastSelOp = null;
4887
    this.lastOrigin = this.lastSelOrigin = null;
4888
    // Used by the isClean() method
16493 obado 4889
    this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
14283 obado 4890
  }
4891
 
4892
  // Create a history change event from an updateDoc-style change
4893
  // object.
4894
  function historyChangeFromChange(doc, change) {
4895
    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4896
    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4897
    linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
4898
    return histChange
4899
  }
4900
 
4901
  // Pop all selection events off the end of a history array. Stop at
4902
  // a change event.
4903
  function clearSelectionEvents(array) {
4904
    while (array.length) {
4905
      var last = lst(array);
4906
      if (last.ranges) { array.pop(); }
4907
      else { break }
4908
    }
4909
  }
4910
 
4911
  // Find the top change event in the history. Pop off selection
4912
  // events that are in the way.
4913
  function lastChangeEvent(hist, force) {
4914
    if (force) {
4915
      clearSelectionEvents(hist.done);
4916
      return lst(hist.done)
4917
    } else if (hist.done.length && !lst(hist.done).ranges) {
4918
      return lst(hist.done)
4919
    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
4920
      hist.done.pop();
4921
      return lst(hist.done)
4922
    }
4923
  }
4924
 
4925
  // Register a change in the history. Merges changes that are within
4926
  // a single operation, or are close together with an origin that
4927
  // allows merging (starting with "+") into a single event.
4928
  function addChangeToHistory(doc, change, selAfter, opId) {
4929
    var hist = doc.history;
4930
    hist.undone.length = 0;
4931
    var time = +new Date, cur;
4932
    var last;
4933
 
4934
    if ((hist.lastOp == opId ||
4935
         hist.lastOrigin == change.origin && change.origin &&
4936
         ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
4937
          change.origin.charAt(0) == "*")) &&
4938
        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
4939
      // Merge this change into the last event
4940
      last = lst(cur.changes);
4941
      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
4942
        // Optimized case for simple insertion -- don't want to add
4943
        // new changesets for every character typed
4944
        last.to = changeEnd(change);
4945
      } else {
4946
        // Add new sub-event
4947
        cur.changes.push(historyChangeFromChange(doc, change));
4948
      }
4949
    } else {
4950
      // Can not be merged, start a new event.
4951
      var before = lst(hist.done);
4952
      if (!before || !before.ranges)
4953
        { pushSelectionToHistory(doc.sel, hist.done); }
4954
      cur = {changes: [historyChangeFromChange(doc, change)],
4955
             generation: hist.generation};
4956
      hist.done.push(cur);
4957
      while (hist.done.length > hist.undoDepth) {
4958
        hist.done.shift();
4959
        if (!hist.done[0].ranges) { hist.done.shift(); }
4960
      }
4961
    }
4962
    hist.done.push(selAfter);
4963
    hist.generation = ++hist.maxGeneration;
4964
    hist.lastModTime = hist.lastSelTime = time;
4965
    hist.lastOp = hist.lastSelOp = opId;
4966
    hist.lastOrigin = hist.lastSelOrigin = change.origin;
4967
 
4968
    if (!last) { signal(doc, "historyAdded"); }
4969
  }
4970
 
4971
  function selectionEventCanBeMerged(doc, origin, prev, sel) {
4972
    var ch = origin.charAt(0);
4973
    return ch == "*" ||
4974
      ch == "+" &&
4975
      prev.ranges.length == sel.ranges.length &&
4976
      prev.somethingSelected() == sel.somethingSelected() &&
4977
      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
4978
  }
4979
 
4980
  // Called whenever the selection changes, sets the new selection as
4981
  // the pending selection in the history, and pushes the old pending
4982
  // selection into the 'done' array when it was significantly
4983
  // different (in number of selected ranges, emptiness, or time).
4984
  function addSelectionToHistory(doc, sel, opId, options) {
4985
    var hist = doc.history, origin = options && options.origin;
4986
 
4987
    // A new event is started when the previous origin does not match
4988
    // the current, or the origins don't allow matching. Origins
4989
    // starting with * are always merged, those starting with + are
4990
    // merged when similar and close together in time.
4991
    if (opId == hist.lastSelOp ||
4992
        (origin && hist.lastSelOrigin == origin &&
4993
         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
4994
          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
4995
      { hist.done[hist.done.length - 1] = sel; }
4996
    else
4997
      { pushSelectionToHistory(sel, hist.done); }
4998
 
4999
    hist.lastSelTime = +new Date;
5000
    hist.lastSelOrigin = origin;
5001
    hist.lastSelOp = opId;
5002
    if (options && options.clearRedo !== false)
5003
      { clearSelectionEvents(hist.undone); }
5004
  }
5005
 
5006
  function pushSelectionToHistory(sel, dest) {
5007
    var top = lst(dest);
5008
    if (!(top && top.ranges && top.equals(sel)))
5009
      { dest.push(sel); }
5010
  }
5011
 
5012
  // Used to store marked span information in the history.
5013
  function attachLocalSpans(doc, change, from, to) {
5014
    var existing = change["spans_" + doc.id], n = 0;
5015
    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
5016
      if (line.markedSpans)
5017
        { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
5018
      ++n;
5019
    });
5020
  }
5021
 
5022
  // When un/re-doing restores text containing marked spans, those
5023
  // that have been explicitly cleared should not be restored.
5024
  function removeClearedSpans(spans) {
5025
    if (!spans) { return null }
5026
    var out;
5027
    for (var i = 0; i < spans.length; ++i) {
5028
      if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
5029
      else if (out) { out.push(spans[i]); }
5030
    }
5031
    return !out ? spans : out.length ? out : null
5032
  }
5033
 
5034
  // Retrieve and filter the old marked spans stored in a change event.
5035
  function getOldSpans(doc, change) {
5036
    var found = change["spans_" + doc.id];
5037
    if (!found) { return null }
5038
    var nw = [];
5039
    for (var i = 0; i < change.text.length; ++i)
5040
      { nw.push(removeClearedSpans(found[i])); }
5041
    return nw
5042
  }
5043
 
5044
  // Used for un/re-doing changes from the history. Combines the
5045
  // result of computing the existing spans with the set of spans that
5046
  // existed in the history (so that deleting around a span and then
5047
  // undoing brings back the span).
5048
  function mergeOldSpans(doc, change) {
5049
    var old = getOldSpans(doc, change);
5050
    var stretched = stretchSpansOverChange(doc, change);
5051
    if (!old) { return stretched }
5052
    if (!stretched) { return old }
5053
 
5054
    for (var i = 0; i < old.length; ++i) {
5055
      var oldCur = old[i], stretchCur = stretched[i];
5056
      if (oldCur && stretchCur) {
5057
        spans: for (var j = 0; j < stretchCur.length; ++j) {
5058
          var span = stretchCur[j];
5059
          for (var k = 0; k < oldCur.length; ++k)
5060
            { if (oldCur[k].marker == span.marker) { continue spans } }
5061
          oldCur.push(span);
5062
        }
5063
      } else if (stretchCur) {
5064
        old[i] = stretchCur;
5065
      }
5066
    }
5067
    return old
5068
  }
5069
 
5070
  // Used both to provide a JSON-safe object in .getHistory, and, when
5071
  // detaching a document, to split the history in two
5072
  function copyHistoryArray(events, newGroup, instantiateSel) {
5073
    var copy = [];
5074
    for (var i = 0; i < events.length; ++i) {
5075
      var event = events[i];
5076
      if (event.ranges) {
5077
        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
5078
        continue
5079
      }
5080
      var changes = event.changes, newChanges = [];
5081
      copy.push({changes: newChanges});
5082
      for (var j = 0; j < changes.length; ++j) {
5083
        var change = changes[j], m = (void 0);
5084
        newChanges.push({from: change.from, to: change.to, text: change.text});
5085
        if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
5086
          if (indexOf(newGroup, Number(m[1])) > -1) {
5087
            lst(newChanges)[prop] = change[prop];
5088
            delete change[prop];
5089
          }
5090
        } } }
5091
      }
5092
    }
5093
    return copy
5094
  }
5095
 
5096
  // The 'scroll' parameter given to many of these indicated whether
5097
  // the new cursor position should be scrolled into view after
5098
  // modifying the selection.
5099
 
5100
  // If shift is held or the extend flag is set, extends a range to
5101
  // include a given position (and optionally a second position).
5102
  // Otherwise, simply returns the range between the given positions.
5103
  // Used for cursor motion and such.
5104
  function extendRange(range, head, other, extend) {
5105
    if (extend) {
5106
      var anchor = range.anchor;
5107
      if (other) {
5108
        var posBefore = cmp(head, anchor) < 0;
5109
        if (posBefore != (cmp(other, anchor) < 0)) {
5110
          anchor = head;
5111
          head = other;
5112
        } else if (posBefore != (cmp(head, other) < 0)) {
5113
          head = other;
5114
        }
5115
      }
5116
      return new Range(anchor, head)
5117
    } else {
5118
      return new Range(other || head, head)
5119
    }
5120
  }
5121
 
5122
  // Extend the primary selection range, discard the rest.
5123
  function extendSelection(doc, head, other, options, extend) {
5124
    if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
5125
    setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
5126
  }
5127
 
5128
  // Extend all selections (pos is an array of selections with length
5129
  // equal the number of selections)
5130
  function extendSelections(doc, heads, options) {
5131
    var out = [];
5132
    var extend = doc.cm && (doc.cm.display.shift || doc.extend);
5133
    for (var i = 0; i < doc.sel.ranges.length; i++)
5134
      { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
5135
    var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
5136
    setSelection(doc, newSel, options);
5137
  }
5138
 
5139
  // Updates a single range in the selection.
5140
  function replaceOneSelection(doc, i, range, options) {
5141
    var ranges = doc.sel.ranges.slice(0);
5142
    ranges[i] = range;
5143
    setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
5144
  }
5145
 
5146
  // Reset the selection to a single range.
5147
  function setSimpleSelection(doc, anchor, head, options) {
5148
    setSelection(doc, simpleSelection(anchor, head), options);
5149
  }
5150
 
5151
  // Give beforeSelectionChange handlers a change to influence a
5152
  // selection update.
5153
  function filterSelectionChange(doc, sel, options) {
5154
    var obj = {
5155
      ranges: sel.ranges,
5156
      update: function(ranges) {
5157
        this.ranges = [];
5158
        for (var i = 0; i < ranges.length; i++)
15152 obado 5159
          { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
14283 obado 5160
                                     clipPos(doc, ranges[i].head)); }
5161
      },
5162
      origin: options && options.origin
5163
    };
5164
    signal(doc, "beforeSelectionChange", doc, obj);
5165
    if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
5166
    if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
5167
    else { return sel }
5168
  }
5169
 
5170
  function setSelectionReplaceHistory(doc, sel, options) {
5171
    var done = doc.history.done, last = lst(done);
5172
    if (last && last.ranges) {
5173
      done[done.length - 1] = sel;
5174
      setSelectionNoUndo(doc, sel, options);
5175
    } else {
5176
      setSelection(doc, sel, options);
5177
    }
5178
  }
5179
 
5180
  // Set a new selection.
5181
  function setSelection(doc, sel, options) {
5182
    setSelectionNoUndo(doc, sel, options);
5183
    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
5184
  }
5185
 
5186
  function setSelectionNoUndo(doc, sel, options) {
5187
    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5188
      { sel = filterSelectionChange(doc, sel, options); }
5189
 
5190
    var bias = options && options.bias ||
5191
      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
5192
    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
5193
 
16493 obado 5194
    if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
14283 obado 5195
      { ensureCursorVisible(doc.cm); }
5196
  }
5197
 
5198
  function setSelectionInner(doc, sel) {
5199
    if (sel.equals(doc.sel)) { return }
5200
 
5201
    doc.sel = sel;
5202
 
5203
    if (doc.cm) {
5204
      doc.cm.curOp.updateInput = 1;
5205
      doc.cm.curOp.selectionChanged = true;
5206
      signalCursorActivity(doc.cm);
5207
    }
5208
    signalLater(doc, "cursorActivity", doc);
5209
  }
5210
 
5211
  // Verify that the selection does not partially select any atomic
5212
  // marked ranges.
5213
  function reCheckSelection(doc) {
5214
    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
5215
  }
5216
 
5217
  // Return a selection that does not partially select any atomic
5218
  // ranges.
5219
  function skipAtomicInSelection(doc, sel, bias, mayClear) {
5220
    var out;
5221
    for (var i = 0; i < sel.ranges.length; i++) {
5222
      var range = sel.ranges[i];
5223
      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
5224
      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
16859 obado 5225
      var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
14283 obado 5226
      if (out || newAnchor != range.anchor || newHead != range.head) {
5227
        if (!out) { out = sel.ranges.slice(0, i); }
5228
        out[i] = new Range(newAnchor, newHead);
5229
      }
5230
    }
5231
    return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
5232
  }
5233
 
5234
  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
5235
    var line = getLine(doc, pos.line);
5236
    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
5237
      var sp = line.markedSpans[i], m = sp.marker;
5238
 
5239
      // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
5240
      // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
5241
      // is with selectLeft/Right
5242
      var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
5243
      var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
5244
 
5245
      if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
5246
          (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
5247
        if (mayClear) {
5248
          signal(m, "beforeCursorEnter");
5249
          if (m.explicitlyCleared) {
5250
            if (!line.markedSpans) { break }
5251
            else {--i; continue}
5252
          }
5253
        }
5254
        if (!m.atomic) { continue }
5255
 
5256
        if (oldPos) {
5257
          var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
5258
          if (dir < 0 ? preventCursorRight : preventCursorLeft)
5259
            { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
5260
          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
5261
            { return skipAtomicInner(doc, near, pos, dir, mayClear) }
5262
        }
5263
 
5264
        var far = m.find(dir < 0 ? -1 : 1);
5265
        if (dir < 0 ? preventCursorLeft : preventCursorRight)
5266
          { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
5267
        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
5268
      }
5269
    } }
5270
    return pos
5271
  }
5272
 
5273
  // Ensure a given position is not inside an atomic range.
5274
  function skipAtomic(doc, pos, oldPos, bias, mayClear) {
5275
    var dir = bias || 1;
5276
    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
5277
        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
5278
        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
5279
        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
5280
    if (!found) {
5281
      doc.cantEdit = true;
5282
      return Pos(doc.first, 0)
5283
    }
5284
    return found
5285
  }
5286
 
5287
  function movePos(doc, pos, dir, line) {
5288
    if (dir < 0 && pos.ch == 0) {
5289
      if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
5290
      else { return null }
5291
    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
5292
      if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
5293
      else { return null }
5294
    } else {
5295
      return new Pos(pos.line, pos.ch + dir)
5296
    }
5297
  }
5298
 
5299
  function selectAll(cm) {
5300
    cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
5301
  }
5302
 
5303
  // UPDATING
5304
 
5305
  // Allow "beforeChange" event handlers to influence a change
5306
  function filterChange(doc, change, update) {
5307
    var obj = {
5308
      canceled: false,
5309
      from: change.from,
5310
      to: change.to,
5311
      text: change.text,
5312
      origin: change.origin,
5313
      cancel: function () { return obj.canceled = true; }
5314
    };
5315
    if (update) { obj.update = function (from, to, text, origin) {
5316
      if (from) { obj.from = clipPos(doc, from); }
5317
      if (to) { obj.to = clipPos(doc, to); }
5318
      if (text) { obj.text = text; }
5319
      if (origin !== undefined) { obj.origin = origin; }
5320
    }; }
5321
    signal(doc, "beforeChange", doc, obj);
5322
    if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
5323
 
5324
    if (obj.canceled) {
5325
      if (doc.cm) { doc.cm.curOp.updateInput = 2; }
5326
      return null
5327
    }
5328
    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
5329
  }
5330
 
5331
  // Apply a change to a document, and add it to the document's
5332
  // history, and propagating it to all linked documents.
5333
  function makeChange(doc, change, ignoreReadOnly) {
5334
    if (doc.cm) {
5335
      if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
5336
      if (doc.cm.state.suppressEdits) { return }
5337
    }
5338
 
5339
    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5340
      change = filterChange(doc, change, true);
5341
      if (!change) { return }
5342
    }
5343
 
5344
    // Possibly split or suppress the update based on the presence
5345
    // of read-only spans in its range.
5346
    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
5347
    if (split) {
5348
      for (var i = split.length - 1; i >= 0; --i)
5349
        { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
5350
    } else {
5351
      makeChangeInner(doc, change);
5352
    }
5353
  }
5354
 
5355
  function makeChangeInner(doc, change) {
5356
    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
5357
    var selAfter = computeSelAfterChange(doc, change);
5358
    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
5359
 
5360
    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
5361
    var rebased = [];
5362
 
5363
    linkedDocs(doc, function (doc, sharedHist) {
5364
      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5365
        rebaseHist(doc.history, change);
5366
        rebased.push(doc.history);
5367
      }
5368
      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
5369
    });
5370
  }
5371
 
5372
  // Revert a change stored in a document's history.
5373
  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
5374
    var suppress = doc.cm && doc.cm.state.suppressEdits;
5375
    if (suppress && !allowSelectionOnly) { return }
5376
 
5377
    var hist = doc.history, event, selAfter = doc.sel;
5378
    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
5379
 
5380
    // Verify that there is a useable event (so that ctrl-z won't
5381
    // needlessly clear selection events)
5382
    var i = 0;
5383
    for (; i < source.length; i++) {
5384
      event = source[i];
5385
      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
5386
        { break }
5387
    }
5388
    if (i == source.length) { return }
5389
    hist.lastOrigin = hist.lastSelOrigin = null;
5390
 
5391
    for (;;) {
5392
      event = source.pop();
5393
      if (event.ranges) {
5394
        pushSelectionToHistory(event, dest);
5395
        if (allowSelectionOnly && !event.equals(doc.sel)) {
5396
          setSelection(doc, event, {clearRedo: false});
5397
          return
5398
        }
5399
        selAfter = event;
5400
      } else if (suppress) {
5401
        source.push(event);
5402
        return
5403
      } else { break }
5404
    }
5405
 
5406
    // Build up a reverse change object to add to the opposite history
5407
    // stack (redo when undoing, and vice versa).
5408
    var antiChanges = [];
5409
    pushSelectionToHistory(selAfter, dest);
5410
    dest.push({changes: antiChanges, generation: hist.generation});
5411
    hist.generation = event.generation || ++hist.maxGeneration;
5412
 
5413
    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
5414
 
5415
    var loop = function ( i ) {
5416
      var change = event.changes[i];
5417
      change.origin = type;
5418
      if (filter && !filterChange(doc, change, false)) {
5419
        source.length = 0;
5420
        return {}
5421
      }
5422
 
5423
      antiChanges.push(historyChangeFromChange(doc, change));
5424
 
5425
      var after = i ? computeSelAfterChange(doc, change) : lst(source);
5426
      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
5427
      if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
5428
      var rebased = [];
5429
 
5430
      // Propagate to the linked documents
5431
      linkedDocs(doc, function (doc, sharedHist) {
5432
        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5433
          rebaseHist(doc.history, change);
5434
          rebased.push(doc.history);
5435
        }
5436
        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5437
      });
5438
    };
5439
 
5440
    for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5441
      var returned = loop( i$1 );
5442
 
5443
      if ( returned ) return returned.v;
5444
    }
5445
  }
5446
 
5447
  // Sub-views need their line numbers shifted when text is added
5448
  // above or below them in the parent document.
5449
  function shiftDoc(doc, distance) {
5450
    if (distance == 0) { return }
5451
    doc.first += distance;
5452
    doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
5453
      Pos(range.anchor.line + distance, range.anchor.ch),
5454
      Pos(range.head.line + distance, range.head.ch)
5455
    ); }), doc.sel.primIndex);
5456
    if (doc.cm) {
5457
      regChange(doc.cm, doc.first, doc.first - distance, distance);
5458
      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
5459
        { regLineChange(doc.cm, l, "gutter"); }
5460
    }
5461
  }
5462
 
5463
  // More lower-level change function, handling only a single document
5464
  // (not linked ones).
5465
  function makeChangeSingleDoc(doc, change, selAfter, spans) {
5466
    if (doc.cm && !doc.cm.curOp)
5467
      { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
5468
 
5469
    if (change.to.line < doc.first) {
5470
      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
5471
      return
5472
    }
5473
    if (change.from.line > doc.lastLine()) { return }
5474
 
5475
    // Clip the change to the size of this doc
5476
    if (change.from.line < doc.first) {
5477
      var shift = change.text.length - 1 - (doc.first - change.from.line);
5478
      shiftDoc(doc, shift);
5479
      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
5480
                text: [lst(change.text)], origin: change.origin};
5481
    }
5482
    var last = doc.lastLine();
5483
    if (change.to.line > last) {
5484
      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
5485
                text: [change.text[0]], origin: change.origin};
5486
    }
5487
 
5488
    change.removed = getBetween(doc, change.from, change.to);
5489
 
5490
    if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
5491
    if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
5492
    else { updateDoc(doc, change, spans); }
5493
    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
5494
 
5495
    if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
5496
      { doc.cantEdit = false; }
5497
  }
5498
 
5499
  // Handle the interaction of a change to a document with the editor
5500
  // that this document is part of.
5501
  function makeChangeSingleDocInEditor(cm, change, spans) {
5502
    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
5503
 
5504
    var recomputeMaxLength = false, checkWidthStart = from.line;
5505
    if (!cm.options.lineWrapping) {
5506
      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
5507
      doc.iter(checkWidthStart, to.line + 1, function (line) {
5508
        if (line == display.maxLine) {
5509
          recomputeMaxLength = true;
5510
          return true
5511
        }
5512
      });
5513
    }
5514
 
5515
    if (doc.sel.contains(change.from, change.to) > -1)
5516
      { signalCursorActivity(cm); }
5517
 
5518
    updateDoc(doc, change, spans, estimateHeight(cm));
5519
 
5520
    if (!cm.options.lineWrapping) {
5521
      doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
5522
        var len = lineLength(line);
5523
        if (len > display.maxLineLength) {
5524
          display.maxLine = line;
5525
          display.maxLineLength = len;
5526
          display.maxLineChanged = true;
5527
          recomputeMaxLength = false;
5528
        }
5529
      });
5530
      if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
5531
    }
5532
 
5533
    retreatFrontier(doc, from.line);
5534
    startWorker(cm, 400);
5535
 
5536
    var lendiff = change.text.length - (to.line - from.line) - 1;
5537
    // Remember that these lines changed, for updating the display
5538
    if (change.full)
5539
      { regChange(cm); }
5540
    else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
5541
      { regLineChange(cm, from.line, "text"); }
5542
    else
5543
      { regChange(cm, from.line, to.line + 1, lendiff); }
5544
 
5545
    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
5546
    if (changeHandler || changesHandler) {
5547
      var obj = {
5548
        from: from, to: to,
5549
        text: change.text,
5550
        removed: change.removed,
5551
        origin: change.origin
5552
      };
5553
      if (changeHandler) { signalLater(cm, "change", cm, obj); }
5554
      if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
5555
    }
5556
    cm.display.selForContextMenu = null;
5557
  }
5558
 
5559
  function replaceRange(doc, code, from, to, origin) {
5560
    var assign;
5561
 
5562
    if (!to) { to = from; }
5563
    if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
5564
    if (typeof code == "string") { code = doc.splitLines(code); }
5565
    makeChange(doc, {from: from, to: to, text: code, origin: origin});
5566
  }
5567
 
5568
  // Rebasing/resetting history to deal with externally-sourced changes
5569
 
5570
  function rebaseHistSelSingle(pos, from, to, diff) {
5571
    if (to < pos.line) {
5572
      pos.line += diff;
5573
    } else if (from < pos.line) {
5574
      pos.line = from;
5575
      pos.ch = 0;
5576
    }
5577
  }
5578
 
5579
  // Tries to rebase an array of history events given a change in the
5580
  // document. If the change touches the same lines as the event, the
5581
  // event, and everything 'behind' it, is discarded. If the change is
5582
  // before the event, the event's positions are updated. Uses a
5583
  // copy-on-write scheme for the positions, to avoid having to
5584
  // reallocate them all on every rebase, but also avoid problems with
5585
  // shared position objects being unsafely updated.
5586
  function rebaseHistArray(array, from, to, diff) {
5587
    for (var i = 0; i < array.length; ++i) {
5588
      var sub = array[i], ok = true;
5589
      if (sub.ranges) {
5590
        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
5591
        for (var j = 0; j < sub.ranges.length; j++) {
5592
          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
5593
          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
5594
        }
5595
        continue
5596
      }
5597
      for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
5598
        var cur = sub.changes[j$1];
5599
        if (to < cur.from.line) {
5600
          cur.from = Pos(cur.from.line + diff, cur.from.ch);
5601
          cur.to = Pos(cur.to.line + diff, cur.to.ch);
5602
        } else if (from <= cur.to.line) {
5603
          ok = false;
5604
          break
5605
        }
5606
      }
5607
      if (!ok) {
5608
        array.splice(0, i + 1);
5609
        i = 0;
5610
      }
5611
    }
5612
  }
5613
 
5614
  function rebaseHist(hist, change) {
5615
    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5616
    rebaseHistArray(hist.done, from, to, diff);
5617
    rebaseHistArray(hist.undone, from, to, diff);
5618
  }
5619
 
5620
  // Utility for applying a change to a line by handle or number,
5621
  // returning the number and optionally registering the line as
5622
  // changed.
5623
  function changeLine(doc, handle, changeType, op) {
5624
    var no = handle, line = handle;
5625
    if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
5626
    else { no = lineNo(handle); }
5627
    if (no == null) { return null }
5628
    if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
5629
    return line
5630
  }
5631
 
5632
  // The document is represented as a BTree consisting of leaves, with
5633
  // chunk of lines in them, and branches, with up to ten leaves or
5634
  // other branch nodes below them. The top node is always a branch
5635
  // node, and is the document object itself (meaning it has
5636
  // additional methods and properties).
5637
  //
5638
  // All nodes have parent links. The tree is used both to go from
5639
  // line numbers to line objects, and to go from objects to numbers.
5640
  // It also indexes by height, and is used to convert between height
5641
  // and line object, and to find the total height of the document.
5642
  //
5643
  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
5644
 
5645
  function LeafChunk(lines) {
5646
    this.lines = lines;
5647
    this.parent = null;
5648
    var height = 0;
5649
    for (var i = 0; i < lines.length; ++i) {
15152 obado 5650
      lines[i].parent = this;
14283 obado 5651
      height += lines[i].height;
5652
    }
5653
    this.height = height;
5654
  }
5655
 
5656
  LeafChunk.prototype = {
5657
    chunkSize: function() { return this.lines.length },
5658
 
5659
    // Remove the n lines at offset 'at'.
5660
    removeInner: function(at, n) {
5661
      for (var i = at, e = at + n; i < e; ++i) {
15152 obado 5662
        var line = this.lines[i];
5663
        this.height -= line.height;
14283 obado 5664
        cleanUpLine(line);
5665
        signalLater(line, "delete");
5666
      }
5667
      this.lines.splice(at, n);
5668
    },
5669
 
5670
    // Helper used to collapse a small branch into a single leaf.
5671
    collapse: function(lines) {
5672
      lines.push.apply(lines, this.lines);
5673
    },
5674
 
5675
    // Insert the given array of lines at offset 'at', count them as
5676
    // having the given height.
5677
    insertInner: function(at, lines, height) {
5678
      this.height += height;
5679
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
15152 obado 5680
      for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
14283 obado 5681
    },
5682
 
5683
    // Used to iterate over a part of the tree.
5684
    iterN: function(at, n, op) {
5685
      for (var e = at + n; at < e; ++at)
15152 obado 5686
        { if (op(this.lines[at])) { return true } }
14283 obado 5687
    }
5688
  };
5689
 
5690
  function BranchChunk(children) {
5691
    this.children = children;
5692
    var size = 0, height = 0;
5693
    for (var i = 0; i < children.length; ++i) {
5694
      var ch = children[i];
5695
      size += ch.chunkSize(); height += ch.height;
15152 obado 5696
      ch.parent = this;
14283 obado 5697
    }
5698
    this.size = size;
5699
    this.height = height;
5700
    this.parent = null;
5701
  }
5702
 
5703
  BranchChunk.prototype = {
5704
    chunkSize: function() { return this.size },
5705
 
5706
    removeInner: function(at, n) {
5707
      this.size -= n;
5708
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5709
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5710
        if (at < sz) {
5711
          var rm = Math.min(n, sz - at), oldHeight = child.height;
5712
          child.removeInner(at, rm);
15152 obado 5713
          this.height -= oldHeight - child.height;
5714
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
14283 obado 5715
          if ((n -= rm) == 0) { break }
5716
          at = 0;
5717
        } else { at -= sz; }
5718
      }
5719
      // If the result is smaller than 25 lines, ensure that it is a
5720
      // single leaf node.
5721
      if (this.size - n < 25 &&
5722
          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
5723
        var lines = [];
5724
        this.collapse(lines);
5725
        this.children = [new LeafChunk(lines)];
5726
        this.children[0].parent = this;
5727
      }
5728
    },
5729
 
5730
    collapse: function(lines) {
15152 obado 5731
      for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
14283 obado 5732
    },
5733
 
5734
    insertInner: function(at, lines, height) {
5735
      this.size += lines.length;
5736
      this.height += height;
5737
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5738
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5739
        if (at <= sz) {
5740
          child.insertInner(at, lines, height);
5741
          if (child.lines && child.lines.length > 50) {
5742
            // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
5743
            // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
5744
            var remaining = child.lines.length % 25 + 25;
5745
            for (var pos = remaining; pos < child.lines.length;) {
5746
              var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
5747
              child.height -= leaf.height;
15152 obado 5748
              this.children.splice(++i, 0, leaf);
5749
              leaf.parent = this;
14283 obado 5750
            }
5751
            child.lines = child.lines.slice(0, remaining);
15152 obado 5752
            this.maybeSpill();
14283 obado 5753
          }
5754
          break
5755
        }
5756
        at -= sz;
5757
      }
5758
    },
5759
 
5760
    // When a node has grown, check whether it should be split.
5761
    maybeSpill: function() {
5762
      if (this.children.length <= 10) { return }
5763
      var me = this;
5764
      do {
5765
        var spilled = me.children.splice(me.children.length - 5, 5);
5766
        var sibling = new BranchChunk(spilled);
5767
        if (!me.parent) { // Become the parent node
5768
          var copy = new BranchChunk(me.children);
5769
          copy.parent = me;
5770
          me.children = [copy, sibling];
5771
          me = copy;
5772
       } else {
5773
          me.size -= sibling.size;
5774
          me.height -= sibling.height;
5775
          var myIndex = indexOf(me.parent.children, me);
5776
          me.parent.children.splice(myIndex + 1, 0, sibling);
5777
        }
5778
        sibling.parent = me.parent;
5779
      } while (me.children.length > 10)
5780
      me.parent.maybeSpill();
5781
    },
5782
 
5783
    iterN: function(at, n, op) {
5784
      for (var i = 0; i < this.children.length; ++i) {
15152 obado 5785
        var child = this.children[i], sz = child.chunkSize();
14283 obado 5786
        if (at < sz) {
5787
          var used = Math.min(n, sz - at);
5788
          if (child.iterN(at, used, op)) { return true }
5789
          if ((n -= used) == 0) { break }
5790
          at = 0;
5791
        } else { at -= sz; }
5792
      }
5793
    }
5794
  };
5795
 
5796
  // Line widgets are block elements displayed above or below a line.
5797
 
5798
  var LineWidget = function(doc, node, options) {
5799
    if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
15152 obado 5800
      { this[opt] = options[opt]; } } }
14283 obado 5801
    this.doc = doc;
5802
    this.node = node;
5803
  };
5804
 
5805
  LineWidget.prototype.clear = function () {
5806
    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5807
    if (no == null || !ws) { return }
15152 obado 5808
    for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
14283 obado 5809
    if (!ws.length) { line.widgets = null; }
5810
    var height = widgetHeight(this);
5811
    updateLineHeight(line, Math.max(0, line.height - height));
5812
    if (cm) {
5813
      runInOp(cm, function () {
5814
        adjustScrollWhenAboveVisible(cm, line, -height);
5815
        regLineChange(cm, no, "widget");
5816
      });
5817
      signalLater(cm, "lineWidgetCleared", cm, this, no);
5818
    }
5819
  };
5820
 
5821
  LineWidget.prototype.changed = function () {
5822
      var this$1 = this;
5823
 
5824
    var oldH = this.height, cm = this.doc.cm, line = this.line;
5825
    this.height = null;
5826
    var diff = widgetHeight(this) - oldH;
5827
    if (!diff) { return }
5828
    if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
5829
    if (cm) {
5830
      runInOp(cm, function () {
5831
        cm.curOp.forceUpdate = true;
5832
        adjustScrollWhenAboveVisible(cm, line, diff);
5833
        signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
5834
      });
5835
    }
5836
  };
5837
  eventMixin(LineWidget);
5838
 
5839
  function adjustScrollWhenAboveVisible(cm, line, diff) {
5840
    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5841
      { addToScrollTop(cm, diff); }
5842
  }
5843
 
5844
  function addLineWidget(doc, handle, node, options) {
5845
    var widget = new LineWidget(doc, node, options);
5846
    var cm = doc.cm;
5847
    if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
5848
    changeLine(doc, handle, "widget", function (line) {
5849
      var widgets = line.widgets || (line.widgets = []);
5850
      if (widget.insertAt == null) { widgets.push(widget); }
16493 obado 5851
      else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
14283 obado 5852
      widget.line = line;
5853
      if (cm && !lineIsHidden(doc, line)) {
5854
        var aboveVisible = heightAtLine(line) < doc.scrollTop;
5855
        updateLineHeight(line, line.height + widgetHeight(widget));
5856
        if (aboveVisible) { addToScrollTop(cm, widget.height); }
5857
        cm.curOp.forceUpdate = true;
5858
      }
5859
      return true
5860
    });
5861
    if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
5862
    return widget
5863
  }
5864
 
5865
  // TEXTMARKERS
5866
 
5867
  // Created with markText and setBookmark methods. A TextMarker is a
5868
  // handle that can be used to clear or find a marked position in the
5869
  // document. Line objects hold arrays (markedSpans) containing
5870
  // {from, to, marker} object pointing to such marker objects, and
5871
  // indicating that such a marker is present on that line. Multiple
5872
  // lines may point to the same marker when it spans across lines.
5873
  // The spans will have null for their from/to properties when the
5874
  // marker continues beyond the start/end of the line. Markers have
5875
  // links back to the lines they currently touch.
5876
 
5877
  // Collapsed markers have unique ids, in order to be able to order
5878
  // them, which is needed for uniquely determining an outer marker
5879
  // when they overlap (they may nest, but not partially overlap).
5880
  var nextMarkerId = 0;
5881
 
5882
  var TextMarker = function(doc, type) {
5883
    this.lines = [];
5884
    this.type = type;
5885
    this.doc = doc;
5886
    this.id = ++nextMarkerId;
5887
  };
5888
 
5889
  // Clear the marker.
5890
  TextMarker.prototype.clear = function () {
5891
    if (this.explicitlyCleared) { return }
5892
    var cm = this.doc.cm, withOp = cm && !cm.curOp;
5893
    if (withOp) { startOperation(cm); }
5894
    if (hasHandler(this, "clear")) {
5895
      var found = this.find();
5896
      if (found) { signalLater(this, "clear", found.from, found.to); }
5897
    }
5898
    var min = null, max = null;
5899
    for (var i = 0; i < this.lines.length; ++i) {
15152 obado 5900
      var line = this.lines[i];
5901
      var span = getMarkedSpanFor(line.markedSpans, this);
5902
      if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
14283 obado 5903
      else if (cm) {
5904
        if (span.to != null) { max = lineNo(line); }
5905
        if (span.from != null) { min = lineNo(line); }
5906
      }
5907
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
15152 obado 5908
      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
14283 obado 5909
        { updateLineHeight(line, textHeight(cm.display)); }
5910
    }
5911
    if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
15152 obado 5912
      var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
14283 obado 5913
      if (len > cm.display.maxLineLength) {
5914
        cm.display.maxLine = visual;
5915
        cm.display.maxLineLength = len;
5916
        cm.display.maxLineChanged = true;
5917
      }
5918
    } }
5919
 
5920
    if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
5921
    this.lines.length = 0;
5922
    this.explicitlyCleared = true;
5923
    if (this.atomic && this.doc.cantEdit) {
5924
      this.doc.cantEdit = false;
5925
      if (cm) { reCheckSelection(cm.doc); }
5926
    }
5927
    if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
5928
    if (withOp) { endOperation(cm); }
5929
    if (this.parent) { this.parent.clear(); }
5930
  };
5931
 
5932
  // Find the position of the marker in the document. Returns a {from,
5933
  // to} object by default. Side can be passed to get a specific side
5934
  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5935
  // Pos objects returned contain a line object, rather than a line
5936
  // number (used to prevent looking up the same line twice).
5937
  TextMarker.prototype.find = function (side, lineObj) {
5938
    if (side == null && this.type == "bookmark") { side = 1; }
5939
    var from, to;
5940
    for (var i = 0; i < this.lines.length; ++i) {
15152 obado 5941
      var line = this.lines[i];
5942
      var span = getMarkedSpanFor(line.markedSpans, this);
14283 obado 5943
      if (span.from != null) {
5944
        from = Pos(lineObj ? line : lineNo(line), span.from);
5945
        if (side == -1) { return from }
5946
      }
5947
      if (span.to != null) {
5948
        to = Pos(lineObj ? line : lineNo(line), span.to);
5949
        if (side == 1) { return to }
5950
      }
5951
    }
5952
    return from && {from: from, to: to}
5953
  };
5954
 
5955
  // Signals that the marker's widget changed, and surrounding layout
5956
  // should be recomputed.
5957
  TextMarker.prototype.changed = function () {
5958
      var this$1 = this;
5959
 
5960
    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
5961
    if (!pos || !cm) { return }
5962
    runInOp(cm, function () {
5963
      var line = pos.line, lineN = lineNo(pos.line);
5964
      var view = findViewForLine(cm, lineN);
5965
      if (view) {
5966
        clearLineMeasurementCacheFor(view);
5967
        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
5968
      }
5969
      cm.curOp.updateMaxLine = true;
5970
      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5971
        var oldHeight = widget.height;
5972
        widget.height = null;
5973
        var dHeight = widgetHeight(widget) - oldHeight;
5974
        if (dHeight)
5975
          { updateLineHeight(line, line.height + dHeight); }
5976
      }
5977
      signalLater(cm, "markerChanged", cm, this$1);
5978
    });
5979
  };
5980
 
5981
  TextMarker.prototype.attachLine = function (line) {
5982
    if (!this.lines.length && this.doc.cm) {
5983
      var op = this.doc.cm.curOp;
5984
      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5985
        { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
5986
    }
5987
    this.lines.push(line);
5988
  };
5989
 
5990
  TextMarker.prototype.detachLine = function (line) {
5991
    this.lines.splice(indexOf(this.lines, line), 1);
5992
    if (!this.lines.length && this.doc.cm) {
5993
      var op = this.doc.cm.curOp
5994
      ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5995
    }
5996
  };
5997
  eventMixin(TextMarker);
5998
 
5999
  // Create a marker, wire it up to the right lines, and
6000
  function markText(doc, from, to, options, type) {
6001
    // Shared markers (across linked documents) are handled separately
6002
    // (markTextShared will call out to this again, once per
6003
    // document).
6004
    if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
6005
    // Ensure we are in an operation.
6006
    if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
6007
 
6008
    var marker = new TextMarker(doc, type), diff = cmp(from, to);
6009
    if (options) { copyObj(options, marker, false); }
6010
    // Don't connect empty markers unless clearWhenEmpty is false
6011
    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6012
      { return marker }
6013
    if (marker.replacedWith) {
6014
      // Showing up as a widget implies collapsed (widget replaces text)
6015
      marker.collapsed = true;
6016
      marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
6017
      if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
6018
      if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
6019
    }
6020
    if (marker.collapsed) {
6021
      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6022
          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6023
        { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
6024
      seeCollapsedSpans();
6025
    }
6026
 
6027
    if (marker.addToHistory)
6028
      { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
6029
 
6030
    var curLine = from.line, cm = doc.cm, updateMaxLine;
6031
    doc.iter(curLine, to.line + 1, function (line) {
6032
      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6033
        { updateMaxLine = true; }
6034
      if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
6035
      addMarkedSpan(line, new MarkedSpan(marker,
6036
                                         curLine == from.line ? from.ch : null,
16493 obado 6037
                                         curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
14283 obado 6038
      ++curLine;
6039
    });
6040
    // lineIsHidden depends on the presence of the spans, so needs a second pass
6041
    if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
6042
      if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
6043
    }); }
6044
 
6045
    if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
6046
 
6047
    if (marker.readOnly) {
6048
      seeReadOnlySpans();
6049
      if (doc.history.done.length || doc.history.undone.length)
6050
        { doc.clearHistory(); }
6051
    }
6052
    if (marker.collapsed) {
6053
      marker.id = ++nextMarkerId;
6054
      marker.atomic = true;
6055
    }
6056
    if (cm) {
6057
      // Sync editor state
6058
      if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
6059
      if (marker.collapsed)
6060
        { regChange(cm, from.line, to.line + 1); }
6061
      else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
6062
               marker.attributes || marker.title)
6063
        { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
6064
      if (marker.atomic) { reCheckSelection(cm.doc); }
6065
      signalLater(cm, "markerAdded", cm, marker);
6066
    }
6067
    return marker
6068
  }
6069
 
6070
  // SHARED TEXTMARKERS
6071
 
6072
  // A shared marker spans multiple linked documents. It is
6073
  // implemented as a meta-marker-object controlling multiple normal
6074
  // markers.
6075
  var SharedTextMarker = function(markers, primary) {
6076
    this.markers = markers;
6077
    this.primary = primary;
6078
    for (var i = 0; i < markers.length; ++i)
15152 obado 6079
      { markers[i].parent = this; }
14283 obado 6080
  };
6081
 
6082
  SharedTextMarker.prototype.clear = function () {
6083
    if (this.explicitlyCleared) { return }
6084
    this.explicitlyCleared = true;
6085
    for (var i = 0; i < this.markers.length; ++i)
15152 obado 6086
      { this.markers[i].clear(); }
14283 obado 6087
    signalLater(this, "clear");
6088
  };
6089
 
6090
  SharedTextMarker.prototype.find = function (side, lineObj) {
6091
    return this.primary.find(side, lineObj)
6092
  };
6093
  eventMixin(SharedTextMarker);
6094
 
6095
  function markTextShared(doc, from, to, options, type) {
6096
    options = copyObj(options);
6097
    options.shared = false;
6098
    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6099
    var widget = options.widgetNode;
6100
    linkedDocs(doc, function (doc) {
6101
      if (widget) { options.widgetNode = widget.cloneNode(true); }
6102
      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6103
      for (var i = 0; i < doc.linked.length; ++i)
6104
        { if (doc.linked[i].isParent) { return } }
6105
      primary = lst(markers);
6106
    });
6107
    return new SharedTextMarker(markers, primary)
6108
  }
6109
 
6110
  function findSharedMarkers(doc) {
6111
    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
6112
  }
6113
 
6114
  function copySharedMarkers(doc, markers) {
6115
    for (var i = 0; i < markers.length; i++) {
6116
      var marker = markers[i], pos = marker.find();
6117
      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6118
      if (cmp(mFrom, mTo)) {
6119
        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6120
        marker.markers.push(subMark);
6121
        subMark.parent = marker;
6122
      }
6123
    }
6124
  }
6125
 
6126
  function detachSharedMarkers(markers) {
6127
    var loop = function ( i ) {
6128
      var marker = markers[i], linked = [marker.primary.doc];
6129
      linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
6130
      for (var j = 0; j < marker.markers.length; j++) {
6131
        var subMarker = marker.markers[j];
6132
        if (indexOf(linked, subMarker.doc) == -1) {
6133
          subMarker.parent = null;
6134
          marker.markers.splice(j--, 1);
6135
        }
6136
      }
6137
    };
6138
 
6139
    for (var i = 0; i < markers.length; i++) loop( i );
6140
  }
6141
 
6142
  var nextDocId = 0;
6143
  var Doc = function(text, mode, firstLine, lineSep, direction) {
6144
    if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
6145
    if (firstLine == null) { firstLine = 0; }
6146
 
6147
    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
6148
    this.first = firstLine;
6149
    this.scrollTop = this.scrollLeft = 0;
6150
    this.cantEdit = false;
6151
    this.cleanGeneration = 1;
6152
    this.modeFrontier = this.highlightFrontier = firstLine;
6153
    var start = Pos(firstLine, 0);
6154
    this.sel = simpleSelection(start);
6155
    this.history = new History(null);
6156
    this.id = ++nextDocId;
6157
    this.modeOption = mode;
6158
    this.lineSep = lineSep;
6159
    this.direction = (direction == "rtl") ? "rtl" : "ltr";
6160
    this.extend = false;
6161
 
6162
    if (typeof text == "string") { text = this.splitLines(text); }
6163
    updateDoc(this, {from: start, to: start, text: text});
6164
    setSelection(this, simpleSelection(start), sel_dontScroll);
6165
  };
6166
 
6167
  Doc.prototype = createObj(BranchChunk.prototype, {
6168
    constructor: Doc,
6169
    // Iterate over the document. Supports two forms -- with only one
6170
    // argument, it calls that for each line in the document. With
6171
    // three, it iterates over the range given by the first two (with
6172
    // the second being non-inclusive).
6173
    iter: function(from, to, op) {
6174
      if (op) { this.iterN(from - this.first, to - from, op); }
6175
      else { this.iterN(this.first, this.first + this.size, from); }
6176
    },
6177
 
6178
    // Non-public interface for adding and removing lines.
6179
    insert: function(at, lines) {
6180
      var height = 0;
6181
      for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
6182
      this.insertInner(at - this.first, lines, height);
6183
    },
6184
    remove: function(at, n) { this.removeInner(at - this.first, n); },
6185
 
6186
    // From here, the methods are part of the public interface. Most
6187
    // are also available from CodeMirror (editor) instances.
6188
 
6189
    getValue: function(lineSep) {
6190
      var lines = getLines(this, this.first, this.first + this.size);
6191
      if (lineSep === false) { return lines }
6192
      return lines.join(lineSep || this.lineSeparator())
6193
    },
6194
    setValue: docMethodOp(function(code) {
6195
      var top = Pos(this.first, 0), last = this.first + this.size - 1;
6196
      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6197
                        text: this.splitLines(code), origin: "setValue", full: true}, true);
6198
      if (this.cm) { scrollToCoords(this.cm, 0, 0); }
6199
      setSelection(this, simpleSelection(top), sel_dontScroll);
6200
    }),
6201
    replaceRange: function(code, from, to, origin) {
6202
      from = clipPos(this, from);
6203
      to = to ? clipPos(this, to) : from;
6204
      replaceRange(this, code, from, to, origin);
6205
    },
6206
    getRange: function(from, to, lineSep) {
6207
      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6208
      if (lineSep === false) { return lines }
16493 obado 6209
      if (lineSep === '') { return lines.join('') }
14283 obado 6210
      return lines.join(lineSep || this.lineSeparator())
6211
    },
6212
 
6213
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6214
 
6215
    getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6216
    getLineNumber: function(line) {return lineNo(line)},
6217
 
6218
    getLineHandleVisualStart: function(line) {
6219
      if (typeof line == "number") { line = getLine(this, line); }
6220
      return visualLine(line)
6221
    },
6222
 
6223
    lineCount: function() {return this.size},
6224
    firstLine: function() {return this.first},
6225
    lastLine: function() {return this.first + this.size - 1},
6226
 
6227
    clipPos: function(pos) {return clipPos(this, pos)},
6228
 
6229
    getCursor: function(start) {
15152 obado 6230
      var range = this.sel.primary(), pos;
6231
      if (start == null || start == "head") { pos = range.head; }
6232
      else if (start == "anchor") { pos = range.anchor; }
6233
      else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
6234
      else { pos = range.from(); }
14283 obado 6235
      return pos
6236
    },
6237
    listSelections: function() { return this.sel.ranges },
6238
    somethingSelected: function() {return this.sel.somethingSelected()},
6239
 
6240
    setCursor: docMethodOp(function(line, ch, options) {
6241
      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6242
    }),
6243
    setSelection: docMethodOp(function(anchor, head, options) {
6244
      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6245
    }),
6246
    extendSelection: docMethodOp(function(head, other, options) {
6247
      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6248
    }),
6249
    extendSelections: docMethodOp(function(heads, options) {
6250
      extendSelections(this, clipPosArray(this, heads), options);
6251
    }),
6252
    extendSelectionsBy: docMethodOp(function(f, options) {
6253
      var heads = map(this.sel.ranges, f);
6254
      extendSelections(this, clipPosArray(this, heads), options);
6255
    }),
6256
    setSelections: docMethodOp(function(ranges, primary, options) {
6257
      if (!ranges.length) { return }
6258
      var out = [];
6259
      for (var i = 0; i < ranges.length; i++)
15152 obado 6260
        { out[i] = new Range(clipPos(this, ranges[i].anchor),
16493 obado 6261
                           clipPos(this, ranges[i].head || ranges[i].anchor)); }
14283 obado 6262
      if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
6263
      setSelection(this, normalizeSelection(this.cm, out, primary), options);
6264
    }),
6265
    addSelection: docMethodOp(function(anchor, head, options) {
6266
      var ranges = this.sel.ranges.slice(0);
6267
      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6268
      setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
6269
    }),
6270
 
6271
    getSelection: function(lineSep) {
6272
      var ranges = this.sel.ranges, lines;
6273
      for (var i = 0; i < ranges.length; i++) {
15152 obado 6274
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
14283 obado 6275
        lines = lines ? lines.concat(sel) : sel;
6276
      }
6277
      if (lineSep === false) { return lines }
6278
      else { return lines.join(lineSep || this.lineSeparator()) }
6279
    },
6280
    getSelections: function(lineSep) {
6281
      var parts = [], ranges = this.sel.ranges;
6282
      for (var i = 0; i < ranges.length; i++) {
15152 obado 6283
        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6284
        if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
14283 obado 6285
        parts[i] = sel;
6286
      }
6287
      return parts
6288
    },
6289
    replaceSelection: function(code, collapse, origin) {
6290
      var dup = [];
6291
      for (var i = 0; i < this.sel.ranges.length; i++)
6292
        { dup[i] = code; }
6293
      this.replaceSelections(dup, collapse, origin || "+input");
6294
    },
6295
    replaceSelections: docMethodOp(function(code, collapse, origin) {
6296
      var changes = [], sel = this.sel;
6297
      for (var i = 0; i < sel.ranges.length; i++) {
15152 obado 6298
        var range = sel.ranges[i];
6299
        changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
14283 obado 6300
      }
6301
      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6302
      for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
15152 obado 6303
        { makeChange(this, changes[i$1]); }
14283 obado 6304
      if (newSel) { setSelectionReplaceHistory(this, newSel); }
6305
      else if (this.cm) { ensureCursorVisible(this.cm); }
6306
    }),
6307
    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6308
    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6309
    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6310
    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6311
 
6312
    setExtending: function(val) {this.extend = val;},
6313
    getExtending: function() {return this.extend},
6314
 
6315
    historySize: function() {
6316
      var hist = this.history, done = 0, undone = 0;
6317
      for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
6318
      for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
6319
      return {undo: done, redo: undone}
6320
    },
15152 obado 6321
    clearHistory: function() {
6322
      var this$1 = this;
14283 obado 6323
 
16493 obado 6324
      this.history = new History(this.history);
15152 obado 6325
      linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
6326
    },
6327
 
14283 obado 6328
    markClean: function() {
6329
      this.cleanGeneration = this.changeGeneration(true);
6330
    },
6331
    changeGeneration: function(forceSplit) {
6332
      if (forceSplit)
6333
        { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
6334
      return this.history.generation
6335
    },
6336
    isClean: function (gen) {
6337
      return this.history.generation == (gen || this.cleanGeneration)
6338
    },
6339
 
6340
    getHistory: function() {
6341
      return {done: copyHistoryArray(this.history.done),
6342
              undone: copyHistoryArray(this.history.undone)}
6343
    },
6344
    setHistory: function(histData) {
16493 obado 6345
      var hist = this.history = new History(this.history);
14283 obado 6346
      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6347
      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6348
    },
6349
 
6350
    setGutterMarker: docMethodOp(function(line, gutterID, value) {
6351
      return changeLine(this, line, "gutter", function (line) {
6352
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
6353
        markers[gutterID] = value;
6354
        if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
6355
        return true
6356
      })
6357
    }),
6358
 
6359
    clearGutter: docMethodOp(function(gutterID) {
6360
      var this$1 = this;
6361
 
6362
      this.iter(function (line) {
6363
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
6364
          changeLine(this$1, line, "gutter", function () {
6365
            line.gutterMarkers[gutterID] = null;
6366
            if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
6367
            return true
6368
          });
6369
        }
6370
      });
6371
    }),
6372
 
6373
    lineInfo: function(line) {
6374
      var n;
6375
      if (typeof line == "number") {
6376
        if (!isLine(this, line)) { return null }
6377
        n = line;
6378
        line = getLine(this, line);
6379
        if (!line) { return null }
6380
      } else {
6381
        n = lineNo(line);
6382
        if (n == null) { return null }
6383
      }
6384
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
6385
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
6386
              widgets: line.widgets}
6387
    },
6388
 
6389
    addLineClass: docMethodOp(function(handle, where, cls) {
6390
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6391
        var prop = where == "text" ? "textClass"
6392
                 : where == "background" ? "bgClass"
6393
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6394
        if (!line[prop]) { line[prop] = cls; }
6395
        else if (classTest(cls).test(line[prop])) { return false }
6396
        else { line[prop] += " " + cls; }
6397
        return true
6398
      })
6399
    }),
6400
    removeLineClass: docMethodOp(function(handle, where, cls) {
6401
      return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6402
        var prop = where == "text" ? "textClass"
6403
                 : where == "background" ? "bgClass"
6404
                 : where == "gutter" ? "gutterClass" : "wrapClass";
6405
        var cur = line[prop];
6406
        if (!cur) { return false }
6407
        else if (cls == null) { line[prop] = null; }
6408
        else {
6409
          var found = cur.match(classTest(cls));
6410
          if (!found) { return false }
6411
          var end = found.index + found[0].length;
6412
          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
6413
        }
6414
        return true
6415
      })
6416
    }),
6417
 
6418
    addLineWidget: docMethodOp(function(handle, node, options) {
6419
      return addLineWidget(this, handle, node, options)
6420
    }),
6421
    removeLineWidget: function(widget) { widget.clear(); },
6422
 
6423
    markText: function(from, to, options) {
6424
      return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
6425
    },
6426
    setBookmark: function(pos, options) {
6427
      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6428
                      insertLeft: options && options.insertLeft,
6429
                      clearWhenEmpty: false, shared: options && options.shared,
6430
                      handleMouseEvents: options && options.handleMouseEvents};
6431
      pos = clipPos(this, pos);
6432
      return markText(this, pos, pos, realOpts, "bookmark")
6433
    },
6434
    findMarksAt: function(pos) {
6435
      pos = clipPos(this, pos);
6436
      var markers = [], spans = getLine(this, pos.line).markedSpans;
6437
      if (spans) { for (var i = 0; i < spans.length; ++i) {
6438
        var span = spans[i];
6439
        if ((span.from == null || span.from <= pos.ch) &&
6440
            (span.to == null || span.to >= pos.ch))
6441
          { markers.push(span.marker.parent || span.marker); }
6442
      } }
6443
      return markers
6444
    },
6445
    findMarks: function(from, to, filter) {
6446
      from = clipPos(this, from); to = clipPos(this, to);
15152 obado 6447
      var found = [], lineNo = from.line;
14283 obado 6448
      this.iter(from.line, to.line + 1, function (line) {
6449
        var spans = line.markedSpans;
6450
        if (spans) { for (var i = 0; i < spans.length; i++) {
6451
          var span = spans[i];
15152 obado 6452
          if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
6453
                span.from == null && lineNo != from.line ||
6454
                span.from != null && lineNo == to.line && span.from >= to.ch) &&
14283 obado 6455
              (!filter || filter(span.marker)))
6456
            { found.push(span.marker.parent || span.marker); }
6457
        } }
15152 obado 6458
        ++lineNo;
14283 obado 6459
      });
6460
      return found
6461
    },
6462
    getAllMarks: function() {
6463
      var markers = [];
6464
      this.iter(function (line) {
6465
        var sps = line.markedSpans;
6466
        if (sps) { for (var i = 0; i < sps.length; ++i)
6467
          { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
6468
      });
6469
      return markers
6470
    },
6471
 
6472
    posFromIndex: function(off) {
15152 obado 6473
      var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
14283 obado 6474
      this.iter(function (line) {
6475
        var sz = line.text.length + sepSize;
6476
        if (sz > off) { ch = off; return true }
6477
        off -= sz;
15152 obado 6478
        ++lineNo;
14283 obado 6479
      });
15152 obado 6480
      return clipPos(this, Pos(lineNo, ch))
14283 obado 6481
    },
6482
    indexFromPos: function (coords) {
6483
      coords = clipPos(this, coords);
6484
      var index = coords.ch;
6485
      if (coords.line < this.first || coords.ch < 0) { return 0 }
6486
      var sepSize = this.lineSeparator().length;
6487
      this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
6488
        index += line.text.length + sepSize;
6489
      });
6490
      return index
6491
    },
6492
 
6493
    copy: function(copyHistory) {
6494
      var doc = new Doc(getLines(this, this.first, this.first + this.size),
6495
                        this.modeOption, this.first, this.lineSep, this.direction);
6496
      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6497
      doc.sel = this.sel;
6498
      doc.extend = false;
6499
      if (copyHistory) {
6500
        doc.history.undoDepth = this.history.undoDepth;
6501
        doc.setHistory(this.getHistory());
6502
      }
6503
      return doc
6504
    },
6505
 
6506
    linkedDoc: function(options) {
6507
      if (!options) { options = {}; }
6508
      var from = this.first, to = this.first + this.size;
6509
      if (options.from != null && options.from > from) { from = options.from; }
6510
      if (options.to != null && options.to < to) { to = options.to; }
6511
      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
6512
      if (options.sharedHist) { copy.history = this.history
6513
      ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6514
      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6515
      copySharedMarkers(copy, findSharedMarkers(this));
6516
      return copy
6517
    },
6518
    unlinkDoc: function(other) {
6519
      if (other instanceof CodeMirror) { other = other.doc; }
6520
      if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
15152 obado 6521
        var link = this.linked[i];
14283 obado 6522
        if (link.doc != other) { continue }
15152 obado 6523
        this.linked.splice(i, 1);
6524
        other.unlinkDoc(this);
6525
        detachSharedMarkers(findSharedMarkers(this));
14283 obado 6526
        break
6527
      } }
6528
      // If the histories were shared, split them again
6529
      if (other.history == this.history) {
6530
        var splitIds = [other.id];
6531
        linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
6532
        other.history = new History(null);
6533
        other.history.done = copyHistoryArray(this.history.done, splitIds);
6534
        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6535
      }
6536
    },
6537
    iterLinkedDocs: function(f) {linkedDocs(this, f);},
6538
 
6539
    getMode: function() {return this.mode},
6540
    getEditor: function() {return this.cm},
6541
 
6542
    splitLines: function(str) {
6543
      if (this.lineSep) { return str.split(this.lineSep) }
6544
      return splitLinesAuto(str)
6545
    },
6546
    lineSeparator: function() { return this.lineSep || "\n" },
6547
 
6548
    setDirection: docMethodOp(function (dir) {
6549
      if (dir != "rtl") { dir = "ltr"; }
6550
      if (dir == this.direction) { return }
6551
      this.direction = dir;
6552
      this.iter(function (line) { return line.order = null; });
6553
      if (this.cm) { directionChanged(this.cm); }
6554
    })
6555
  });
6556
 
6557
  // Public alias.
6558
  Doc.prototype.eachLine = Doc.prototype.iter;
6559
 
6560
  // Kludge to work around strange IE behavior where it'll sometimes
6561
  // re-fire a series of drag-related events right after the drop (#1551)
6562
  var lastDrop = 0;
6563
 
6564
  function onDrop(e) {
6565
    var cm = this;
6566
    clearDragCursor(cm);
6567
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
6568
      { return }
6569
    e_preventDefault(e);
6570
    if (ie) { lastDrop = +new Date; }
6571
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
6572
    if (!pos || cm.isReadOnly()) { return }
6573
    // Might be a file drop, in which case we simply extract the text
6574
    // and insert it.
6575
    if (files && files.length && window.FileReader && window.File) {
6576
      var n = files.length, text = Array(n), read = 0;
15152 obado 6577
      var markAsReadAndPasteIfAllFilesAreRead = function () {
6578
        if (++read == n) {
6579
          operation(cm, function () {
14283 obado 6580
            pos = clipPos(cm.doc, pos);
6581
            var change = {from: pos, to: pos,
15152 obado 6582
                          text: cm.doc.splitLines(
6583
                              text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
14283 obado 6584
                          origin: "paste"};
6585
            makeChange(cm.doc, change);
15152 obado 6586
            setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
6587
          })();
6588
        }
6589
      };
6590
      var readTextFromFile = function (file, i) {
6591
        if (cm.options.allowDropFileTypes &&
6592
            indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
6593
          markAsReadAndPasteIfAllFilesAreRead();
6594
          return
6595
        }
6596
        var reader = new FileReader;
6597
        reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
6598
        reader.onload = function () {
6599
          var content = reader.result;
6600
          if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
6601
            markAsReadAndPasteIfAllFilesAreRead();
6602
            return
14283 obado 6603
          }
15152 obado 6604
          text[i] = content;
6605
          markAsReadAndPasteIfAllFilesAreRead();
6606
        };
14283 obado 6607
        reader.readAsText(file);
6608
      };
15152 obado 6609
      for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
14283 obado 6610
    } else { // Normal drop
6611
      // Don't do a replace if the drop happened inside of the selected text.
6612
      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
6613
        cm.state.draggingText(e);
6614
        // Ensure the editor is re-focused
6615
        setTimeout(function () { return cm.display.input.focus(); }, 20);
6616
        return
6617
      }
6618
      try {
6619
        var text$1 = e.dataTransfer.getData("Text");
6620
        if (text$1) {
6621
          var selected;
6622
          if (cm.state.draggingText && !cm.state.draggingText.copy)
6623
            { selected = cm.listSelections(); }
6624
          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
6625
          if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
6626
            { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
6627
          cm.replaceSelection(text$1, "around", "paste");
6628
          cm.display.input.focus();
6629
        }
6630
      }
15332 obado 6631
      catch(e$1){}
14283 obado 6632
    }
6633
  }
6634
 
6635
  function onDragStart(cm, e) {
6636
    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
6637
    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
6638
 
6639
    e.dataTransfer.setData("Text", cm.getSelection());
6640
    e.dataTransfer.effectAllowed = "copyMove";
6641
 
6642
    // Use dummy image instead of default browsers image.
6643
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
6644
    if (e.dataTransfer.setDragImage && !safari) {
6645
      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
6646
      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
6647
      if (presto) {
6648
        img.width = img.height = 1;
6649
        cm.display.wrapper.appendChild(img);
6650
        // Force a relayout, or Opera won't use our image for some obscure reason
6651
        img._top = img.offsetTop;
6652
      }
6653
      e.dataTransfer.setDragImage(img, 0, 0);
6654
      if (presto) { img.parentNode.removeChild(img); }
6655
    }
6656
  }
6657
 
6658
  function onDragOver(cm, e) {
6659
    var pos = posFromMouse(cm, e);
6660
    if (!pos) { return }
6661
    var frag = document.createDocumentFragment();
6662
    drawSelectionCursor(cm, pos, frag);
6663
    if (!cm.display.dragCursor) {
6664
      cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
6665
      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
6666
    }
6667
    removeChildrenAndAdd(cm.display.dragCursor, frag);
6668
  }
6669
 
6670
  function clearDragCursor(cm) {
6671
    if (cm.display.dragCursor) {
6672
      cm.display.lineSpace.removeChild(cm.display.dragCursor);
6673
      cm.display.dragCursor = null;
6674
    }
6675
  }
6676
 
6677
  // These must be handled carefully, because naively registering a
6678
  // handler for each editor will cause the editors to never be
6679
  // garbage collected.
6680
 
6681
  function forEachCodeMirror(f) {
6682
    if (!document.getElementsByClassName) { return }
6683
    var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
6684
    for (var i = 0; i < byClass.length; i++) {
6685
      var cm = byClass[i].CodeMirror;
6686
      if (cm) { editors.push(cm); }
6687
    }
6688
    if (editors.length) { editors[0].operation(function () {
6689
      for (var i = 0; i < editors.length; i++) { f(editors[i]); }
6690
    }); }
6691
  }
6692
 
6693
  var globalsRegistered = false;
6694
  function ensureGlobalHandlers() {
6695
    if (globalsRegistered) { return }
6696
    registerGlobalHandlers();
6697
    globalsRegistered = true;
6698
  }
6699
  function registerGlobalHandlers() {
6700
    // When the window resizes, we need to refresh active editors.
6701
    var resizeTimer;
6702
    on(window, "resize", function () {
6703
      if (resizeTimer == null) { resizeTimer = setTimeout(function () {
6704
        resizeTimer = null;
6705
        forEachCodeMirror(onResize);
6706
      }, 100); }
6707
    });
6708
    // When the window loses focus, we want to show the editor as blurred
6709
    on(window, "blur", function () { return forEachCodeMirror(onBlur); });
6710
  }
6711
  // Called when the window resizes
6712
  function onResize(cm) {
6713
    var d = cm.display;
6714
    // Might be a text scaling operation, clear size caches.
6715
    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
6716
    d.scrollbarsClipped = false;
6717
    cm.setSize();
6718
  }
6719
 
6720
  var keyNames = {
6721
    3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
6722
    19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
6723
    36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
6724
    46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
6725
    106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
6726
    173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
15332 obado 6727
    221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
14283 obado 6728
    63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
6729
  };
6730
 
6731
  // Number keys
6732
  for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
6733
  // Alphabetic keys
6734
  for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
6735
  // Function keys
6736
  for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
6737
 
6738
  var keyMap = {};
6739
 
6740
  keyMap.basic = {
6741
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
6742
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
6743
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
6744
    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
6745
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
6746
    "Esc": "singleSelection"
6747
  };
6748
  // Note that the save and find-related commands aren't defined by
6749
  // default. User code or addons can define them. Unknown commands
6750
  // are simply ignored.
6751
  keyMap.pcDefault = {
6752
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
6753
    "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
6754
    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
6755
    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
6756
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
6757
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
6758
    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
6759
    "fallthrough": "basic"
6760
  };
6761
  // Very basic readline/emacs-style bindings, which are standard on Mac.
6762
  keyMap.emacsy = {
6763
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
16493 obado 6764
    "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
6765
    "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
6766
    "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
14283 obado 6767
  };
6768
  keyMap.macDefault = {
6769
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
6770
    "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
6771
    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
6772
    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
6773
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
6774
    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
6775
    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
6776
    "fallthrough": ["basic", "emacsy"]
6777
  };
6778
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
6779
 
6780
  // KEYMAP DISPATCH
6781
 
6782
  function normalizeKeyName(name) {
6783
    var parts = name.split(/-(?!$)/);
6784
    name = parts[parts.length - 1];
6785
    var alt, ctrl, shift, cmd;
6786
    for (var i = 0; i < parts.length - 1; i++) {
6787
      var mod = parts[i];
6788
      if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
6789
      else if (/^a(lt)?$/i.test(mod)) { alt = true; }
6790
      else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
6791
      else if (/^s(hift)?$/i.test(mod)) { shift = true; }
6792
      else { throw new Error("Unrecognized modifier name: " + mod) }
6793
    }
6794
    if (alt) { name = "Alt-" + name; }
6795
    if (ctrl) { name = "Ctrl-" + name; }
6796
    if (cmd) { name = "Cmd-" + name; }
6797
    if (shift) { name = "Shift-" + name; }
6798
    return name
6799
  }
6800
 
6801
  // This is a kludge to keep keymaps mostly working as raw objects
6802
  // (backwards compatibility) while at the same time support features
6803
  // like normalization and multi-stroke key bindings. It compiles a
6804
  // new normalized keymap, and then updates the old object to reflect
6805
  // this.
6806
  function normalizeKeyMap(keymap) {
6807
    var copy = {};
6808
    for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
6809
      var value = keymap[keyname];
6810
      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
6811
      if (value == "...") { delete keymap[keyname]; continue }
6812
 
6813
      var keys = map(keyname.split(" "), normalizeKeyName);
6814
      for (var i = 0; i < keys.length; i++) {
6815
        var val = (void 0), name = (void 0);
6816
        if (i == keys.length - 1) {
6817
          name = keys.join(" ");
6818
          val = value;
6819
        } else {
6820
          name = keys.slice(0, i + 1).join(" ");
6821
          val = "...";
6822
        }
6823
        var prev = copy[name];
6824
        if (!prev) { copy[name] = val; }
6825
        else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
6826
      }
6827
      delete keymap[keyname];
6828
    } }
6829
    for (var prop in copy) { keymap[prop] = copy[prop]; }
6830
    return keymap
6831
  }
6832
 
15152 obado 6833
  function lookupKey(key, map, handle, context) {
6834
    map = getKeyMap(map);
6835
    var found = map.call ? map.call(key, context) : map[key];
14283 obado 6836
    if (found === false) { return "nothing" }
6837
    if (found === "...") { return "multi" }
6838
    if (found != null && handle(found)) { return "handled" }
6839
 
15152 obado 6840
    if (map.fallthrough) {
6841
      if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
6842
        { return lookupKey(key, map.fallthrough, handle, context) }
6843
      for (var i = 0; i < map.fallthrough.length; i++) {
6844
        var result = lookupKey(key, map.fallthrough[i], handle, context);
14283 obado 6845
        if (result) { return result }
6846
      }
6847
    }
6848
  }
6849
 
6850
  // Modifier key presses don't count as 'real' key presses for the
6851
  // purpose of keymap fallthrough.
6852
  function isModifierKey(value) {
6853
    var name = typeof value == "string" ? value : keyNames[value.keyCode];
6854
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
6855
  }
6856
 
6857
  function addModifierNames(name, event, noShift) {
6858
    var base = name;
6859
    if (event.altKey && base != "Alt") { name = "Alt-" + name; }
6860
    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
15332 obado 6861
    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
14283 obado 6862
    if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
6863
    return name
6864
  }
6865
 
6866
  // Look up the name of a key as indicated by an event object.
6867
  function keyName(event, noShift) {
6868
    if (presto && event.keyCode == 34 && event["char"]) { return false }
6869
    var name = keyNames[event.keyCode];
6870
    if (name == null || event.altGraphKey) { return false }
6871
    // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
6872
    // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
6873
    if (event.keyCode == 3 && event.code) { name = event.code; }
6874
    return addModifierNames(name, event, noShift)
6875
  }
6876
 
6877
  function getKeyMap(val) {
6878
    return typeof val == "string" ? keyMap[val] : val
6879
  }
6880
 
6881
  // Helper for deleting text near the selection(s), used to implement
6882
  // backspace, delete, and similar functionality.
6883
  function deleteNearSelection(cm, compute) {
6884
    var ranges = cm.doc.sel.ranges, kill = [];
6885
    // Build up a set of ranges to kill first, merging overlapping
6886
    // ranges.
6887
    for (var i = 0; i < ranges.length; i++) {
6888
      var toKill = compute(ranges[i]);
6889
      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
6890
        var replaced = kill.pop();
6891
        if (cmp(replaced.from, toKill.from) < 0) {
6892
          toKill.from = replaced.from;
6893
          break
6894
        }
6895
      }
6896
      kill.push(toKill);
6897
    }
6898
    // Next, remove those actual ranges.
6899
    runInOp(cm, function () {
6900
      for (var i = kill.length - 1; i >= 0; i--)
6901
        { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
6902
      ensureCursorVisible(cm);
6903
    });
6904
  }
6905
 
6906
  function moveCharLogically(line, ch, dir) {
6907
    var target = skipExtendingChars(line.text, ch + dir, dir);
6908
    return target < 0 || target > line.text.length ? null : target
6909
  }
6910
 
6911
  function moveLogically(line, start, dir) {
6912
    var ch = moveCharLogically(line, start.ch, dir);
6913
    return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
6914
  }
6915
 
6916
  function endOfLine(visually, cm, lineObj, lineNo, dir) {
6917
    if (visually) {
15152 obado 6918
      if (cm.doc.direction == "rtl") { dir = -dir; }
14283 obado 6919
      var order = getOrder(lineObj, cm.doc.direction);
6920
      if (order) {
6921
        var part = dir < 0 ? lst(order) : order[0];
6922
        var moveInStorageOrder = (dir < 0) == (part.level == 1);
6923
        var sticky = moveInStorageOrder ? "after" : "before";
6924
        var ch;
6925
        // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
6926
        // it could be that the last bidi part is not on the last visual line,
6927
        // since visual lines contain content order-consecutive chunks.
6928
        // Thus, in rtl, we are looking for the first (content-order) character
6929
        // in the rtl chunk that is on the last line (that is, the same line
6930
        // as the last (content-order) character).
6931
        if (part.level > 0 || cm.doc.direction == "rtl") {
6932
          var prep = prepareMeasureForLine(cm, lineObj);
6933
          ch = dir < 0 ? lineObj.text.length - 1 : 0;
6934
          var targetTop = measureCharPrepared(cm, prep, ch).top;
6935
          ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
6936
          if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
6937
        } else { ch = dir < 0 ? part.to : part.from; }
6938
        return new Pos(lineNo, ch, sticky)
6939
      }
6940
    }
6941
    return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6942
  }
6943
 
6944
  function moveVisually(cm, line, start, dir) {
6945
    var bidi = getOrder(line, cm.doc.direction);
6946
    if (!bidi) { return moveLogically(line, start, dir) }
6947
    if (start.ch >= line.text.length) {
6948
      start.ch = line.text.length;
6949
      start.sticky = "before";
6950
    } else if (start.ch <= 0) {
6951
      start.ch = 0;
6952
      start.sticky = "after";
6953
    }
6954
    var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
6955
    if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
6956
      // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
6957
      // nothing interesting happens.
6958
      return moveLogically(line, start, dir)
6959
    }
6960
 
6961
    var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
6962
    var prep;
6963
    var getWrappedLineExtent = function (ch) {
6964
      if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
6965
      prep = prep || prepareMeasureForLine(cm, line);
6966
      return wrappedLineExtentChar(cm, line, prep, ch)
6967
    };
6968
    var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
6969
 
6970
    if (cm.doc.direction == "rtl" || part.level == 1) {
6971
      var moveInStorageOrder = (part.level == 1) == (dir < 0);
6972
      var ch = mv(start, moveInStorageOrder ? 1 : -1);
6973
      if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
6974
        // Case 2: We move within an rtl part or in an rtl editor on the same visual line
6975
        var sticky = moveInStorageOrder ? "before" : "after";
6976
        return new Pos(start.line, ch, sticky)
6977
      }
6978
    }
6979
 
6980
    // Case 3: Could not move within this bidi part in this visual line, so leave
6981
    // the current bidi part
6982
 
6983
    var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
6984
      var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
6985
        ? new Pos(start.line, mv(ch, 1), "before")
6986
        : new Pos(start.line, ch, "after"); };
6987
 
6988
      for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
6989
        var part = bidi[partPos];
6990
        var moveInStorageOrder = (dir > 0) == (part.level != 1);
6991
        var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
6992
        if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
6993
        ch = moveInStorageOrder ? part.from : mv(part.to, -1);
6994
        if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
6995
      }
6996
    };
6997
 
6998
    // Case 3a: Look for other bidi parts on the same visual line
6999
    var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
7000
    if (res) { return res }
7001
 
7002
    // Case 3b: Look for other bidi parts on the next visual line
7003
    var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
7004
    if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
7005
      res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
7006
      if (res) { return res }
7007
    }
7008
 
7009
    // Case 4: Nowhere to move
7010
    return null
7011
  }
7012
 
7013
  // Commands are parameter-less actions that can be performed on an
7014
  // editor, mostly used for keybindings.
7015
  var commands = {
7016
    selectAll: selectAll,
7017
    singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
7018
    killLine: function (cm) { return deleteNearSelection(cm, function (range) {
7019
      if (range.empty()) {
7020
        var len = getLine(cm.doc, range.head.line).text.length;
7021
        if (range.head.ch == len && range.head.line < cm.lastLine())
7022
          { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
7023
        else
7024
          { return {from: range.head, to: Pos(range.head.line, len)} }
7025
      } else {
7026
        return {from: range.from(), to: range.to()}
7027
      }
7028
    }); },
7029
    deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
7030
      from: Pos(range.from().line, 0),
7031
      to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
7032
    }); }); },
7033
    delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
7034
      from: Pos(range.from().line, 0), to: range.from()
7035
    }); }); },
7036
    delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
7037
      var top = cm.charCoords(range.head, "div").top + 5;
7038
      var leftPos = cm.coordsChar({left: 0, top: top}, "div");
7039
      return {from: leftPos, to: range.from()}
7040
    }); },
7041
    delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
7042
      var top = cm.charCoords(range.head, "div").top + 5;
7043
      var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
7044
      return {from: range.from(), to: rightPos }
7045
    }); },
7046
    undo: function (cm) { return cm.undo(); },
7047
    redo: function (cm) { return cm.redo(); },
7048
    undoSelection: function (cm) { return cm.undoSelection(); },
7049
    redoSelection: function (cm) { return cm.redoSelection(); },
7050
    goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
7051
    goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
7052
    goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
7053
      {origin: "+move", bias: 1}
7054
    ); },
7055
    goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
7056
      {origin: "+move", bias: 1}
7057
    ); },
7058
    goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
7059
      {origin: "+move", bias: -1}
7060
    ); },
7061
    goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
7062
      var top = cm.cursorCoords(range.head, "div").top + 5;
7063
      return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
7064
    }, sel_move); },
7065
    goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
7066
      var top = cm.cursorCoords(range.head, "div").top + 5;
7067
      return cm.coordsChar({left: 0, top: top}, "div")
7068
    }, sel_move); },
7069
    goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
7070
      var top = cm.cursorCoords(range.head, "div").top + 5;
7071
      var pos = cm.coordsChar({left: 0, top: top}, "div");
7072
      if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
7073
      return pos
7074
    }, sel_move); },
7075
    goLineUp: function (cm) { return cm.moveV(-1, "line"); },
7076
    goLineDown: function (cm) { return cm.moveV(1, "line"); },
7077
    goPageUp: function (cm) { return cm.moveV(-1, "page"); },
7078
    goPageDown: function (cm) { return cm.moveV(1, "page"); },
7079
    goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
7080
    goCharRight: function (cm) { return cm.moveH(1, "char"); },
7081
    goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
7082
    goColumnRight: function (cm) { return cm.moveH(1, "column"); },
7083
    goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
7084
    goGroupRight: function (cm) { return cm.moveH(1, "group"); },
7085
    goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
7086
    goWordRight: function (cm) { return cm.moveH(1, "word"); },
16493 obado 7087
    delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
14283 obado 7088
    delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
7089
    delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
7090
    delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
7091
    delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
7092
    delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
7093
    indentAuto: function (cm) { return cm.indentSelection("smart"); },
7094
    indentMore: function (cm) { return cm.indentSelection("add"); },
7095
    indentLess: function (cm) { return cm.indentSelection("subtract"); },
7096
    insertTab: function (cm) { return cm.replaceSelection("\t"); },
7097
    insertSoftTab: function (cm) {
7098
      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
7099
      for (var i = 0; i < ranges.length; i++) {
7100
        var pos = ranges[i].from();
7101
        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
7102
        spaces.push(spaceStr(tabSize - col % tabSize));
7103
      }
7104
      cm.replaceSelections(spaces);
7105
    },
7106
    defaultTab: function (cm) {
7107
      if (cm.somethingSelected()) { cm.indentSelection("add"); }
7108
      else { cm.execCommand("insertTab"); }
7109
    },
7110
    // Swap the two chars left and right of each selection's head.
7111
    // Move cursor behind the two swapped characters afterwards.
7112
    //
7113
    // Doesn't consider line feeds a character.
7114
    // Doesn't scan more than one line above to find a character.
7115
    // Doesn't do anything on an empty line.
7116
    // Doesn't do anything with non-empty selections.
7117
    transposeChars: function (cm) { return runInOp(cm, function () {
7118
      var ranges = cm.listSelections(), newSel = [];
7119
      for (var i = 0; i < ranges.length; i++) {
7120
        if (!ranges[i].empty()) { continue }
7121
        var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
7122
        if (line) {
7123
          if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
7124
          if (cur.ch > 0) {
7125
            cur = new Pos(cur.line, cur.ch + 1);
7126
            cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
7127
                            Pos(cur.line, cur.ch - 2), cur, "+transpose");
7128
          } else if (cur.line > cm.doc.first) {
7129
            var prev = getLine(cm.doc, cur.line - 1).text;
7130
            if (prev) {
7131
              cur = new Pos(cur.line, 1);
7132
              cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
7133
                              prev.charAt(prev.length - 1),
7134
                              Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
7135
            }
7136
          }
7137
        }
7138
        newSel.push(new Range(cur, cur));
7139
      }
7140
      cm.setSelections(newSel);
7141
    }); },
7142
    newlineAndIndent: function (cm) { return runInOp(cm, function () {
7143
      var sels = cm.listSelections();
7144
      for (var i = sels.length - 1; i >= 0; i--)
7145
        { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
7146
      sels = cm.listSelections();
7147
      for (var i$1 = 0; i$1 < sels.length; i$1++)
7148
        { cm.indentLine(sels[i$1].from().line, null, true); }
7149
      ensureCursorVisible(cm);
7150
    }); },
7151
    openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
7152
    toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
7153
  };
7154
 
7155
 
7156
  function lineStart(cm, lineN) {
7157
    var line = getLine(cm.doc, lineN);
7158
    var visual = visualLine(line);
7159
    if (visual != line) { lineN = lineNo(visual); }
7160
    return endOfLine(true, cm, visual, lineN, 1)
7161
  }
7162
  function lineEnd(cm, lineN) {
7163
    var line = getLine(cm.doc, lineN);
7164
    var visual = visualLineEnd(line);
7165
    if (visual != line) { lineN = lineNo(visual); }
7166
    return endOfLine(true, cm, line, lineN, -1)
7167
  }
7168
  function lineStartSmart(cm, pos) {
7169
    var start = lineStart(cm, pos.line);
7170
    var line = getLine(cm.doc, start.line);
7171
    var order = getOrder(line, cm.doc.direction);
7172
    if (!order || order[0].level == 0) {
15152 obado 7173
      var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
14283 obado 7174
      var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
7175
      return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
7176
    }
7177
    return start
7178
  }
7179
 
7180
  // Run a handler that was bound to a key.
7181
  function doHandleBinding(cm, bound, dropShift) {
7182
    if (typeof bound == "string") {
7183
      bound = commands[bound];
7184
      if (!bound) { return false }
7185
    }
7186
    // Ensure previous input has been read, so that the handler sees a
7187
    // consistent view of the document
7188
    cm.display.input.ensurePolled();
7189
    var prevShift = cm.display.shift, done = false;
7190
    try {
7191
      if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7192
      if (dropShift) { cm.display.shift = false; }
7193
      done = bound(cm) != Pass;
7194
    } finally {
7195
      cm.display.shift = prevShift;
7196
      cm.state.suppressEdits = false;
7197
    }
7198
    return done
7199
  }
7200
 
7201
  function lookupKeyForEditor(cm, name, handle) {
7202
    for (var i = 0; i < cm.state.keyMaps.length; i++) {
7203
      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
7204
      if (result) { return result }
7205
    }
7206
    return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7207
      || lookupKey(name, cm.options.keyMap, handle, cm)
7208
  }
7209
 
7210
  // Note that, despite the name, this function is also used to check
7211
  // for bound mouse clicks.
7212
 
7213
  var stopSeq = new Delayed;
7214
 
7215
  function dispatchKey(cm, name, e, handle) {
7216
    var seq = cm.state.keySeq;
7217
    if (seq) {
7218
      if (isModifierKey(name)) { return "handled" }
7219
      if (/\'$/.test(name))
7220
        { cm.state.keySeq = null; }
7221
      else
7222
        { stopSeq.set(50, function () {
7223
          if (cm.state.keySeq == seq) {
7224
            cm.state.keySeq = null;
7225
            cm.display.input.reset();
7226
          }
7227
        }); }
7228
      if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
7229
    }
7230
    return dispatchKeyInner(cm, name, e, handle)
7231
  }
7232
 
7233
  function dispatchKeyInner(cm, name, e, handle) {
7234
    var result = lookupKeyForEditor(cm, name, handle);
7235
 
7236
    if (result == "multi")
7237
      { cm.state.keySeq = name; }
7238
    if (result == "handled")
7239
      { signalLater(cm, "keyHandled", cm, name, e); }
7240
 
7241
    if (result == "handled" || result == "multi") {
7242
      e_preventDefault(e);
7243
      restartBlink(cm);
7244
    }
7245
 
7246
    return !!result
7247
  }
7248
 
7249
  // Handle a key from the keydown event.
7250
  function handleKeyBinding(cm, e) {
7251
    var name = keyName(e, true);
7252
    if (!name) { return false }
7253
 
7254
    if (e.shiftKey && !cm.state.keySeq) {
7255
      // First try to resolve full name (including 'Shift-'). Failing
7256
      // that, see if there is a cursor-motion command (starting with
7257
      // 'go') bound to the keyname without 'Shift-'.
7258
      return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
7259
          || dispatchKey(cm, name, e, function (b) {
7260
               if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
7261
                 { return doHandleBinding(cm, b) }
7262
             })
7263
    } else {
7264
      return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
7265
    }
7266
  }
7267
 
7268
  // Handle a key from the keypress event
7269
  function handleCharBinding(cm, e, ch) {
7270
    return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
7271
  }
7272
 
7273
  var lastStoppedKey = null;
7274
  function onKeyDown(e) {
7275
    var cm = this;
15152 obado 7276
    if (e.target && e.target != cm.display.input.getField()) { return }
18249 obado 7277
    cm.curOp.focus = activeElt(root(cm));
14283 obado 7278
    if (signalDOMEvent(cm, e)) { return }
7279
    // IE does strange things with escape.
7280
    if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
7281
    var code = e.keyCode;
7282
    cm.display.shift = code == 16 || e.shiftKey;
7283
    var handled = handleKeyBinding(cm, e);
7284
    if (presto) {
7285
      lastStoppedKey = handled ? code : null;
7286
      // Opera has no cut event... we try to at least catch the key combo
7287
      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
7288
        { cm.replaceSelection("", null, "cut"); }
7289
    }
15152 obado 7290
    if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
7291
      { document.execCommand("cut"); }
14283 obado 7292
 
7293
    // Turn mouse into crosshair when Alt is held on Mac.
7294
    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
7295
      { showCrossHair(cm); }
7296
  }
7297
 
7298
  function showCrossHair(cm) {
7299
    var lineDiv = cm.display.lineDiv;
7300
    addClass(lineDiv, "CodeMirror-crosshair");
7301
 
7302
    function up(e) {
7303
      if (e.keyCode == 18 || !e.altKey) {
7304
        rmClass(lineDiv, "CodeMirror-crosshair");
7305
        off(document, "keyup", up);
7306
        off(document, "mouseover", up);
7307
      }
7308
    }
7309
    on(document, "keyup", up);
7310
    on(document, "mouseover", up);
7311
  }
7312
 
7313
  function onKeyUp(e) {
7314
    if (e.keyCode == 16) { this.doc.sel.shift = false; }
7315
    signalDOMEvent(this, e);
7316
  }
7317
 
7318
  function onKeyPress(e) {
7319
    var cm = this;
15152 obado 7320
    if (e.target && e.target != cm.display.input.getField()) { return }
14283 obado 7321
    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
7322
    var keyCode = e.keyCode, charCode = e.charCode;
7323
    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
7324
    if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
7325
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
7326
    // Some browsers fire keypress events for backspace
7327
    if (ch == "\x08") { return }
7328
    if (handleCharBinding(cm, e, ch)) { return }
7329
    cm.display.input.onKeyPress(e);
7330
  }
7331
 
7332
  var DOUBLECLICK_DELAY = 400;
7333
 
7334
  var PastClick = function(time, pos, button) {
7335
    this.time = time;
7336
    this.pos = pos;
7337
    this.button = button;
7338
  };
7339
 
7340
  PastClick.prototype.compare = function (time, pos, button) {
7341
    return this.time + DOUBLECLICK_DELAY > time &&
7342
      cmp(pos, this.pos) == 0 && button == this.button
7343
  };
7344
 
7345
  var lastClick, lastDoubleClick;
7346
  function clickRepeat(pos, button) {
7347
    var now = +new Date;
7348
    if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
7349
      lastClick = lastDoubleClick = null;
7350
      return "triple"
7351
    } else if (lastClick && lastClick.compare(now, pos, button)) {
7352
      lastDoubleClick = new PastClick(now, pos, button);
7353
      lastClick = null;
7354
      return "double"
7355
    } else {
7356
      lastClick = new PastClick(now, pos, button);
7357
      lastDoubleClick = null;
7358
      return "single"
7359
    }
7360
  }
7361
 
7362
  // A mouse down can be a single click, double click, triple click,
7363
  // start of selection drag, start of text drag, new cursor
7364
  // (ctrl-click), rectangle drag (alt-drag), or xwin
7365
  // middle-click-paste. Or it might be a click on something we should
7366
  // not interfere with, such as a scrollbar or widget.
7367
  function onMouseDown(e) {
7368
    var cm = this, display = cm.display;
7369
    if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
7370
    display.input.ensurePolled();
7371
    display.shift = e.shiftKey;
7372
 
7373
    if (eventInWidget(display, e)) {
7374
      if (!webkit) {
7375
        // Briefly turn off draggability, to allow widgets to do
7376
        // normal dragging things.
7377
        display.scroller.draggable = false;
7378
        setTimeout(function () { return display.scroller.draggable = true; }, 100);
7379
      }
7380
      return
7381
    }
7382
    if (clickInGutter(cm, e)) { return }
7383
    var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
17702 obado 7384
    win(cm).focus();
14283 obado 7385
 
7386
    // #3261: make sure, that we're not starting a second selection
7387
    if (button == 1 && cm.state.selectingText)
7388
      { cm.state.selectingText(e); }
7389
 
7390
    if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
7391
 
7392
    if (button == 1) {
7393
      if (pos) { leftButtonDown(cm, pos, repeat, e); }
7394
      else if (e_target(e) == display.scroller) { e_preventDefault(e); }
7395
    } else if (button == 2) {
7396
      if (pos) { extendSelection(cm.doc, pos); }
7397
      setTimeout(function () { return display.input.focus(); }, 20);
7398
    } else if (button == 3) {
7399
      if (captureRightClick) { cm.display.input.onContextMenu(e); }
7400
      else { delayBlurEvent(cm); }
7401
    }
7402
  }
7403
 
7404
  function handleMappedButton(cm, button, pos, repeat, event) {
7405
    var name = "Click";
7406
    if (repeat == "double") { name = "Double" + name; }
7407
    else if (repeat == "triple") { name = "Triple" + name; }
7408
    name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
7409
 
7410
    return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
7411
      if (typeof bound == "string") { bound = commands[bound]; }
7412
      if (!bound) { return false }
7413
      var done = false;
7414
      try {
7415
        if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7416
        done = bound(cm, pos) != Pass;
7417
      } finally {
7418
        cm.state.suppressEdits = false;
7419
      }
7420
      return done
7421
    })
7422
  }
7423
 
7424
  function configureMouse(cm, repeat, event) {
7425
    var option = cm.getOption("configureMouse");
7426
    var value = option ? option(cm, repeat, event) : {};
7427
    if (value.unit == null) {
7428
      var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
7429
      value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
7430
    }
7431
    if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
7432
    if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
7433
    if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
7434
    return value
7435
  }
7436
 
7437
  function leftButtonDown(cm, pos, repeat, event) {
7438
    if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
18249 obado 7439
    else { cm.curOp.focus = activeElt(root(cm)); }
14283 obado 7440
 
7441
    var behavior = configureMouse(cm, repeat, event);
7442
 
7443
    var sel = cm.doc.sel, contained;
7444
    if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
7445
        repeat == "single" && (contained = sel.contains(pos)) > -1 &&
7446
        (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
7447
        (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
7448
      { leftButtonStartDrag(cm, event, pos, behavior); }
7449
    else
7450
      { leftButtonSelect(cm, event, pos, behavior); }
7451
  }
7452
 
7453
  // Start a text drag. When it ends, see if any dragging actually
7454
  // happen, and treat as a click if it didn't.
7455
  function leftButtonStartDrag(cm, event, pos, behavior) {
7456
    var display = cm.display, moved = false;
7457
    var dragEnd = operation(cm, function (e) {
7458
      if (webkit) { display.scroller.draggable = false; }
7459
      cm.state.draggingText = false;
16493 obado 7460
      if (cm.state.delayingBlurEvent) {
7461
        if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
7462
        else { delayBlurEvent(cm); }
7463
      }
14283 obado 7464
      off(display.wrapper.ownerDocument, "mouseup", dragEnd);
7465
      off(display.wrapper.ownerDocument, "mousemove", mouseMove);
7466
      off(display.scroller, "dragstart", dragStart);
7467
      off(display.scroller, "drop", dragEnd);
7468
      if (!moved) {
7469
        e_preventDefault(e);
7470
        if (!behavior.addNew)
7471
          { extendSelection(cm.doc, pos, null, null, behavior.extend); }
7472
        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
15152 obado 7473
        if ((webkit && !safari) || ie && ie_version == 9)
7474
          { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
14283 obado 7475
        else
7476
          { display.input.focus(); }
7477
      }
7478
    });
7479
    var mouseMove = function(e2) {
7480
      moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
7481
    };
7482
    var dragStart = function () { return moved = true; };
7483
    // Let the drag handler handle this.
7484
    if (webkit) { display.scroller.draggable = true; }
7485
    cm.state.draggingText = dragEnd;
7486
    dragEnd.copy = !behavior.moveOnDrag;
7487
    on(display.wrapper.ownerDocument, "mouseup", dragEnd);
7488
    on(display.wrapper.ownerDocument, "mousemove", mouseMove);
7489
    on(display.scroller, "dragstart", dragStart);
7490
    on(display.scroller, "drop", dragEnd);
7491
 
16493 obado 7492
    cm.state.delayingBlurEvent = true;
14283 obado 7493
    setTimeout(function () { return display.input.focus(); }, 20);
16493 obado 7494
    // IE's approach to draggable
7495
    if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
14283 obado 7496
  }
7497
 
7498
  function rangeForUnit(cm, pos, unit) {
7499
    if (unit == "char") { return new Range(pos, pos) }
7500
    if (unit == "word") { return cm.findWordAt(pos) }
7501
    if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
7502
    var result = unit(cm, pos);
7503
    return new Range(result.from, result.to)
7504
  }
7505
 
7506
  // Normal selection, as opposed to text dragging.
7507
  function leftButtonSelect(cm, event, start, behavior) {
16493 obado 7508
    if (ie) { delayBlurEvent(cm); }
18249 obado 7509
    var display = cm.display, doc = cm.doc;
14283 obado 7510
    e_preventDefault(event);
7511
 
18249 obado 7512
    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
14283 obado 7513
    if (behavior.addNew && !behavior.extend) {
18249 obado 7514
      ourIndex = doc.sel.contains(start);
14283 obado 7515
      if (ourIndex > -1)
7516
        { ourRange = ranges[ourIndex]; }
7517
      else
7518
        { ourRange = new Range(start, start); }
7519
    } else {
18249 obado 7520
      ourRange = doc.sel.primary();
7521
      ourIndex = doc.sel.primIndex;
14283 obado 7522
    }
7523
 
7524
    if (behavior.unit == "rectangle") {
7525
      if (!behavior.addNew) { ourRange = new Range(start, start); }
7526
      start = posFromMouse(cm, event, true, true);
7527
      ourIndex = -1;
7528
    } else {
15152 obado 7529
      var range = rangeForUnit(cm, start, behavior.unit);
14283 obado 7530
      if (behavior.extend)
15152 obado 7531
        { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
14283 obado 7532
      else
15152 obado 7533
        { ourRange = range; }
14283 obado 7534
    }
7535
 
7536
    if (!behavior.addNew) {
7537
      ourIndex = 0;
18249 obado 7538
      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
7539
      startSel = doc.sel;
14283 obado 7540
    } else if (ourIndex == -1) {
7541
      ourIndex = ranges.length;
18249 obado 7542
      setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
14283 obado 7543
                   {scroll: false, origin: "*mouse"});
7544
    } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
18249 obado 7545
      setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
14283 obado 7546
                   {scroll: false, origin: "*mouse"});
18249 obado 7547
      startSel = doc.sel;
14283 obado 7548
    } else {
18249 obado 7549
      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
14283 obado 7550
    }
7551
 
7552
    var lastPos = start;
7553
    function extendTo(pos) {
7554
      if (cmp(lastPos, pos) == 0) { return }
7555
      lastPos = pos;
7556
 
7557
      if (behavior.unit == "rectangle") {
7558
        var ranges = [], tabSize = cm.options.tabSize;
18249 obado 7559
        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
7560
        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
14283 obado 7561
        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
7562
        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
7563
             line <= end; line++) {
18249 obado 7564
          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
14283 obado 7565
          if (left == right)
7566
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
7567
          else if (text.length > leftPos)
7568
            { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
7569
        }
7570
        if (!ranges.length) { ranges.push(new Range(start, start)); }
18249 obado 7571
        setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
14283 obado 7572
                     {origin: "*mouse", scroll: false});
7573
        cm.scrollIntoView(pos);
7574
      } else {
7575
        var oldRange = ourRange;
15152 obado 7576
        var range = rangeForUnit(cm, pos, behavior.unit);
14283 obado 7577
        var anchor = oldRange.anchor, head;
15152 obado 7578
        if (cmp(range.anchor, anchor) > 0) {
7579
          head = range.head;
7580
          anchor = minPos(oldRange.from(), range.anchor);
14283 obado 7581
        } else {
15152 obado 7582
          head = range.anchor;
7583
          anchor = maxPos(oldRange.to(), range.head);
14283 obado 7584
        }
7585
        var ranges$1 = startSel.ranges.slice(0);
18249 obado 7586
        ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
7587
        setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
14283 obado 7588
      }
7589
    }
7590
 
7591
    var editorSize = display.wrapper.getBoundingClientRect();
7592
    // Used to ensure timeout re-tries don't fire when another extend
7593
    // happened in the meantime (clearTimeout isn't reliable -- at
7594
    // least on Chrome, the timeouts still happen even when cleared,
7595
    // if the clear happens after their scheduled firing time).
7596
    var counter = 0;
7597
 
7598
    function extend(e) {
7599
      var curCount = ++counter;
7600
      var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
7601
      if (!cur) { return }
7602
      if (cmp(cur, lastPos) != 0) {
18249 obado 7603
        cm.curOp.focus = activeElt(root(cm));
14283 obado 7604
        extendTo(cur);
18249 obado 7605
        var visible = visibleLines(display, doc);
14283 obado 7606
        if (cur.line >= visible.to || cur.line < visible.from)
7607
          { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
7608
      } else {
7609
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
7610
        if (outside) { setTimeout(operation(cm, function () {
7611
          if (counter != curCount) { return }
7612
          display.scroller.scrollTop += outside;
7613
          extend(e);
7614
        }), 50); }
7615
      }
7616
    }
7617
 
7618
    function done(e) {
7619
      cm.state.selectingText = false;
7620
      counter = Infinity;
7621
      // If e is null or undefined we interpret this as someone trying
7622
      // to explicitly cancel the selection rather than the user
7623
      // letting go of the mouse button.
7624
      if (e) {
7625
        e_preventDefault(e);
7626
        display.input.focus();
7627
      }
7628
      off(display.wrapper.ownerDocument, "mousemove", move);
7629
      off(display.wrapper.ownerDocument, "mouseup", up);
18249 obado 7630
      doc.history.lastSelOrigin = null;
14283 obado 7631
    }
7632
 
7633
    var move = operation(cm, function (e) {
7634
      if (e.buttons === 0 || !e_button(e)) { done(e); }
7635
      else { extend(e); }
7636
    });
7637
    var up = operation(cm, done);
7638
    cm.state.selectingText = up;
7639
    on(display.wrapper.ownerDocument, "mousemove", move);
7640
    on(display.wrapper.ownerDocument, "mouseup", up);
7641
  }
7642
 
7643
  // Used when mouse-selecting to adjust the anchor to the proper side
7644
  // of a bidi jump depending on the visual position of the head.
15152 obado 7645
  function bidiSimplify(cm, range) {
7646
    var anchor = range.anchor;
7647
    var head = range.head;
14283 obado 7648
    var anchorLine = getLine(cm.doc, anchor.line);
15152 obado 7649
    if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
14283 obado 7650
    var order = getOrder(anchorLine);
15152 obado 7651
    if (!order) { return range }
14283 obado 7652
    var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
15152 obado 7653
    if (part.from != anchor.ch && part.to != anchor.ch) { return range }
14283 obado 7654
    var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
15152 obado 7655
    if (boundary == 0 || boundary == order.length) { return range }
14283 obado 7656
 
7657
    // Compute the relative visual position of the head compared to the
7658
    // anchor (<0 is to the left, >0 to the right)
7659
    var leftSide;
7660
    if (head.line != anchor.line) {
7661
      leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
7662
    } else {
7663
      var headIndex = getBidiPartAt(order, head.ch, head.sticky);
7664
      var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
7665
      if (headIndex == boundary - 1 || headIndex == boundary)
7666
        { leftSide = dir < 0; }
7667
      else
7668
        { leftSide = dir > 0; }
7669
    }
7670
 
7671
    var usePart = order[boundary + (leftSide ? -1 : 0)];
7672
    var from = leftSide == (usePart.level == 1);
7673
    var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
15152 obado 7674
    return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
14283 obado 7675
  }
7676
 
7677
 
7678
  // Determines whether an event happened in the gutter, and fires the
7679
  // handlers for the corresponding event.
7680
  function gutterEvent(cm, e, type, prevent) {
7681
    var mX, mY;
7682
    if (e.touches) {
7683
      mX = e.touches[0].clientX;
7684
      mY = e.touches[0].clientY;
7685
    } else {
7686
      try { mX = e.clientX; mY = e.clientY; }
15332 obado 7687
      catch(e$1) { return false }
14283 obado 7688
    }
7689
    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
7690
    if (prevent) { e_preventDefault(e); }
7691
 
7692
    var display = cm.display;
7693
    var lineBox = display.lineDiv.getBoundingClientRect();
7694
 
7695
    if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
7696
    mY -= lineBox.top - display.viewOffset;
7697
 
7698
    for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
7699
      var g = display.gutters.childNodes[i];
7700
      if (g && g.getBoundingClientRect().right >= mX) {
7701
        var line = lineAtHeight(cm.doc, mY);
7702
        var gutter = cm.display.gutterSpecs[i];
7703
        signal(cm, type, cm, line, gutter.className, e);
7704
        return e_defaultPrevented(e)
7705
      }
7706
    }
7707
  }
7708
 
7709
  function clickInGutter(cm, e) {
7710
    return gutterEvent(cm, e, "gutterClick", true)
7711
  }
7712
 
7713
  // CONTEXT MENU HANDLING
7714
 
7715
  // To make the context menu work, we need to briefly unhide the
7716
  // textarea (making it as unobtrusive as possible) to let the
7717
  // right-click take effect on it.
7718
  function onContextMenu(cm, e) {
7719
    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
7720
    if (signalDOMEvent(cm, e, "contextmenu")) { return }
7721
    if (!captureRightClick) { cm.display.input.onContextMenu(e); }
7722
  }
7723
 
7724
  function contextMenuInGutter(cm, e) {
7725
    if (!hasHandler(cm, "gutterContextMenu")) { return false }
7726
    return gutterEvent(cm, e, "gutterContextMenu", false)
7727
  }
7728
 
7729
  function themeChanged(cm) {
7730
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
7731
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
7732
    clearCaches(cm);
7733
  }
7734
 
7735
  var Init = {toString: function(){return "CodeMirror.Init"}};
7736
 
7737
  var defaults = {};
7738
  var optionHandlers = {};
7739
 
7740
  function defineOptions(CodeMirror) {
7741
    var optionHandlers = CodeMirror.optionHandlers;
7742
 
7743
    function option(name, deflt, handle, notOnInit) {
7744
      CodeMirror.defaults[name] = deflt;
7745
      if (handle) { optionHandlers[name] =
7746
        notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
7747
    }
7748
 
7749
    CodeMirror.defineOption = option;
7750
 
7751
    // Passed to option handlers when there is no old value.
7752
    CodeMirror.Init = Init;
7753
 
7754
    // These two are, on init, called from the constructor because they
7755
    // have to be initialized before the editor can start at all.
7756
    option("value", "", function (cm, val) { return cm.setValue(val); }, true);
7757
    option("mode", null, function (cm, val) {
7758
      cm.doc.modeOption = val;
7759
      loadMode(cm);
7760
    }, true);
7761
 
7762
    option("indentUnit", 2, loadMode, true);
7763
    option("indentWithTabs", false);
7764
    option("smartIndent", true);
7765
    option("tabSize", 4, function (cm) {
7766
      resetModeState(cm);
7767
      clearCaches(cm);
7768
      regChange(cm);
7769
    }, true);
7770
 
7771
    option("lineSeparator", null, function (cm, val) {
7772
      cm.doc.lineSep = val;
7773
      if (!val) { return }
7774
      var newBreaks = [], lineNo = cm.doc.first;
7775
      cm.doc.iter(function (line) {
7776
        for (var pos = 0;;) {
7777
          var found = line.text.indexOf(val, pos);
7778
          if (found == -1) { break }
7779
          pos = found + val.length;
7780
          newBreaks.push(Pos(lineNo, found));
7781
        }
7782
        lineNo++;
7783
      });
7784
      for (var i = newBreaks.length - 1; i >= 0; i--)
7785
        { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
7786
    });
17702 obado 7787
    option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
14283 obado 7788
      cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
7789
      if (old != Init) { cm.refresh(); }
7790
    });
7791
    option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
7792
    option("electricChars", true);
7793
    option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
7794
      throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
7795
    }, true);
7796
    option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
7797
    option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
7798
    option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
7799
    option("rtlMoveVisually", !windows);
7800
    option("wholeLineUpdateBefore", true);
7801
 
7802
    option("theme", "default", function (cm) {
7803
      themeChanged(cm);
7804
      updateGutters(cm);
7805
    }, true);
7806
    option("keyMap", "default", function (cm, val, old) {
7807
      var next = getKeyMap(val);
7808
      var prev = old != Init && getKeyMap(old);
7809
      if (prev && prev.detach) { prev.detach(cm, next); }
7810
      if (next.attach) { next.attach(cm, prev || null); }
7811
    });
7812
    option("extraKeys", null);
7813
    option("configureMouse", null);
7814
 
7815
    option("lineWrapping", false, wrappingChanged, true);
7816
    option("gutters", [], function (cm, val) {
7817
      cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
7818
      updateGutters(cm);
7819
    }, true);
7820
    option("fixedGutter", true, function (cm, val) {
7821
      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
7822
      cm.refresh();
7823
    }, true);
7824
    option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
7825
    option("scrollbarStyle", "native", function (cm) {
7826
      initScrollbars(cm);
7827
      updateScrollbars(cm);
7828
      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
7829
      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
7830
    }, true);
7831
    option("lineNumbers", false, function (cm, val) {
7832
      cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
7833
      updateGutters(cm);
7834
    }, true);
7835
    option("firstLineNumber", 1, updateGutters, true);
7836
    option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
7837
    option("showCursorWhenSelecting", false, updateSelection, true);
7838
 
7839
    option("resetSelectionOnContextMenu", true);
7840
    option("lineWiseCopyCut", true);
7841
    option("pasteLinesPerSelection", true);
7842
    option("selectionsMayTouch", false);
7843
 
7844
    option("readOnly", false, function (cm, val) {
7845
      if (val == "nocursor") {
7846
        onBlur(cm);
7847
        cm.display.input.blur();
7848
      }
7849
      cm.display.input.readOnlyChanged(val);
7850
    });
15152 obado 7851
 
7852
    option("screenReaderLabel", null, function (cm, val) {
7853
      val = (val === '') ? null : val;
7854
      cm.display.input.screenReaderLabelChanged(val);
7855
    });
7856
 
14283 obado 7857
    option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
7858
    option("dragDrop", true, dragDropChanged);
7859
    option("allowDropFileTypes", null);
7860
 
7861
    option("cursorBlinkRate", 530);
7862
    option("cursorScrollMargin", 0);
7863
    option("cursorHeight", 1, updateSelection, true);
7864
    option("singleCursorHeightPerLine", true, updateSelection, true);
7865
    option("workTime", 100);
7866
    option("workDelay", 100);
7867
    option("flattenSpans", true, resetModeState, true);
7868
    option("addModeClass", false, resetModeState, true);
7869
    option("pollInterval", 100);
7870
    option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
7871
    option("historyEventDelay", 1250);
7872
    option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
7873
    option("maxHighlightLength", 10000, resetModeState, true);
7874
    option("moveInputWithCursor", true, function (cm, val) {
7875
      if (!val) { cm.display.input.resetPosition(); }
7876
    });
7877
 
7878
    option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
7879
    option("autofocus", null);
7880
    option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
7881
    option("phrases", null);
7882
  }
7883
 
7884
  function dragDropChanged(cm, value, old) {
7885
    var wasOn = old && old != Init;
7886
    if (!value != !wasOn) {
7887
      var funcs = cm.display.dragFunctions;
7888
      var toggle = value ? on : off;
7889
      toggle(cm.display.scroller, "dragstart", funcs.start);
7890
      toggle(cm.display.scroller, "dragenter", funcs.enter);
7891
      toggle(cm.display.scroller, "dragover", funcs.over);
7892
      toggle(cm.display.scroller, "dragleave", funcs.leave);
7893
      toggle(cm.display.scroller, "drop", funcs.drop);
7894
    }
7895
  }
7896
 
7897
  function wrappingChanged(cm) {
7898
    if (cm.options.lineWrapping) {
7899
      addClass(cm.display.wrapper, "CodeMirror-wrap");
7900
      cm.display.sizer.style.minWidth = "";
7901
      cm.display.sizerWidth = null;
7902
    } else {
7903
      rmClass(cm.display.wrapper, "CodeMirror-wrap");
7904
      findMaxLine(cm);
7905
    }
7906
    estimateLineHeights(cm);
7907
    regChange(cm);
7908
    clearCaches(cm);
7909
    setTimeout(function () { return updateScrollbars(cm); }, 100);
7910
  }
7911
 
7912
  // A CodeMirror instance represents an editor. This is the object
7913
  // that user code is usually dealing with.
7914
 
7915
  function CodeMirror(place, options) {
7916
    var this$1 = this;
7917
 
7918
    if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
7919
 
7920
    this.options = options = options ? copyObj(options) : {};
7921
    // Determine effective options based on given values and defaults.
7922
    copyObj(defaults, options, false);
7923
 
7924
    var doc = options.value;
7925
    if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
7926
    else if (options.mode) { doc.modeOption = options.mode; }
7927
    this.doc = doc;
7928
 
7929
    var input = new CodeMirror.inputStyles[options.inputStyle](this);
7930
    var display = this.display = new Display(place, doc, input, options);
7931
    display.wrapper.CodeMirror = this;
7932
    themeChanged(this);
7933
    if (options.lineWrapping)
7934
      { this.display.wrapper.className += " CodeMirror-wrap"; }
7935
    initScrollbars(this);
7936
 
7937
    this.state = {
7938
      keyMaps: [],  // stores maps added by addKeyMap
7939
      overlays: [], // highlighting overlays, as added by addOverlay
7940
      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
7941
      overwrite: false,
7942
      delayingBlurEvent: false,
7943
      focused: false,
7944
      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
7945
      pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
7946
      selectingText: false,
7947
      draggingText: false,
7948
      highlight: new Delayed(), // stores highlight worker timeout
7949
      keySeq: null,  // Unfinished key sequence
7950
      specialChars: null
7951
    };
7952
 
7953
    if (options.autofocus && !mobile) { display.input.focus(); }
7954
 
7955
    // Override magic textarea content restore that IE sometimes does
7956
    // on our hidden textarea on reload
7957
    if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
7958
 
7959
    registerEventHandlers(this);
7960
    ensureGlobalHandlers();
7961
 
7962
    startOperation(this);
7963
    this.curOp.forceUpdate = true;
7964
    attachDoc(this, doc);
7965
 
7966
    if ((options.autofocus && !mobile) || this.hasFocus())
16493 obado 7967
      { setTimeout(function () {
7968
        if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
7969
      }, 20); }
14283 obado 7970
    else
7971
      { onBlur(this); }
7972
 
7973
    for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
15152 obado 7974
      { optionHandlers[opt](this, options[opt], Init); } }
14283 obado 7975
    maybeUpdateLineNumberWidth(this);
7976
    if (options.finishInit) { options.finishInit(this); }
15152 obado 7977
    for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
14283 obado 7978
    endOperation(this);
7979
    // Suppress optimizelegibility in Webkit, since it breaks text
7980
    // measuring on line wrapping boundaries.
7981
    if (webkit && options.lineWrapping &&
7982
        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
7983
      { display.lineDiv.style.textRendering = "auto"; }
7984
  }
7985
 
7986
  // The default configuration options.
7987
  CodeMirror.defaults = defaults;
7988
  // Functions to run when options are changed.
7989
  CodeMirror.optionHandlers = optionHandlers;
7990
 
7991
  // Attach the necessary event handlers when initializing the editor
7992
  function registerEventHandlers(cm) {
7993
    var d = cm.display;
7994
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
7995
    // Older IE's will not fire a second mousedown for a double click
7996
    if (ie && ie_version < 11)
7997
      { on(d.scroller, "dblclick", operation(cm, function (e) {
7998
        if (signalDOMEvent(cm, e)) { return }
7999
        var pos = posFromMouse(cm, e);
8000
        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
8001
        e_preventDefault(e);
8002
        var word = cm.findWordAt(pos);
8003
        extendSelection(cm.doc, word.anchor, word.head);
8004
      })); }
8005
    else
8006
      { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
8007
    // Some browsers fire contextmenu *after* opening the menu, at
8008
    // which point we can't mess with it anymore. Context menu is
8009
    // handled in onMouseDown for these browsers.
8010
    on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
15152 obado 8011
    on(d.input.getField(), "contextmenu", function (e) {
8012
      if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
8013
    });
14283 obado 8014
 
8015
    // Used to suppress mouse event handling when a touch happens
8016
    var touchFinished, prevTouch = {end: 0};
8017
    function finishTouch() {
8018
      if (d.activeTouch) {
8019
        touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
8020
        prevTouch = d.activeTouch;
8021
        prevTouch.end = +new Date;
8022
      }
8023
    }
8024
    function isMouseLikeTouchEvent(e) {
8025
      if (e.touches.length != 1) { return false }
8026
      var touch = e.touches[0];
8027
      return touch.radiusX <= 1 && touch.radiusY <= 1
8028
    }
8029
    function farAway(touch, other) {
8030
      if (other.left == null) { return true }
8031
      var dx = other.left - touch.left, dy = other.top - touch.top;
8032
      return dx * dx + dy * dy > 20 * 20
8033
    }
8034
    on(d.scroller, "touchstart", function (e) {
8035
      if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
8036
        d.input.ensurePolled();
8037
        clearTimeout(touchFinished);
8038
        var now = +new Date;
8039
        d.activeTouch = {start: now, moved: false,
8040
                         prev: now - prevTouch.end <= 300 ? prevTouch : null};
8041
        if (e.touches.length == 1) {
8042
          d.activeTouch.left = e.touches[0].pageX;
8043
          d.activeTouch.top = e.touches[0].pageY;
8044
        }
8045
      }
8046
    });
8047
    on(d.scroller, "touchmove", function () {
8048
      if (d.activeTouch) { d.activeTouch.moved = true; }
8049
    });
8050
    on(d.scroller, "touchend", function (e) {
8051
      var touch = d.activeTouch;
8052
      if (touch && !eventInWidget(d, e) && touch.left != null &&
8053
          !touch.moved && new Date - touch.start < 300) {
8054
        var pos = cm.coordsChar(d.activeTouch, "page"), range;
8055
        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
8056
          { range = new Range(pos, pos); }
8057
        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
8058
          { range = cm.findWordAt(pos); }
8059
        else // Triple tap
8060
          { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
8061
        cm.setSelection(range.anchor, range.head);
8062
        cm.focus();
8063
        e_preventDefault(e);
8064
      }
8065
      finishTouch();
8066
    });
8067
    on(d.scroller, "touchcancel", finishTouch);
8068
 
8069
    // Sync scrolling between fake scrollbars and real scrollable
8070
    // area, ensure viewport is updated when scrolling.
8071
    on(d.scroller, "scroll", function () {
8072
      if (d.scroller.clientHeight) {
8073
        updateScrollTop(cm, d.scroller.scrollTop);
8074
        setScrollLeft(cm, d.scroller.scrollLeft, true);
8075
        signal(cm, "scroll", cm);
8076
      }
8077
    });
8078
 
8079
    // Listen to wheel events in order to try and update the viewport on time.
8080
    on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
8081
    on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
8082
 
8083
    // Prevent wrapper from ever scrolling
8084
    on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
8085
 
8086
    d.dragFunctions = {
8087
      enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
8088
      over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
8089
      start: function (e) { return onDragStart(cm, e); },
8090
      drop: operation(cm, onDrop),
8091
      leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
8092
    };
8093
 
8094
    var inp = d.input.getField();
8095
    on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
8096
    on(inp, "keydown", operation(cm, onKeyDown));
8097
    on(inp, "keypress", operation(cm, onKeyPress));
8098
    on(inp, "focus", function (e) { return onFocus(cm, e); });
8099
    on(inp, "blur", function (e) { return onBlur(cm, e); });
8100
  }
8101
 
8102
  var initHooks = [];
8103
  CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
8104
 
8105
  // Indent the given line. The how parameter can be "smart",
8106
  // "add"/null, "subtract", or "prev". When aggressive is false
8107
  // (typically set to true for forced single-line indents), empty
8108
  // lines are not indented, and places where the mode returns Pass
8109
  // are left alone.
8110
  function indentLine(cm, n, how, aggressive) {
8111
    var doc = cm.doc, state;
8112
    if (how == null) { how = "add"; }
8113
    if (how == "smart") {
8114
      // Fall back to "prev" when the mode doesn't have an indentation
8115
      // method.
8116
      if (!doc.mode.indent) { how = "prev"; }
8117
      else { state = getContextBefore(cm, n).state; }
8118
    }
8119
 
8120
    var tabSize = cm.options.tabSize;
8121
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
8122
    if (line.stateAfter) { line.stateAfter = null; }
8123
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
8124
    if (!aggressive && !/\S/.test(line.text)) {
8125
      indentation = 0;
8126
      how = "not";
8127
    } else if (how == "smart") {
8128
      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
8129
      if (indentation == Pass || indentation > 150) {
8130
        if (!aggressive) { return }
8131
        how = "prev";
8132
      }
8133
    }
8134
    if (how == "prev") {
8135
      if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
8136
      else { indentation = 0; }
8137
    } else if (how == "add") {
8138
      indentation = curSpace + cm.options.indentUnit;
8139
    } else if (how == "subtract") {
8140
      indentation = curSpace - cm.options.indentUnit;
8141
    } else if (typeof how == "number") {
8142
      indentation = curSpace + how;
8143
    }
8144
    indentation = Math.max(0, indentation);
8145
 
8146
    var indentString = "", pos = 0;
8147
    if (cm.options.indentWithTabs)
8148
      { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
8149
    if (pos < indentation) { indentString += spaceStr(indentation - pos); }
8150
 
8151
    if (indentString != curSpaceString) {
8152
      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
8153
      line.stateAfter = null;
8154
      return true
8155
    } else {
8156
      // Ensure that, if the cursor was in the whitespace at the start
8157
      // of the line, it is moved to the end of that space.
8158
      for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
8159
        var range = doc.sel.ranges[i$1];
8160
        if (range.head.line == n && range.head.ch < curSpaceString.length) {
8161
          var pos$1 = Pos(n, curSpaceString.length);
8162
          replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
8163
          break
8164
        }
8165
      }
8166
    }
8167
  }
8168
 
8169
  // This will be set to a {lineWise: bool, text: [string]} object, so
8170
  // that, when pasting, we know what kind of selections the copied
8171
  // text was made out of.
8172
  var lastCopied = null;
8173
 
8174
  function setLastCopied(newLastCopied) {
8175
    lastCopied = newLastCopied;
8176
  }
8177
 
8178
  function applyTextInput(cm, inserted, deleted, sel, origin) {
8179
    var doc = cm.doc;
8180
    cm.display.shift = false;
8181
    if (!sel) { sel = doc.sel; }
8182
 
8183
    var recent = +new Date - 200;
8184
    var paste = origin == "paste" || cm.state.pasteIncoming > recent;
8185
    var textLines = splitLinesAuto(inserted), multiPaste = null;
8186
    // When pasting N lines into N selections, insert one line per selection
8187
    if (paste && sel.ranges.length > 1) {
8188
      if (lastCopied && lastCopied.text.join("\n") == inserted) {
8189
        if (sel.ranges.length % lastCopied.text.length == 0) {
8190
          multiPaste = [];
8191
          for (var i = 0; i < lastCopied.text.length; i++)
8192
            { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
8193
        }
8194
      } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
8195
        multiPaste = map(textLines, function (l) { return [l]; });
8196
      }
8197
    }
8198
 
8199
    var updateInput = cm.curOp.updateInput;
8200
    // Normal behavior is to insert the new text into every selection
8201
    for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
15152 obado 8202
      var range = sel.ranges[i$1];
8203
      var from = range.from(), to = range.to();
8204
      if (range.empty()) {
14283 obado 8205
        if (deleted && deleted > 0) // Handle deletion
8206
          { from = Pos(from.line, from.ch - deleted); }
8207
        else if (cm.state.overwrite && !paste) // Handle overwrite
8208
          { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
15332 obado 8209
        else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
14283 obado 8210
          { from = to = Pos(from.line, 0); }
8211
      }
8212
      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
8213
                         origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
8214
      makeChange(cm.doc, changeEvent);
8215
      signalLater(cm, "inputRead", cm, changeEvent);
8216
    }
8217
    if (inserted && !paste)
8218
      { triggerElectric(cm, inserted); }
8219
 
8220
    ensureCursorVisible(cm);
8221
    if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
8222
    cm.curOp.typing = true;
8223
    cm.state.pasteIncoming = cm.state.cutIncoming = -1;
8224
  }
8225
 
8226
  function handlePaste(e, cm) {
8227
    var pasted = e.clipboardData && e.clipboardData.getData("Text");
8228
    if (pasted) {
8229
      e.preventDefault();
16859 obado 8230
      if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
14283 obado 8231
        { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
8232
      return true
8233
    }
8234
  }
8235
 
8236
  function triggerElectric(cm, inserted) {
8237
    // When an 'electric' character is inserted, immediately trigger a reindent
8238
    if (!cm.options.electricChars || !cm.options.smartIndent) { return }
8239
    var sel = cm.doc.sel;
8240
 
8241
    for (var i = sel.ranges.length - 1; i >= 0; i--) {
15152 obado 8242
      var range = sel.ranges[i];
8243
      if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
8244
      var mode = cm.getModeAt(range.head);
14283 obado 8245
      var indented = false;
8246
      if (mode.electricChars) {
8247
        for (var j = 0; j < mode.electricChars.length; j++)
8248
          { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
15152 obado 8249
            indented = indentLine(cm, range.head.line, "smart");
14283 obado 8250
            break
8251
          } }
8252
      } else if (mode.electricInput) {
15152 obado 8253
        if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
8254
          { indented = indentLine(cm, range.head.line, "smart"); }
14283 obado 8255
      }
15152 obado 8256
      if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
14283 obado 8257
    }
8258
  }
8259
 
8260
  function copyableRanges(cm) {
8261
    var text = [], ranges = [];
8262
    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
8263
      var line = cm.doc.sel.ranges[i].head.line;
8264
      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
8265
      ranges.push(lineRange);
8266
      text.push(cm.getRange(lineRange.anchor, lineRange.head));
8267
    }
8268
    return {text: text, ranges: ranges}
8269
  }
8270
 
8271
  function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
17702 obado 8272
    field.setAttribute("autocorrect", autocorrect ? "on" : "off");
8273
    field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
14283 obado 8274
    field.setAttribute("spellcheck", !!spellcheck);
8275
  }
8276
 
8277
  function hiddenTextarea() {
16493 obado 8278
    var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
14283 obado 8279
    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
8280
    // The textarea is kept positioned near the cursor to prevent the
8281
    // fact that it'll be scrolled into view on input from scrolling
8282
    // our fake cursor out of view. On webkit, when wrap=off, paste is
8283
    // very slow. So make the area wide instead.
8284
    if (webkit) { te.style.width = "1000px"; }
8285
    else { te.setAttribute("wrap", "off"); }
8286
    // If border: 0; -- iOS fails to open keyboard (issue #1287)
8287
    if (ios) { te.style.border = "1px solid black"; }
8288
    return div
8289
  }
8290
 
8291
  // The publicly visible API. Note that methodOp(f) means
8292
  // 'wrap f in an operation, performed on its `this` parameter'.
8293
 
8294
  // This is not the complete set of editor methods. Most of the
8295
  // methods defined on the Doc type are also injected into
8296
  // CodeMirror.prototype, for backwards compatibility and
8297
  // convenience.
8298
 
8299
  function addEditorMethods(CodeMirror) {
8300
    var optionHandlers = CodeMirror.optionHandlers;
8301
 
8302
    var helpers = CodeMirror.helpers = {};
8303
 
8304
    CodeMirror.prototype = {
8305
      constructor: CodeMirror,
17702 obado 8306
      focus: function(){win(this).focus(); this.display.input.focus();},
14283 obado 8307
 
8308
      setOption: function(option, value) {
8309
        var options = this.options, old = options[option];
8310
        if (options[option] == value && option != "mode") { return }
8311
        options[option] = value;
8312
        if (optionHandlers.hasOwnProperty(option))
8313
          { operation(this, optionHandlers[option])(this, value, old); }
8314
        signal(this, "optionChange", this, option);
8315
      },
8316
 
8317
      getOption: function(option) {return this.options[option]},
8318
      getDoc: function() {return this.doc},
8319
 
15152 obado 8320
      addKeyMap: function(map, bottom) {
8321
        this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
14283 obado 8322
      },
15152 obado 8323
      removeKeyMap: function(map) {
14283 obado 8324
        var maps = this.state.keyMaps;
8325
        for (var i = 0; i < maps.length; ++i)
15152 obado 8326
          { if (maps[i] == map || maps[i].name == map) {
14283 obado 8327
            maps.splice(i, 1);
8328
            return true
8329
          } }
8330
      },
8331
 
8332
      addOverlay: methodOp(function(spec, options) {
8333
        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
8334
        if (mode.startState) { throw new Error("Overlays may not be stateful.") }
8335
        insertSorted(this.state.overlays,
8336
                     {mode: mode, modeSpec: spec, opaque: options && options.opaque,
8337
                      priority: (options && options.priority) || 0},
8338
                     function (overlay) { return overlay.priority; });
8339
        this.state.modeGen++;
8340
        regChange(this);
8341
      }),
8342
      removeOverlay: methodOp(function(spec) {
8343
        var overlays = this.state.overlays;
8344
        for (var i = 0; i < overlays.length; ++i) {
8345
          var cur = overlays[i].modeSpec;
8346
          if (cur == spec || typeof spec == "string" && cur.name == spec) {
8347
            overlays.splice(i, 1);
15152 obado 8348
            this.state.modeGen++;
8349
            regChange(this);
14283 obado 8350
            return
8351
          }
8352
        }
8353
      }),
8354
 
8355
      indentLine: methodOp(function(n, dir, aggressive) {
8356
        if (typeof dir != "string" && typeof dir != "number") {
8357
          if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
8358
          else { dir = dir ? "add" : "subtract"; }
8359
        }
8360
        if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
8361
      }),
8362
      indentSelection: methodOp(function(how) {
8363
        var ranges = this.doc.sel.ranges, end = -1;
8364
        for (var i = 0; i < ranges.length; i++) {
15152 obado 8365
          var range = ranges[i];
8366
          if (!range.empty()) {
8367
            var from = range.from(), to = range.to();
14283 obado 8368
            var start = Math.max(end, from.line);
15152 obado 8369
            end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
14283 obado 8370
            for (var j = start; j < end; ++j)
15152 obado 8371
              { indentLine(this, j, how); }
8372
            var newRanges = this.doc.sel.ranges;
14283 obado 8373
            if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
15152 obado 8374
              { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
8375
          } else if (range.head.line > end) {
8376
            indentLine(this, range.head.line, how, true);
8377
            end = range.head.line;
8378
            if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
14283 obado 8379
          }
8380
        }
8381
      }),
8382
 
8383
      // Fetch the parser token for a given character. Useful for hacks
8384
      // that want to inspect the mode state (say, for completion).
8385
      getTokenAt: function(pos, precise) {
8386
        return takeToken(this, pos, precise)
8387
      },
8388
 
8389
      getLineTokens: function(line, precise) {
8390
        return takeToken(this, Pos(line), precise, true)
8391
      },
8392
 
8393
      getTokenTypeAt: function(pos) {
8394
        pos = clipPos(this.doc, pos);
8395
        var styles = getLineStyles(this, getLine(this.doc, pos.line));
8396
        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
8397
        var type;
8398
        if (ch == 0) { type = styles[2]; }
8399
        else { for (;;) {
8400
          var mid = (before + after) >> 1;
8401
          if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
8402
          else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
8403
          else { type = styles[mid * 2 + 2]; break }
8404
        } }
8405
        var cut = type ? type.indexOf("overlay ") : -1;
8406
        return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
8407
      },
8408
 
8409
      getModeAt: function(pos) {
8410
        var mode = this.doc.mode;
8411
        if (!mode.innerMode) { return mode }
8412
        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
8413
      },
8414
 
8415
      getHelper: function(pos, type) {
8416
        return this.getHelpers(pos, type)[0]
8417
      },
8418
 
8419
      getHelpers: function(pos, type) {
8420
        var found = [];
8421
        if (!helpers.hasOwnProperty(type)) { return found }
8422
        var help = helpers[type], mode = this.getModeAt(pos);
8423
        if (typeof mode[type] == "string") {
8424
          if (help[mode[type]]) { found.push(help[mode[type]]); }
8425
        } else if (mode[type]) {
8426
          for (var i = 0; i < mode[type].length; i++) {
8427
            var val = help[mode[type][i]];
8428
            if (val) { found.push(val); }
8429
          }
8430
        } else if (mode.helperType && help[mode.helperType]) {
8431
          found.push(help[mode.helperType]);
8432
        } else if (help[mode.name]) {
8433
          found.push(help[mode.name]);
8434
        }
8435
        for (var i$1 = 0; i$1 < help._global.length; i$1++) {
8436
          var cur = help._global[i$1];
15152 obado 8437
          if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
14283 obado 8438
            { found.push(cur.val); }
8439
        }
8440
        return found
8441
      },
8442
 
8443
      getStateAfter: function(line, precise) {
8444
        var doc = this.doc;
8445
        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
8446
        return getContextBefore(this, line + 1, precise).state
8447
      },
8448
 
8449
      cursorCoords: function(start, mode) {
15152 obado 8450
        var pos, range = this.doc.sel.primary();
8451
        if (start == null) { pos = range.head; }
14283 obado 8452
        else if (typeof start == "object") { pos = clipPos(this.doc, start); }
15152 obado 8453
        else { pos = start ? range.from() : range.to(); }
14283 obado 8454
        return cursorCoords(this, pos, mode || "page")
8455
      },
8456
 
8457
      charCoords: function(pos, mode) {
8458
        return charCoords(this, clipPos(this.doc, pos), mode || "page")
8459
      },
8460
 
8461
      coordsChar: function(coords, mode) {
8462
        coords = fromCoordSystem(this, coords, mode || "page");
8463
        return coordsChar(this, coords.left, coords.top)
8464
      },
8465
 
8466
      lineAtHeight: function(height, mode) {
8467
        height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
8468
        return lineAtHeight(this.doc, height + this.display.viewOffset)
8469
      },
8470
      heightAtLine: function(line, mode, includeWidgets) {
8471
        var end = false, lineObj;
8472
        if (typeof line == "number") {
8473
          var last = this.doc.first + this.doc.size - 1;
8474
          if (line < this.doc.first) { line = this.doc.first; }
8475
          else if (line > last) { line = last; end = true; }
8476
          lineObj = getLine(this.doc, line);
8477
        } else {
8478
          lineObj = line;
8479
        }
8480
        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
8481
          (end ? this.doc.height - heightAtLine(lineObj) : 0)
8482
      },
8483
 
8484
      defaultTextHeight: function() { return textHeight(this.display) },
8485
      defaultCharWidth: function() { return charWidth(this.display) },
8486
 
8487
      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8488
 
8489
      addWidget: function(pos, node, scroll, vert, horiz) {
8490
        var display = this.display;
8491
        pos = cursorCoords(this, clipPos(this.doc, pos));
8492
        var top = pos.bottom, left = pos.left;
8493
        node.style.position = "absolute";
8494
        node.setAttribute("cm-ignore-events", "true");
8495
        this.display.input.setUneditable(node);
8496
        display.sizer.appendChild(node);
8497
        if (vert == "over") {
8498
          top = pos.top;
8499
        } else if (vert == "above" || vert == "near") {
8500
          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
8501
          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
8502
          // Default to positioning above (if specified and possible); otherwise default to positioning below
8503
          if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
8504
            { top = pos.top - node.offsetHeight; }
8505
          else if (pos.bottom + node.offsetHeight <= vspace)
8506
            { top = pos.bottom; }
8507
          if (left + node.offsetWidth > hspace)
8508
            { left = hspace - node.offsetWidth; }
8509
        }
8510
        node.style.top = top + "px";
8511
        node.style.left = node.style.right = "";
8512
        if (horiz == "right") {
8513
          left = display.sizer.clientWidth - node.offsetWidth;
8514
          node.style.right = "0px";
8515
        } else {
8516
          if (horiz == "left") { left = 0; }
8517
          else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
8518
          node.style.left = left + "px";
8519
        }
8520
        if (scroll)
8521
          { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
8522
      },
8523
 
8524
      triggerOnKeyDown: methodOp(onKeyDown),
8525
      triggerOnKeyPress: methodOp(onKeyPress),
8526
      triggerOnKeyUp: onKeyUp,
8527
      triggerOnMouseDown: methodOp(onMouseDown),
8528
 
8529
      execCommand: function(cmd) {
8530
        if (commands.hasOwnProperty(cmd))
8531
          { return commands[cmd].call(null, this) }
8532
      },
8533
 
8534
      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8535
 
8536
      findPosH: function(from, amount, unit, visually) {
8537
        var dir = 1;
8538
        if (amount < 0) { dir = -1; amount = -amount; }
8539
        var cur = clipPos(this.doc, from);
8540
        for (var i = 0; i < amount; ++i) {
15152 obado 8541
          cur = findPosH(this.doc, cur, dir, unit, visually);
14283 obado 8542
          if (cur.hitSide) { break }
8543
        }
8544
        return cur
8545
      },
8546
 
8547
      moveH: methodOp(function(dir, unit) {
8548
        var this$1 = this;
8549
 
15152 obado 8550
        this.extendSelectionsBy(function (range) {
8551
          if (this$1.display.shift || this$1.doc.extend || range.empty())
8552
            { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
14283 obado 8553
          else
15152 obado 8554
            { return dir < 0 ? range.from() : range.to() }
14283 obado 8555
        }, sel_move);
8556
      }),
8557
 
8558
      deleteH: methodOp(function(dir, unit) {
8559
        var sel = this.doc.sel, doc = this.doc;
8560
        if (sel.somethingSelected())
8561
          { doc.replaceSelection("", null, "+delete"); }
8562
        else
15152 obado 8563
          { deleteNearSelection(this, function (range) {
8564
            var other = findPosH(doc, range.head, dir, unit, false);
8565
            return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
14283 obado 8566
          }); }
8567
      }),
8568
 
8569
      findPosV: function(from, amount, unit, goalColumn) {
8570
        var dir = 1, x = goalColumn;
8571
        if (amount < 0) { dir = -1; amount = -amount; }
8572
        var cur = clipPos(this.doc, from);
8573
        for (var i = 0; i < amount; ++i) {
15152 obado 8574
          var coords = cursorCoords(this, cur, "div");
14283 obado 8575
          if (x == null) { x = coords.left; }
8576
          else { coords.left = x; }
15152 obado 8577
          cur = findPosV(this, coords, dir, unit);
14283 obado 8578
          if (cur.hitSide) { break }
8579
        }
8580
        return cur
8581
      },
8582
 
8583
      moveV: methodOp(function(dir, unit) {
8584
        var this$1 = this;
8585
 
8586
        var doc = this.doc, goals = [];
8587
        var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
15152 obado 8588
        doc.extendSelectionsBy(function (range) {
14283 obado 8589
          if (collapse)
15152 obado 8590
            { return dir < 0 ? range.from() : range.to() }
8591
          var headPos = cursorCoords(this$1, range.head, "div");
8592
          if (range.goalColumn != null) { headPos.left = range.goalColumn; }
14283 obado 8593
          goals.push(headPos.left);
8594
          var pos = findPosV(this$1, headPos, dir, unit);
15152 obado 8595
          if (unit == "page" && range == doc.sel.primary())
14283 obado 8596
            { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
8597
          return pos
8598
        }, sel_move);
8599
        if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
8600
          { doc.sel.ranges[i].goalColumn = goals[i]; } }
8601
      }),
8602
 
8603
      // Find the word at the given position (as returned by coordsChar).
8604
      findWordAt: function(pos) {
8605
        var doc = this.doc, line = getLine(doc, pos.line).text;
8606
        var start = pos.ch, end = pos.ch;
8607
        if (line) {
8608
          var helper = this.getHelper(pos, "wordChars");
8609
          if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
8610
          var startChar = line.charAt(start);
8611
          var check = isWordChar(startChar, helper)
8612
            ? function (ch) { return isWordChar(ch, helper); }
8613
            : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
8614
            : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
8615
          while (start > 0 && check(line.charAt(start - 1))) { --start; }
8616
          while (end < line.length && check(line.charAt(end))) { ++end; }
8617
        }
8618
        return new Range(Pos(pos.line, start), Pos(pos.line, end))
8619
      },
8620
 
8621
      toggleOverwrite: function(value) {
8622
        if (value != null && value == this.state.overwrite) { return }
8623
        if (this.state.overwrite = !this.state.overwrite)
8624
          { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8625
        else
8626
          { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8627
 
8628
        signal(this, "overwriteToggle", this, this.state.overwrite);
8629
      },
18249 obado 8630
      hasFocus: function() { return this.display.input.getField() == activeElt(root(this)) },
14283 obado 8631
      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
8632
 
8633
      scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
8634
      getScrollInfo: function() {
8635
        var scroller = this.display.scroller;
8636
        return {left: scroller.scrollLeft, top: scroller.scrollTop,
8637
                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
8638
                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
8639
                clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
8640
      },
8641
 
15152 obado 8642
      scrollIntoView: methodOp(function(range, margin) {
8643
        if (range == null) {
8644
          range = {from: this.doc.sel.primary().head, to: null};
14283 obado 8645
          if (margin == null) { margin = this.options.cursorScrollMargin; }
15152 obado 8646
        } else if (typeof range == "number") {
8647
          range = {from: Pos(range, 0), to: null};
8648
        } else if (range.from == null) {
8649
          range = {from: range, to: null};
14283 obado 8650
        }
15152 obado 8651
        if (!range.to) { range.to = range.from; }
8652
        range.margin = margin || 0;
14283 obado 8653
 
15152 obado 8654
        if (range.from.line != null) {
8655
          scrollToRange(this, range);
14283 obado 8656
        } else {
15152 obado 8657
          scrollToCoordsRange(this, range.from, range.to, range.margin);
14283 obado 8658
        }
8659
      }),
8660
 
8661
      setSize: methodOp(function(width, height) {
8662
        var this$1 = this;
8663
 
8664
        var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
8665
        if (width != null) { this.display.wrapper.style.width = interpret(width); }
8666
        if (height != null) { this.display.wrapper.style.height = interpret(height); }
8667
        if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
15152 obado 8668
        var lineNo = this.display.viewFrom;
8669
        this.doc.iter(lineNo, this.display.viewTo, function (line) {
14283 obado 8670
          if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
15152 obado 8671
            { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
8672
          ++lineNo;
14283 obado 8673
        });
8674
        this.curOp.forceUpdate = true;
8675
        signal(this, "refresh", this);
8676
      }),
8677
 
8678
      operation: function(f){return runInOp(this, f)},
8679
      startOperation: function(){return startOperation(this)},
8680
      endOperation: function(){return endOperation(this)},
8681
 
8682
      refresh: methodOp(function() {
8683
        var oldHeight = this.display.cachedTextHeight;
8684
        regChange(this);
8685
        this.curOp.forceUpdate = true;
8686
        clearCaches(this);
8687
        scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
8688
        updateGutterSpace(this.display);
15152 obado 8689
        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
14283 obado 8690
          { estimateLineHeights(this); }
8691
        signal(this, "refresh", this);
8692
      }),
8693
 
8694
      swapDoc: methodOp(function(doc) {
8695
        var old = this.doc;
8696
        old.cm = null;
8697
        // Cancel the current text selection if any (#5821)
8698
        if (this.state.selectingText) { this.state.selectingText(); }
8699
        attachDoc(this, doc);
8700
        clearCaches(this);
8701
        this.display.input.reset();
8702
        scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
8703
        this.curOp.forceScroll = true;
8704
        signalLater(this, "swapDoc", this, old);
8705
        return old
8706
      }),
8707
 
8708
      phrase: function(phraseText) {
8709
        var phrases = this.options.phrases;
8710
        return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
8711
      },
8712
 
8713
      getInputField: function(){return this.display.input.getField()},
8714
      getWrapperElement: function(){return this.display.wrapper},
8715
      getScrollerElement: function(){return this.display.scroller},
8716
      getGutterElement: function(){return this.display.gutters}
8717
    };
8718
    eventMixin(CodeMirror);
8719
 
8720
    CodeMirror.registerHelper = function(type, name, value) {
8721
      if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
8722
      helpers[type][name] = value;
8723
    };
8724
    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
8725
      CodeMirror.registerHelper(type, name, value);
8726
      helpers[type]._global.push({pred: predicate, val: value});
8727
    };
8728
  }
8729
 
8730
  // Used for horizontal relative motion. Dir is -1 or 1 (left or
16493 obado 8731
  // right), unit can be "codepoint", "char", "column" (like char, but
8732
  // doesn't cross line boundaries), "word" (across next word), or
8733
  // "group" (to the start of next group of word or
8734
  // non-word-non-whitespace chars). The visually param controls
8735
  // whether, in right-to-left text, direction 1 means to move towards
8736
  // the next index in the string, or towards the character to the right
8737
  // of the current position. The resulting position will have a
8738
  // hitSide=true property if it reached the end of the document.
14283 obado 8739
  function findPosH(doc, pos, dir, unit, visually) {
8740
    var oldPos = pos;
8741
    var origDir = dir;
8742
    var lineObj = getLine(doc, pos.line);
15152 obado 8743
    var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
14283 obado 8744
    function findNextLine() {
15152 obado 8745
      var l = pos.line + lineDir;
14283 obado 8746
      if (l < doc.first || l >= doc.first + doc.size) { return false }
8747
      pos = new Pos(l, pos.ch, pos.sticky);
8748
      return lineObj = getLine(doc, l)
8749
    }
8750
    function moveOnce(boundToLine) {
8751
      var next;
16493 obado 8752
      if (unit == "codepoint") {
8753
        var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
8754
        if (isNaN(ch)) {
8755
          next = null;
8756
        } else {
8757
          var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
8758
          next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
8759
        }
8760
      } else if (visually) {
14283 obado 8761
        next = moveVisually(doc.cm, lineObj, pos, dir);
8762
      } else {
8763
        next = moveLogically(lineObj, pos, dir);
8764
      }
8765
      if (next == null) {
8766
        if (!boundToLine && findNextLine())
15152 obado 8767
          { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
14283 obado 8768
        else
8769
          { return false }
8770
      } else {
8771
        pos = next;
8772
      }
8773
      return true
8774
    }
8775
 
16493 obado 8776
    if (unit == "char" || unit == "codepoint") {
14283 obado 8777
      moveOnce();
8778
    } else if (unit == "column") {
8779
      moveOnce(true);
8780
    } else if (unit == "word" || unit == "group") {
8781
      var sawType = null, group = unit == "group";
8782
      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
8783
      for (var first = true;; first = false) {
8784
        if (dir < 0 && !moveOnce(!first)) { break }
8785
        var cur = lineObj.text.charAt(pos.ch) || "\n";
8786
        var type = isWordChar(cur, helper) ? "w"
8787
          : group && cur == "\n" ? "n"
8788
          : !group || /\s/.test(cur) ? null
8789
          : "p";
8790
        if (group && !first && !type) { type = "s"; }
8791
        if (sawType && sawType != type) {
8792
          if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
8793
          break
8794
        }
8795
 
8796
        if (type) { sawType = type; }
8797
        if (dir > 0 && !moveOnce(!first)) { break }
8798
      }
8799
    }
8800
    var result = skipAtomic(doc, pos, oldPos, origDir, true);
8801
    if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8802
    return result
8803
  }
8804
 
8805
  // For relative vertical movement. Dir may be -1 or 1. Unit can be
8806
  // "page" or "line". The resulting position will have a hitSide=true
8807
  // property if it reached the end of the document.
8808
  function findPosV(cm, pos, dir, unit) {
8809
    var doc = cm.doc, x = pos.left, y;
8810
    if (unit == "page") {
17702 obado 8811
      var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
14283 obado 8812
      var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
8813
      y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
8814
 
8815
    } else if (unit == "line") {
8816
      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8817
    }
8818
    var target;
8819
    for (;;) {
8820
      target = coordsChar(cm, x, y);
8821
      if (!target.outside) { break }
8822
      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
8823
      y += dir * 5;
8824
    }
8825
    return target
8826
  }
8827
 
8828
  // CONTENTEDITABLE INPUT STYLE
8829
 
8830
  var ContentEditableInput = function(cm) {
8831
    this.cm = cm;
8832
    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
8833
    this.polling = new Delayed();
8834
    this.composing = null;
8835
    this.gracePeriod = false;
8836
    this.readDOMTimeout = null;
8837
  };
8838
 
8839
  ContentEditableInput.prototype.init = function (display) {
8840
      var this$1 = this;
8841
 
8842
    var input = this, cm = input.cm;
8843
    var div = input.div = display.lineDiv;
16493 obado 8844
    div.contentEditable = true;
14283 obado 8845
    disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
8846
 
15152 obado 8847
    function belongsToInput(e) {
8848
      for (var t = e.target; t; t = t.parentNode) {
8849
        if (t == div) { return true }
8850
        if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
8851
      }
8852
      return false
8853
    }
8854
 
14283 obado 8855
    on(div, "paste", function (e) {
15152 obado 8856
      if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
14283 obado 8857
      // IE doesn't fire input events, so we schedule a read for the pasted content in this way
8858
      if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
8859
    });
8860
 
8861
    on(div, "compositionstart", function (e) {
8862
      this$1.composing = {data: e.data, done: false};
8863
    });
8864
    on(div, "compositionupdate", function (e) {
8865
      if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
8866
    });
8867
    on(div, "compositionend", function (e) {
8868
      if (this$1.composing) {
8869
        if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
8870
        this$1.composing.done = true;
8871
      }
8872
    });
8873
 
8874
    on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8875
 
8876
    on(div, "input", function () {
8877
      if (!this$1.composing) { this$1.readFromDOMSoon(); }
8878
    });
8879
 
8880
    function onCopyCut(e) {
15152 obado 8881
      if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
14283 obado 8882
      if (cm.somethingSelected()) {
8883
        setLastCopied({lineWise: false, text: cm.getSelections()});
8884
        if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
8885
      } else if (!cm.options.lineWiseCopyCut) {
8886
        return
8887
      } else {
8888
        var ranges = copyableRanges(cm);
8889
        setLastCopied({lineWise: true, text: ranges.text});
8890
        if (e.type == "cut") {
8891
          cm.operation(function () {
8892
            cm.setSelections(ranges.ranges, 0, sel_dontScroll);
8893
            cm.replaceSelection("", null, "cut");
8894
          });
8895
        }
8896
      }
8897
      if (e.clipboardData) {
8898
        e.clipboardData.clearData();
8899
        var content = lastCopied.text.join("\n");
8900
        // iOS exposes the clipboard API, but seems to discard content inserted into it
8901
        e.clipboardData.setData("Text", content);
8902
        if (e.clipboardData.getData("Text") == content) {
8903
          e.preventDefault();
8904
          return
8905
        }
8906
      }
8907
      // Old-fashioned briefly-focus-a-textarea hack
8908
      var kludge = hiddenTextarea(), te = kludge.firstChild;
17702 obado 8909
      disableBrowserMagic(te);
14283 obado 8910
      cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
8911
      te.value = lastCopied.text.join("\n");
18249 obado 8912
      var hadFocus = activeElt(rootNode(div));
14283 obado 8913
      selectInput(te);
8914
      setTimeout(function () {
8915
        cm.display.lineSpace.removeChild(kludge);
8916
        hadFocus.focus();
8917
        if (hadFocus == div) { input.showPrimarySelection(); }
8918
      }, 50);
8919
    }
8920
    on(div, "copy", onCopyCut);
8921
    on(div, "cut", onCopyCut);
8922
  };
8923
 
15152 obado 8924
  ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
8925
    // Label for screenreaders, accessibility
8926
    if(label) {
8927
      this.div.setAttribute('aria-label', label);
8928
    } else {
8929
      this.div.removeAttribute('aria-label');
8930
    }
8931
  };
8932
 
14283 obado 8933
  ContentEditableInput.prototype.prepareSelection = function () {
8934
    var result = prepareSelection(this.cm, false);
18249 obado 8935
    result.focus = activeElt(rootNode(this.div)) == this.div;
14283 obado 8936
    return result
8937
  };
8938
 
8939
  ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
8940
    if (!info || !this.cm.display.view.length) { return }
8941
    if (info.focus || takeFocus) { this.showPrimarySelection(); }
8942
    this.showMultipleSelections(info);
8943
  };
8944
 
8945
  ContentEditableInput.prototype.getSelection = function () {
8946
    return this.cm.display.wrapper.ownerDocument.getSelection()
8947
  };
8948
 
8949
  ContentEditableInput.prototype.showPrimarySelection = function () {
8950
    var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
8951
    var from = prim.from(), to = prim.to();
8952
 
8953
    if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8954
      sel.removeAllRanges();
8955
      return
8956
    }
8957
 
8958
    var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8959
    var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
8960
    if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
8961
        cmp(minPos(curAnchor, curFocus), from) == 0 &&
8962
        cmp(maxPos(curAnchor, curFocus), to) == 0)
8963
      { return }
8964
 
8965
    var view = cm.display.view;
8966
    var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
8967
        {node: view[0].measure.map[2], offset: 0};
8968
    var end = to.line < cm.display.viewTo && posToDOM(cm, to);
8969
    if (!end) {
8970
      var measure = view[view.length - 1].measure;
15152 obado 8971
      var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
8972
      end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
14283 obado 8973
    }
8974
 
8975
    if (!start || !end) {
8976
      sel.removeAllRanges();
8977
      return
8978
    }
8979
 
8980
    var old = sel.rangeCount && sel.getRangeAt(0), rng;
8981
    try { rng = range(start.node, start.offset, end.offset, end.node); }
8982
    catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
8983
    if (rng) {
8984
      if (!gecko && cm.state.focused) {
8985
        sel.collapse(start.node, start.offset);
8986
        if (!rng.collapsed) {
8987
          sel.removeAllRanges();
8988
          sel.addRange(rng);
8989
        }
8990
      } else {
8991
        sel.removeAllRanges();
8992
        sel.addRange(rng);
8993
      }
8994
      if (old && sel.anchorNode == null) { sel.addRange(old); }
8995
      else if (gecko) { this.startGracePeriod(); }
8996
    }
8997
    this.rememberSelection();
8998
  };
8999
 
9000
  ContentEditableInput.prototype.startGracePeriod = function () {
9001
      var this$1 = this;
9002
 
9003
    clearTimeout(this.gracePeriod);
9004
    this.gracePeriod = setTimeout(function () {
9005
      this$1.gracePeriod = false;
9006
      if (this$1.selectionChanged())
9007
        { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
9008
    }, 20);
9009
  };
9010
 
9011
  ContentEditableInput.prototype.showMultipleSelections = function (info) {
9012
    removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
9013
    removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
9014
  };
9015
 
9016
  ContentEditableInput.prototype.rememberSelection = function () {
9017
    var sel = this.getSelection();
9018
    this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
9019
    this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
9020
  };
9021
 
9022
  ContentEditableInput.prototype.selectionInEditor = function () {
9023
    var sel = this.getSelection();
9024
    if (!sel.rangeCount) { return false }
9025
    var node = sel.getRangeAt(0).commonAncestorContainer;
9026
    return contains(this.div, node)
9027
  };
9028
 
9029
  ContentEditableInput.prototype.focus = function () {
9030
    if (this.cm.options.readOnly != "nocursor") {
18249 obado 9031
      if (!this.selectionInEditor() || activeElt(rootNode(this.div)) != this.div)
14283 obado 9032
        { this.showSelection(this.prepareSelection(), true); }
9033
      this.div.focus();
9034
    }
9035
  };
9036
  ContentEditableInput.prototype.blur = function () { this.div.blur(); };
9037
  ContentEditableInput.prototype.getField = function () { return this.div };
9038
 
9039
  ContentEditableInput.prototype.supportsTouch = function () { return true };
9040
 
9041
  ContentEditableInput.prototype.receivedFocus = function () {
16493 obado 9042
      var this$1 = this;
9043
 
14283 obado 9044
    var input = this;
9045
    if (this.selectionInEditor())
16493 obado 9046
      { setTimeout(function () { return this$1.pollSelection(); }, 20); }
14283 obado 9047
    else
9048
      { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
9049
 
9050
    function poll() {
9051
      if (input.cm.state.focused) {
9052
        input.pollSelection();
9053
        input.polling.set(input.cm.options.pollInterval, poll);
9054
      }
9055
    }
9056
    this.polling.set(this.cm.options.pollInterval, poll);
9057
  };
9058
 
9059
  ContentEditableInput.prototype.selectionChanged = function () {
9060
    var sel = this.getSelection();
9061
    return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
9062
      sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
9063
  };
9064
 
9065
  ContentEditableInput.prototype.pollSelection = function () {
9066
    if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
9067
    var sel = this.getSelection(), cm = this.cm;
9068
    // On Android Chrome (version 56, at least), backspacing into an
9069
    // uneditable block element will put the cursor in that element,
9070
    // and then, because it's not editable, hide the virtual keyboard.
9071
    // Because Android doesn't allow us to actually detect backspace
9072
    // presses in a sane way, this code checks for when that happens
9073
    // and simulates a backspace press in this case.
9074
    if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
9075
      this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
9076
      this.blur();
9077
      this.focus();
9078
      return
9079
    }
9080
    if (this.composing) { return }
9081
    this.rememberSelection();
9082
    var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
9083
    var head = domToPos(cm, sel.focusNode, sel.focusOffset);
9084
    if (anchor && head) { runInOp(cm, function () {
9085
      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
9086
      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
9087
    }); }
9088
  };
9089
 
9090
  ContentEditableInput.prototype.pollContent = function () {
9091
    if (this.readDOMTimeout != null) {
9092
      clearTimeout(this.readDOMTimeout);
9093
      this.readDOMTimeout = null;
9094
    }
9095
 
9096
    var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
9097
    var from = sel.from(), to = sel.to();
9098
    if (from.ch == 0 && from.line > cm.firstLine())
9099
      { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
9100
    if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
9101
      { to = Pos(to.line + 1, 0); }
9102
    if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
9103
 
9104
    var fromIndex, fromLine, fromNode;
9105
    if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
9106
      fromLine = lineNo(display.view[0].line);
9107
      fromNode = display.view[0].node;
9108
    } else {
9109
      fromLine = lineNo(display.view[fromIndex].line);
9110
      fromNode = display.view[fromIndex - 1].node.nextSibling;
9111
    }
9112
    var toIndex = findViewIndex(cm, to.line);
9113
    var toLine, toNode;
9114
    if (toIndex == display.view.length - 1) {
9115
      toLine = display.viewTo - 1;
9116
      toNode = display.lineDiv.lastChild;
9117
    } else {
9118
      toLine = lineNo(display.view[toIndex + 1].line) - 1;
9119
      toNode = display.view[toIndex + 1].node.previousSibling;
9120
    }
9121
 
9122
    if (!fromNode) { return false }
9123
    var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
9124
    var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
9125
    while (newText.length > 1 && oldText.length > 1) {
9126
      if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
9127
      else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
9128
      else { break }
9129
    }
9130
 
9131
    var cutFront = 0, cutEnd = 0;
9132
    var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
9133
    while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
9134
      { ++cutFront; }
9135
    var newBot = lst(newText), oldBot = lst(oldText);
9136
    var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
9137
                             oldBot.length - (oldText.length == 1 ? cutFront : 0));
9138
    while (cutEnd < maxCutEnd &&
9139
           newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
9140
      { ++cutEnd; }
9141
    // Try to move start of change to start of selection if ambiguous
9142
    if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
9143
      while (cutFront && cutFront > from.ch &&
9144
             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
9145
        cutFront--;
9146
        cutEnd++;
9147
      }
9148
    }
9149
 
9150
    newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
9151
    newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
9152
 
9153
    var chFrom = Pos(fromLine, cutFront);
9154
    var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
9155
    if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
9156
      replaceRange(cm.doc, newText, chFrom, chTo, "+input");
9157
      return true
9158
    }
9159
  };
9160
 
9161
  ContentEditableInput.prototype.ensurePolled = function () {
9162
    this.forceCompositionEnd();
9163
  };
9164
  ContentEditableInput.prototype.reset = function () {
9165
    this.forceCompositionEnd();
9166
  };
9167
  ContentEditableInput.prototype.forceCompositionEnd = function () {
9168
    if (!this.composing) { return }
9169
    clearTimeout(this.readDOMTimeout);
9170
    this.composing = null;
9171
    this.updateFromDOM();
9172
    this.div.blur();
9173
    this.div.focus();
9174
  };
9175
  ContentEditableInput.prototype.readFromDOMSoon = function () {
9176
      var this$1 = this;
9177
 
9178
    if (this.readDOMTimeout != null) { return }
9179
    this.readDOMTimeout = setTimeout(function () {
9180
      this$1.readDOMTimeout = null;
9181
      if (this$1.composing) {
9182
        if (this$1.composing.done) { this$1.composing = null; }
9183
        else { return }
9184
      }
9185
      this$1.updateFromDOM();
9186
    }, 80);
9187
  };
9188
 
9189
  ContentEditableInput.prototype.updateFromDOM = function () {
9190
      var this$1 = this;
9191
 
9192
    if (this.cm.isReadOnly() || !this.pollContent())
9193
      { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
9194
  };
9195
 
9196
  ContentEditableInput.prototype.setUneditable = function (node) {
9197
    node.contentEditable = "false";
9198
  };
9199
 
9200
  ContentEditableInput.prototype.onKeyPress = function (e) {
9201
    if (e.charCode == 0 || this.composing) { return }
9202
    e.preventDefault();
9203
    if (!this.cm.isReadOnly())
9204
      { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
9205
  };
9206
 
9207
  ContentEditableInput.prototype.readOnlyChanged = function (val) {
9208
    this.div.contentEditable = String(val != "nocursor");
9209
  };
9210
 
9211
  ContentEditableInput.prototype.onContextMenu = function () {};
9212
  ContentEditableInput.prototype.resetPosition = function () {};
9213
 
9214
  ContentEditableInput.prototype.needsContentAttribute = true;
9215
 
9216
  function posToDOM(cm, pos) {
9217
    var view = findViewForLine(cm, pos.line);
9218
    if (!view || view.hidden) { return null }
9219
    var line = getLine(cm.doc, pos.line);
9220
    var info = mapFromLineView(view, line, pos.line);
9221
 
9222
    var order = getOrder(line, cm.doc.direction), side = "left";
9223
    if (order) {
9224
      var partPos = getBidiPartAt(order, pos.ch);
9225
      side = partPos % 2 ? "right" : "left";
9226
    }
9227
    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9228
    result.offset = result.collapse == "right" ? result.end : result.start;
9229
    return result
9230
  }
9231
 
9232
  function isInGutter(node) {
9233
    for (var scan = node; scan; scan = scan.parentNode)
9234
      { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
9235
    return false
9236
  }
9237
 
9238
  function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9239
 
9240
  function domTextBetween(cm, from, to, fromLine, toLine) {
9241
    var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
9242
    function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
9243
    function close() {
9244
      if (closing) {
9245
        text += lineSep;
9246
        if (extraLinebreak) { text += lineSep; }
9247
        closing = extraLinebreak = false;
9248
      }
9249
    }
9250
    function addText(str) {
9251
      if (str) {
9252
        close();
9253
        text += str;
9254
      }
9255
    }
9256
    function walk(node) {
9257
      if (node.nodeType == 1) {
9258
        var cmText = node.getAttribute("cm-text");
9259
        if (cmText) {
9260
          addText(cmText);
9261
          return
9262
        }
15152 obado 9263
        var markerID = node.getAttribute("cm-marker"), range;
14283 obado 9264
        if (markerID) {
9265
          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
15152 obado 9266
          if (found.length && (range = found[0].find(0)))
9267
            { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
14283 obado 9268
          return
9269
        }
9270
        if (node.getAttribute("contenteditable") == "false") { return }
9271
        var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
9272
        if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
9273
 
9274
        if (isBlock) { close(); }
9275
        for (var i = 0; i < node.childNodes.length; i++)
9276
          { walk(node.childNodes[i]); }
9277
 
9278
        if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
9279
        if (isBlock) { closing = true; }
9280
      } else if (node.nodeType == 3) {
9281
        addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
9282
      }
9283
    }
9284
    for (;;) {
9285
      walk(from);
9286
      if (from == to) { break }
9287
      from = from.nextSibling;
9288
      extraLinebreak = false;
9289
    }
9290
    return text
9291
  }
9292
 
9293
  function domToPos(cm, node, offset) {
9294
    var lineNode;
9295
    if (node == cm.display.lineDiv) {
9296
      lineNode = cm.display.lineDiv.childNodes[offset];
9297
      if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
9298
      node = null; offset = 0;
9299
    } else {
9300
      for (lineNode = node;; lineNode = lineNode.parentNode) {
9301
        if (!lineNode || lineNode == cm.display.lineDiv) { return null }
9302
        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
9303
      }
9304
    }
9305
    for (var i = 0; i < cm.display.view.length; i++) {
9306
      var lineView = cm.display.view[i];
9307
      if (lineView.node == lineNode)
9308
        { return locateNodeInLineView(lineView, node, offset) }
9309
    }
9310
  }
9311
 
9312
  function locateNodeInLineView(lineView, node, offset) {
9313
    var wrapper = lineView.text.firstChild, bad = false;
9314
    if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
9315
    if (node == wrapper) {
9316
      bad = true;
9317
      node = wrapper.childNodes[offset];
9318
      offset = 0;
9319
      if (!node) {
9320
        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
9321
        return badPos(Pos(lineNo(line), line.text.length), bad)
9322
      }
9323
    }
9324
 
9325
    var textNode = node.nodeType == 3 ? node : null, topNode = node;
9326
    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
9327
      textNode = node.firstChild;
9328
      if (offset) { offset = textNode.nodeValue.length; }
9329
    }
9330
    while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
9331
    var measure = lineView.measure, maps = measure.maps;
9332
 
9333
    function find(textNode, topNode, offset) {
9334
      for (var i = -1; i < (maps ? maps.length : 0); i++) {
15152 obado 9335
        var map = i < 0 ? measure.map : maps[i];
9336
        for (var j = 0; j < map.length; j += 3) {
9337
          var curNode = map[j + 2];
14283 obado 9338
          if (curNode == textNode || curNode == topNode) {
9339
            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
15152 obado 9340
            var ch = map[j] + offset;
9341
            if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
14283 obado 9342
            return Pos(line, ch)
9343
          }
9344
        }
9345
      }
9346
    }
9347
    var found = find(textNode, topNode, offset);
9348
    if (found) { return badPos(found, bad) }
9349
 
9350
    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
9351
    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
9352
      found = find(after, after.firstChild, 0);
9353
      if (found)
9354
        { return badPos(Pos(found.line, found.ch - dist), bad) }
9355
      else
9356
        { dist += after.textContent.length; }
9357
    }
9358
    for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
9359
      found = find(before, before.firstChild, -1);
9360
      if (found)
9361
        { return badPos(Pos(found.line, found.ch + dist$1), bad) }
9362
      else
9363
        { dist$1 += before.textContent.length; }
9364
    }
9365
  }
9366
 
9367
  // TEXTAREA INPUT STYLE
9368
 
9369
  var TextareaInput = function(cm) {
9370
    this.cm = cm;
9371
    // See input.poll and input.reset
9372
    this.prevInput = "";
9373
 
9374
    // Flag that indicates whether we expect input to appear real soon
9375
    // now (after some event like 'keypress' or 'input') and are
9376
    // polling intensively.
9377
    this.pollingFast = false;
9378
    // Self-resetting timeout for the poller
9379
    this.polling = new Delayed();
9380
    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
9381
    this.hasSelection = false;
9382
    this.composing = null;
17702 obado 9383
    this.resetting = false;
14283 obado 9384
  };
9385
 
9386
  TextareaInput.prototype.init = function (display) {
9387
      var this$1 = this;
9388
 
9389
    var input = this, cm = this.cm;
9390
    this.createField(display);
9391
    var te = this.textarea;
9392
 
9393
    display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
9394
 
9395
    // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
9396
    if (ios) { te.style.width = "0px"; }
9397
 
9398
    on(te, "input", function () {
9399
      if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9400
      input.poll();
9401
    });
9402
 
9403
    on(te, "paste", function (e) {
9404
      if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9405
 
9406
      cm.state.pasteIncoming = +new Date;
9407
      input.fastPoll();
9408
    });
9409
 
9410
    function prepareCopyCut(e) {
9411
      if (signalDOMEvent(cm, e)) { return }
9412
      if (cm.somethingSelected()) {
9413
        setLastCopied({lineWise: false, text: cm.getSelections()});
9414
      } else if (!cm.options.lineWiseCopyCut) {
9415
        return
9416
      } else {
9417
        var ranges = copyableRanges(cm);
9418
        setLastCopied({lineWise: true, text: ranges.text});
9419
        if (e.type == "cut") {
9420
          cm.setSelections(ranges.ranges, null, sel_dontScroll);
9421
        } else {
9422
          input.prevInput = "";
9423
          te.value = ranges.text.join("\n");
9424
          selectInput(te);
9425
        }
9426
      }
9427
      if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
9428
    }
9429
    on(te, "cut", prepareCopyCut);
9430
    on(te, "copy", prepareCopyCut);
9431
 
9432
    on(display.scroller, "paste", function (e) {
9433
      if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
9434
      if (!te.dispatchEvent) {
9435
        cm.state.pasteIncoming = +new Date;
9436
        input.focus();
9437
        return
9438
      }
9439
 
9440
      // Pass the `paste` event to the textarea so it's handled by its event listener.
9441
      var event = new Event("paste");
9442
      event.clipboardData = e.clipboardData;
9443
      te.dispatchEvent(event);
9444
    });
9445
 
9446
    // Prevent normal selection in the editor (we handle our own)
9447
    on(display.lineSpace, "selectstart", function (e) {
9448
      if (!eventInWidget(display, e)) { e_preventDefault(e); }
9449
    });
9450
 
9451
    on(te, "compositionstart", function () {
9452
      var start = cm.getCursor("from");
9453
      if (input.composing) { input.composing.range.clear(); }
9454
      input.composing = {
9455
        start: start,
9456
        range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
9457
      };
9458
    });
9459
    on(te, "compositionend", function () {
9460
      if (input.composing) {
9461
        input.poll();
9462
        input.composing.range.clear();
9463
        input.composing = null;
9464
      }
9465
    });
9466
  };
9467
 
9468
  TextareaInput.prototype.createField = function (_display) {
9469
    // Wraps and hides input textarea
9470
    this.wrapper = hiddenTextarea();
9471
    // The semihidden textarea that is focused when the editor is
9472
    // focused, and receives input.
9473
    this.textarea = this.wrapper.firstChild;
17702 obado 9474
    var opts = this.cm.options;
9475
    disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
14283 obado 9476
  };
9477
 
15152 obado 9478
  TextareaInput.prototype.screenReaderLabelChanged = function (label) {
9479
    // Label for screenreaders, accessibility
9480
    if(label) {
9481
      this.textarea.setAttribute('aria-label', label);
9482
    } else {
9483
      this.textarea.removeAttribute('aria-label');
9484
    }
9485
  };
9486
 
14283 obado 9487
  TextareaInput.prototype.prepareSelection = function () {
9488
    // Redraw the selection and/or cursor
9489
    var cm = this.cm, display = cm.display, doc = cm.doc;
9490
    var result = prepareSelection(cm);
9491
 
9492
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
9493
    if (cm.options.moveInputWithCursor) {
9494
      var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
9495
      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
9496
      result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
9497
                                          headPos.top + lineOff.top - wrapOff.top));
9498
      result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
9499
                                           headPos.left + lineOff.left - wrapOff.left));
9500
    }
9501
 
9502
    return result
9503
  };
9504
 
9505
  TextareaInput.prototype.showSelection = function (drawn) {
9506
    var cm = this.cm, display = cm.display;
9507
    removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
9508
    removeChildrenAndAdd(display.selectionDiv, drawn.selection);
9509
    if (drawn.teTop != null) {
9510
      this.wrapper.style.top = drawn.teTop + "px";
9511
      this.wrapper.style.left = drawn.teLeft + "px";
9512
    }
9513
  };
9514
 
9515
  // Reset the input to correspond to the selection (or to be empty,
9516
  // when not typing and nothing is selected)
9517
  TextareaInput.prototype.reset = function (typing) {
17702 obado 9518
    if (this.contextMenuPending || this.composing && typing) { return }
14283 obado 9519
    var cm = this.cm;
17702 obado 9520
    this.resetting = true;
14283 obado 9521
    if (cm.somethingSelected()) {
9522
      this.prevInput = "";
9523
      var content = cm.getSelection();
9524
      this.textarea.value = content;
9525
      if (cm.state.focused) { selectInput(this.textarea); }
9526
      if (ie && ie_version >= 9) { this.hasSelection = content; }
9527
    } else if (!typing) {
9528
      this.prevInput = this.textarea.value = "";
9529
      if (ie && ie_version >= 9) { this.hasSelection = null; }
9530
    }
17702 obado 9531
    this.resetting = false;
14283 obado 9532
  };
9533
 
9534
  TextareaInput.prototype.getField = function () { return this.textarea };
9535
 
9536
  TextareaInput.prototype.supportsTouch = function () { return false };
9537
 
9538
  TextareaInput.prototype.focus = function () {
18249 obado 9539
    if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(rootNode(this.textarea)) != this.textarea)) {
14283 obado 9540
      try { this.textarea.focus(); }
9541
      catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
9542
    }
9543
  };
9544
 
9545
  TextareaInput.prototype.blur = function () { this.textarea.blur(); };
9546
 
9547
  TextareaInput.prototype.resetPosition = function () {
9548
    this.wrapper.style.top = this.wrapper.style.left = 0;
9549
  };
9550
 
9551
  TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
9552
 
9553
  // Poll for input changes, using the normal rate of polling. This
9554
  // runs as long as the editor is focused.
9555
  TextareaInput.prototype.slowPoll = function () {
9556
      var this$1 = this;
9557
 
9558
    if (this.pollingFast) { return }
9559
    this.polling.set(this.cm.options.pollInterval, function () {
9560
      this$1.poll();
9561
      if (this$1.cm.state.focused) { this$1.slowPoll(); }
9562
    });
9563
  };
9564
 
9565
  // When an event has just come in that is likely to add or change
9566
  // something in the input textarea, we poll faster, to ensure that
9567
  // the change appears on the screen quickly.
9568
  TextareaInput.prototype.fastPoll = function () {
9569
    var missed = false, input = this;
9570
    input.pollingFast = true;
9571
    function p() {
9572
      var changed = input.poll();
9573
      if (!changed && !missed) {missed = true; input.polling.set(60, p);}
9574
      else {input.pollingFast = false; input.slowPoll();}
9575
    }
9576
    input.polling.set(20, p);
9577
  };
9578
 
9579
  // Read input from the textarea, and update the document to match.
9580
  // When something is selected, it is present in the textarea, and
9581
  // selected (unless it is huge, in which case a placeholder is
9582
  // used). When nothing is selected, the cursor sits after previously
9583
  // seen text (can be empty), which is stored in prevInput (we must
9584
  // not reset the textarea when typing, because that breaks IME).
9585
  TextareaInput.prototype.poll = function () {
9586
      var this$1 = this;
9587
 
9588
    var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
9589
    // Since this is called a *lot*, try to bail out as cheaply as
9590
    // possible when it is clear that nothing happened. hasSelection
9591
    // will be the case when there is a lot of text in the textarea,
9592
    // in which case reading its value would be expensive.
17702 obado 9593
    if (this.contextMenuPending || this.resetting || !cm.state.focused ||
14283 obado 9594
        (hasSelection(input) && !prevInput && !this.composing) ||
9595
        cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
9596
      { return false }
9597
 
9598
    var text = input.value;
9599
    // If nothing changed, bail.
9600
    if (text == prevInput && !cm.somethingSelected()) { return false }
9601
    // Work around nonsensical selection resetting in IE9/10, and
9602
    // inexplicable appearance of private area unicode characters on
9603
    // some key combos in Mac (#2689).
9604
    if (ie && ie_version >= 9 && this.hasSelection === text ||
9605
        mac && /[\uf700-\uf7ff]/.test(text)) {
9606
      cm.display.input.reset();
9607
      return false
9608
    }
9609
 
9610
    if (cm.doc.sel == cm.display.selForContextMenu) {
9611
      var first = text.charCodeAt(0);
9612
      if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
9613
      if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
9614
    }
9615
    // Find the part of the input that is actually new
9616
    var same = 0, l = Math.min(prevInput.length, text.length);
9617
    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
9618
 
9619
    runInOp(cm, function () {
9620
      applyTextInput(cm, text.slice(same), prevInput.length - same,
9621
                     null, this$1.composing ? "*compose" : null);
9622
 
9623
      // Don't leave long text in the textarea, since it makes further polling slow
9624
      if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
9625
      else { this$1.prevInput = text; }
9626
 
9627
      if (this$1.composing) {
9628
        this$1.composing.range.clear();
9629
        this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
9630
                                           {className: "CodeMirror-composing"});
9631
      }
9632
    });
9633
    return true
9634
  };
9635
 
9636
  TextareaInput.prototype.ensurePolled = function () {
9637
    if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9638
  };
9639
 
9640
  TextareaInput.prototype.onKeyPress = function () {
9641
    if (ie && ie_version >= 9) { this.hasSelection = null; }
9642
    this.fastPoll();
9643
  };
9644
 
9645
  TextareaInput.prototype.onContextMenu = function (e) {
9646
    var input = this, cm = input.cm, display = cm.display, te = input.textarea;
9647
    if (input.contextMenuPending) { input.contextMenuPending(); }
9648
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
9649
    if (!pos || presto) { return } // Opera is difficult.
9650
 
9651
    // Reset the current text selection only if the click is done outside of the selection
9652
    // and 'resetSelectionOnContextMenu' option is true.
9653
    var reset = cm.options.resetSelectionOnContextMenu;
9654
    if (reset && cm.doc.sel.contains(pos) == -1)
9655
      { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
9656
 
9657
    var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
9658
    var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
9659
    input.wrapper.style.cssText = "position: static";
9660
    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);";
9661
    var oldScrollY;
17702 obado 9662
    if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
14283 obado 9663
    display.input.focus();
17702 obado 9664
    if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
14283 obado 9665
    display.input.reset();
9666
    // Adds "Select all" to context menu in FF
9667
    if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
9668
    input.contextMenuPending = rehide;
9669
    display.selForContextMenu = cm.doc.sel;
9670
    clearTimeout(display.detectingSelectAll);
9671
 
9672
    // Select-all will be greyed out if there's nothing to select, so
9673
    // this adds a zero-width space so that we can later check whether
9674
    // it got selected.
9675
    function prepareSelectAllHack() {
9676
      if (te.selectionStart != null) {
9677
        var selected = cm.somethingSelected();
9678
        var extval = "\u200b" + (selected ? te.value : "");
9679
        te.value = "\u21da"; // Used to catch context-menu undo
9680
        te.value = extval;
9681
        input.prevInput = selected ? "" : "\u200b";
9682
        te.selectionStart = 1; te.selectionEnd = extval.length;
9683
        // Re-set this, in case some other handler touched the
9684
        // selection in the meantime.
9685
        display.selForContextMenu = cm.doc.sel;
9686
      }
9687
    }
9688
    function rehide() {
9689
      if (input.contextMenuPending != rehide) { return }
9690
      input.contextMenuPending = false;
9691
      input.wrapper.style.cssText = oldWrapperCSS;
9692
      te.style.cssText = oldCSS;
9693
      if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
9694
 
9695
      // Try to detect the user choosing select-all
9696
      if (te.selectionStart != null) {
9697
        if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
9698
        var i = 0, poll = function () {
9699
          if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
9700
              te.selectionEnd > 0 && input.prevInput == "\u200b") {
9701
            operation(cm, selectAll)(cm);
9702
          } else if (i++ < 10) {
9703
            display.detectingSelectAll = setTimeout(poll, 500);
9704
          } else {
9705
            display.selForContextMenu = null;
9706
            display.input.reset();
9707
          }
9708
        };
9709
        display.detectingSelectAll = setTimeout(poll, 200);
9710
      }
9711
    }
9712
 
9713
    if (ie && ie_version >= 9) { prepareSelectAllHack(); }
9714
    if (captureRightClick) {
9715
      e_stop(e);
9716
      var mouseup = function () {
9717
        off(window, "mouseup", mouseup);
9718
        setTimeout(rehide, 20);
9719
      };
9720
      on(window, "mouseup", mouseup);
9721
    } else {
9722
      setTimeout(rehide, 50);
9723
    }
9724
  };
9725
 
9726
  TextareaInput.prototype.readOnlyChanged = function (val) {
9727
    if (!val) { this.reset(); }
9728
    this.textarea.disabled = val == "nocursor";
16493 obado 9729
    this.textarea.readOnly = !!val;
14283 obado 9730
  };
9731
 
9732
  TextareaInput.prototype.setUneditable = function () {};
9733
 
9734
  TextareaInput.prototype.needsContentAttribute = false;
9735
 
9736
  function fromTextArea(textarea, options) {
9737
    options = options ? copyObj(options) : {};
9738
    options.value = textarea.value;
9739
    if (!options.tabindex && textarea.tabIndex)
9740
      { options.tabindex = textarea.tabIndex; }
9741
    if (!options.placeholder && textarea.placeholder)
9742
      { options.placeholder = textarea.placeholder; }
9743
    // Set autofocus to true if this textarea is focused, or if it has
9744
    // autofocus and no other element is focused.
9745
    if (options.autofocus == null) {
18249 obado 9746
      var hasFocus = activeElt(rootNode(textarea));
14283 obado 9747
      options.autofocus = hasFocus == textarea ||
9748
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
9749
    }
9750
 
9751
    function save() {textarea.value = cm.getValue();}
9752
 
9753
    var realSubmit;
9754
    if (textarea.form) {
9755
      on(textarea.form, "submit", save);
9756
      // Deplorable hack to make the submit method do the right thing.
9757
      if (!options.leaveSubmitMethodAlone) {
9758
        var form = textarea.form;
9759
        realSubmit = form.submit;
9760
        try {
9761
          var wrappedSubmit = form.submit = function () {
9762
            save();
9763
            form.submit = realSubmit;
9764
            form.submit();
9765
            form.submit = wrappedSubmit;
9766
          };
9767
        } catch(e) {}
9768
      }
9769
    }
9770
 
9771
    options.finishInit = function (cm) {
9772
      cm.save = save;
9773
      cm.getTextArea = function () { return textarea; };
9774
      cm.toTextArea = function () {
9775
        cm.toTextArea = isNaN; // Prevent this from being ran twice
9776
        save();
9777
        textarea.parentNode.removeChild(cm.getWrapperElement());
9778
        textarea.style.display = "";
9779
        if (textarea.form) {
9780
          off(textarea.form, "submit", save);
15152 obado 9781
          if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
14283 obado 9782
            { textarea.form.submit = realSubmit; }
9783
        }
9784
      };
9785
    };
9786
 
9787
    textarea.style.display = "none";
9788
    var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
9789
      options);
9790
    return cm
9791
  }
9792
 
9793
  function addLegacyProps(CodeMirror) {
9794
    CodeMirror.off = off;
9795
    CodeMirror.on = on;
9796
    CodeMirror.wheelEventPixels = wheelEventPixels;
9797
    CodeMirror.Doc = Doc;
9798
    CodeMirror.splitLines = splitLinesAuto;
9799
    CodeMirror.countColumn = countColumn;
9800
    CodeMirror.findColumn = findColumn;
9801
    CodeMirror.isWordChar = isWordCharBasic;
9802
    CodeMirror.Pass = Pass;
9803
    CodeMirror.signal = signal;
9804
    CodeMirror.Line = Line;
9805
    CodeMirror.changeEnd = changeEnd;
9806
    CodeMirror.scrollbarModel = scrollbarModel;
9807
    CodeMirror.Pos = Pos;
9808
    CodeMirror.cmpPos = cmp;
9809
    CodeMirror.modes = modes;
9810
    CodeMirror.mimeModes = mimeModes;
9811
    CodeMirror.resolveMode = resolveMode;
9812
    CodeMirror.getMode = getMode;
9813
    CodeMirror.modeExtensions = modeExtensions;
9814
    CodeMirror.extendMode = extendMode;
9815
    CodeMirror.copyState = copyState;
9816
    CodeMirror.startState = startState;
9817
    CodeMirror.innerMode = innerMode;
9818
    CodeMirror.commands = commands;
9819
    CodeMirror.keyMap = keyMap;
9820
    CodeMirror.keyName = keyName;
9821
    CodeMirror.isModifierKey = isModifierKey;
9822
    CodeMirror.lookupKey = lookupKey;
9823
    CodeMirror.normalizeKeyMap = normalizeKeyMap;
9824
    CodeMirror.StringStream = StringStream;
9825
    CodeMirror.SharedTextMarker = SharedTextMarker;
9826
    CodeMirror.TextMarker = TextMarker;
9827
    CodeMirror.LineWidget = LineWidget;
9828
    CodeMirror.e_preventDefault = e_preventDefault;
9829
    CodeMirror.e_stopPropagation = e_stopPropagation;
9830
    CodeMirror.e_stop = e_stop;
9831
    CodeMirror.addClass = addClass;
9832
    CodeMirror.contains = contains;
9833
    CodeMirror.rmClass = rmClass;
9834
    CodeMirror.keyNames = keyNames;
9835
  }
9836
 
9837
  // EDITOR CONSTRUCTOR
9838
 
9839
  defineOptions(CodeMirror);
9840
 
9841
  addEditorMethods(CodeMirror);
9842
 
9843
  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
9844
  var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
9845
  for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
9846
    { CodeMirror.prototype[prop] = (function(method) {
9847
      return function() {return method.apply(this.doc, arguments)}
9848
    })(Doc.prototype[prop]); } }
9849
 
9850
  eventMixin(Doc);
9851
  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9852
 
9853
  // Extra arguments are stored as the mode's dependencies, which is
9854
  // used by (legacy) mechanisms like loadmode.js to automatically
9855
  // load a mode. (Preferred mechanism is the require/define calls.)
9856
  CodeMirror.defineMode = function(name/*, mode, …*/) {
9857
    if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
9858
    defineMode.apply(this, arguments);
9859
  };
9860
 
9861
  CodeMirror.defineMIME = defineMIME;
9862
 
9863
  // Minimal default mode.
9864
  CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9865
  CodeMirror.defineMIME("text/plain", "null");
9866
 
9867
  // EXTENSIONS
9868
 
9869
  CodeMirror.defineExtension = function (name, func) {
9870
    CodeMirror.prototype[name] = func;
9871
  };
9872
  CodeMirror.defineDocExtension = function (name, func) {
9873
    Doc.prototype[name] = func;
9874
  };
9875
 
9876
  CodeMirror.fromTextArea = fromTextArea;
9877
 
9878
  addLegacyProps(CodeMirror);
9879
 
18249 obado 9880
  CodeMirror.version = "5.65.16";
14283 obado 9881
 
9882
  return CodeMirror;
9883
 
9884
})));