PluginProbe
Smart Grid-Layout Design for Contact Form 7 / 4.5
Smart Grid-Layout Design for Contact Form 7 v4.5
4.18.0 4.17.0 3.2.0 3.2.1 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4 3.3.5 3.3.6 3.3.7 3.3.8 4.0.0 4.0.1 4.1.0 4.1.1 4.1.2 4.1.3 4.1.4 4.10 4.11 4.12 4.13 4.14 All 119 releases
cf7-grid-layout / assets / codemirror / codemirror.js

codemirror.js in Smart Grid-Layout Design for Contact Form 7 4.5, at assets/codemirror/codemirror.js

9,666 lines 364.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: http://codemirror.net/LICENSE
3
4 // This is CodeMirror (http://codemirror.net), a code editor
5 // implemented in JavaScript on top of the browser's DOM.
6 //
7 // You can find some technical background for some of the code below
8 // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
10 (function (global, factory) {
11 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
12 typeof define === 'function' && define.amd ? define(factory) :
13 (global.CodeMirror = factory());
14 }(this, (function () { 'use strict';
15
16 // Kludges for bugs and behavior differences that can't be feature
17 // detected are enabled based on userAgent etc sniffing.
18 var userAgent = navigator.userAgent;
19 var platform = navigator.platform;
20
21 var gecko = /gecko\/\d/i.test(userAgent);
22 var ie_upto10 = /MSIE \d/.test(userAgent);
23 var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
24 var edge = /Edge\/(\d+)/.exec(userAgent);
25 var ie = ie_upto10 || ie_11up || edge;
26 var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
27 var webkit = !edge && /WebKit\//.test(userAgent);
28 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
29 var chrome = !edge && /Chrome\//.test(userAgent);
30 var presto = /Opera\//.test(userAgent);
31 var safari = /Apple Computer/.test(navigator.vendor);
32 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
33 var phantom = /PhantomJS/.test(userAgent);
34
35 var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
36 var android = /Android/.test(userAgent);
37 // This is woefully incomplete. Suggestions for alternative methods welcome.
38 var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
39 var mac = ios || /Mac/.test(platform);
40 var chromeOS = /\bCrOS\b/.test(userAgent);
41 var windows = /win/i.test(platform);
42
43 var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
44 if (presto_version) { presto_version = Number(presto_version[1]); }
45 if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
46 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
47 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
48 var captureRightClick = gecko || (ie && ie_version >= 9);
49
50 function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
51
52 var rmClass = function(node, cls) {
53 var current = node.className;
54 var match = classTest(cls).exec(current);
55 if (match) {
56 var after = current.slice(match.index + match[0].length);
57 node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
58 }
59 };
60
61 function removeChildren(e) {
62 for (var count = e.childNodes.length; count > 0; --count)
63 { e.removeChild(e.firstChild); }
64 return e
65 }
66
67 function removeChildrenAndAdd(parent, e) {
68 return removeChildren(parent).appendChild(e)
69 }
70
71 function elt(tag, content, className, style) {
72 var e = document.createElement(tag);
73 if (className) { e.className = className; }
74 if (style) { e.style.cssText = style; }
75 if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
76 else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
77 return e
78 }
79 // wrapper for elt, which removes the elt from the accessibility tree
80 function eltP(tag, content, className, style) {
81 var e = elt(tag, content, className, style);
82 e.setAttribute("role", "presentation");
83 return e
84 }
85
86 var range;
87 if (document.createRange) { range = function(node, start, end, endNode) {
88 var r = document.createRange();
89 r.setEnd(endNode || node, end);
90 r.setStart(node, start);
91 return r
92 }; }
93 else { range = function(node, start, end) {
94 var r = document.body.createTextRange();
95 try { r.moveToElementText(node.parentNode); }
96 catch(e) { return r }
97 r.collapse(true);
98 r.moveEnd("character", end);
99 r.moveStart("character", start);
100 return r
101 }; }
102
103 function contains(parent, child) {
104 if (child.nodeType == 3) // Android browser always returns false when child is a textnode
105 { child = child.parentNode; }
106 if (parent.contains)
107 { return parent.contains(child) }
108 do {
109 if (child.nodeType == 11) { child = child.host; }
110 if (child == parent) { return true }
111 } while (child = child.parentNode)
112 }
113
114 function activeElt() {
115 // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
116 // IE < 10 will throw when accessed while the page is loading or in an iframe.
117 // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
118 var activeElement;
119 try {
120 activeElement = document.activeElement;
121 } catch(e) {
122 activeElement = document.body || null;
123 }
124 while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
125 { activeElement = activeElement.shadowRoot.activeElement; }
126 return activeElement
127 }
128
129 function addClass(node, cls) {
130 var current = node.className;
131 if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
132 }
133 function joinClasses(a, b) {
134 var as = a.split(" ");
135 for (var i = 0; i < as.length; i++)
136 { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
137 return b
138 }
139
140 var selectInput = function(node) { node.select(); };
141 if (ios) // Mobile Safari apparently has a bug where select() is broken.
142 { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
143 else if (ie) // Suppress mysterious IE10 errors
144 { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
145
146 function bind(f) {
147 var args = Array.prototype.slice.call(arguments, 1);
148 return function(){return f.apply(null, args)}
149 }
150
151 function copyObj(obj, target, overwrite) {
152 if (!target) { target = {}; }
153 for (var prop in obj)
154 { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
155 { target[prop] = obj[prop]; } }
156 return target
157 }
158
159 // Counts the column offset in a string, taking tabs into account.
160 // Used mostly to find indentation.
161 function countColumn(string, end, tabSize, startIndex, startValue) {
162 if (end == null) {
163 end = string.search(/[^\s\u00a0]/);
164 if (end == -1) { end = string.length; }
165 }
166 for (var i = startIndex || 0, n = startValue || 0;;) {
167 var nextTab = string.indexOf("\t", i);
168 if (nextTab < 0 || nextTab >= end)
169 { return n + (end - i) }
170 n += nextTab - i;
171 n += tabSize - (n % tabSize);
172 i = nextTab + 1;
173 }
174 }
175
176 var Delayed = function() {this.id = null;};
177 Delayed.prototype.set = function (ms, f) {
178 clearTimeout(this.id);
179 this.id = setTimeout(f, ms);
180 };
181
182 function indexOf(array, elt) {
183 for (var i = 0; i < array.length; ++i)
184 { if (array[i] == elt) { return i } }
185 return -1
186 }
187
188 // Number of pixels added to scroller and sizer to hide scrollbar
189 var scrollerGap = 30;
190
191 // Returned or thrown by various protocols to signal 'I'm not
192 // handling this'.
193 var Pass = {toString: function(){return "CodeMirror.Pass"}};
194
195 // Reused option objects for setSelection & friends
196 var sel_dontScroll = {scroll: false};
197 var sel_mouse = {origin: "*mouse"};
198 var sel_move = {origin: "+move"};
199
200 // The inverse of countColumn -- find the offset that corresponds to
201 // a particular column.
202 function findColumn(string, goal, tabSize) {
203 for (var pos = 0, col = 0;;) {
204 var nextTab = string.indexOf("\t", pos);
205 if (nextTab == -1) { nextTab = string.length; }
206 var skipped = nextTab - pos;
207 if (nextTab == string.length || col + skipped >= goal)
208 { return pos + Math.min(skipped, goal - col) }
209 col += nextTab - pos;
210 col += tabSize - (col % tabSize);
211 pos = nextTab + 1;
212 if (col >= goal) { return pos }
213 }
214 }
215
216 var spaceStrs = [""];
217 function spaceStr(n) {
218 while (spaceStrs.length <= n)
219 { spaceStrs.push(lst(spaceStrs) + " "); }
220 return spaceStrs[n]
221 }
222
223 function lst(arr) { return arr[arr.length-1] }
224
225 function map(array, f) {
226 var out = [];
227 for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
228 return out
229 }
230
231 function insertSorted(array, value, score) {
232 var pos = 0, priority = score(value);
233 while (pos < array.length && score(array[pos]) <= priority) { pos++; }
234 array.splice(pos, 0, value);
235 }
236
237 function nothing() {}
238
239 function createObj(base, props) {
240 var inst;
241 if (Object.create) {
242 inst = Object.create(base);
243 } else {
244 nothing.prototype = base;
245 inst = new nothing();
246 }
247 if (props) { copyObj(props, inst); }
248 return inst
249 }
250
251 var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
252 function isWordCharBasic(ch) {
253 return /\w/.test(ch) || ch > "\x80" &&
254 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
255 }
256 function isWordChar(ch, helper) {
257 if (!helper) { return isWordCharBasic(ch) }
258 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
259 return helper.test(ch)
260 }
261
262 function isEmpty(obj) {
263 for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
264 return true
265 }
266
267 // Extending unicode characters. A series of a non-extending char +
268 // any number of extending chars is treated as a single unit as far
269 // as editing and measuring is concerned. This is not fully correct,
270 // since some scripts/fonts/browsers also treat other configurations
271 // of code points as a group.
272 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]/;
273 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
274
275 // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
276 function skipExtendingChars(str, pos, dir) {
277 while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
278 return pos
279 }
280
281 // Returns the value from the range [`from`; `to`] that satisfies
282 // `pred` and is closest to `from`. Assumes that at least `to`
283 // satisfies `pred`. Supports `from` being greater than `to`.
284 function findFirst(pred, from, to) {
285 // At any point we are certain `to` satisfies `pred`, don't know
286 // whether `from` does.
287 var dir = from > to ? -1 : 1;
288 for (;;) {
289 if (from == to) { return from }
290 var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
291 if (mid == from) { return pred(mid) ? from : to }
292 if (pred(mid)) { to = mid; }
293 else { from = mid + dir; }
294 }
295 }
296
297 // The display handles the DOM integration, both for input reading
298 // and content drawing. It holds references to DOM nodes and
299 // display-related state.
300
301 function Display(place, doc, input) {
302 var d = this;
303 this.input = input;
304
305 // Covers bottom-right square when both scrollbars are present.
306 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
307 d.scrollbarFiller.setAttribute("cm-not-content", "true");
308 // Covers bottom of gutter when coverGutterNextToScrollbar is on
309 // and h scrollbar is present.
310 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
311 d.gutterFiller.setAttribute("cm-not-content", "true");
312 // Will contain the actual code, positioned to cover the viewport.
313 d.lineDiv = eltP("div", null, "CodeMirror-code");
314 // Elements are added to these to represent selection and cursors.
315 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
316 d.cursorDiv = elt("div", null, "CodeMirror-cursors");
317 // A visibility: hidden element used to find the size of things.
318 d.measure = elt("div", null, "CodeMirror-measure");
319 // When lines outside of the viewport are measured, they are drawn in this.
320 d.lineMeasure = elt("div", null, "CodeMirror-measure");
321 // Wraps everything that needs to exist inside the vertically-padded coordinate system
322 d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
323 null, "position: relative; outline: none");
324 var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
325 // Moved around its parent to cover visible view.
326 d.mover = elt("div", [lines], null, "position: relative");
327 // Set to the height of the document, allowing scrolling.
328 d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
329 d.sizerWidth = null;
330 // Behavior of elts with overflow: auto and padding is
331 // inconsistent across browsers. This is used to ensure the
332 // scrollable area is big enough.
333 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
334 // Will contain the gutters, if any.
335 d.gutters = elt("div", null, "CodeMirror-gutters");
336 d.lineGutter = null;
337 // Actual scrollable element.
338 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
339 d.scroller.setAttribute("tabIndex", "-1");
340 // The element in which the editor lives.
341 d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
342
343 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
344 if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
345 if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
346
347 if (place) {
348 if (place.appendChild) { place.appendChild(d.wrapper); }
349 else { place(d.wrapper); }
350 }
351
352 // Current rendered range (may be bigger than the view window).
353 d.viewFrom = d.viewTo = doc.first;
354 d.reportedViewFrom = d.reportedViewTo = doc.first;
355 // Information about the rendered lines.
356 d.view = [];
357 d.renderedView = null;
358 // Holds info about a single rendered line when it was rendered
359 // for measurement, while not in view.
360 d.externalMeasured = null;
361 // Empty space (in pixels) above the view
362 d.viewOffset = 0;
363 d.lastWrapHeight = d.lastWrapWidth = 0;
364 d.updateLineNumbers = null;
365
366 d.nativeBarWidth = d.barHeight = d.barWidth = 0;
367 d.scrollbarsClipped = false;
368
369 // Used to only resize the line number gutter when necessary (when
370 // the amount of lines crosses a boundary that makes its width change)
371 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
372 // Set to true when a non-horizontal-scrolling line widget is
373 // added. As an optimization, line widget aligning is skipped when
374 // this is false.
375 d.alignWidgets = false;
376
377 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
378
379 // Tracks the maximum line length so that the horizontal scrollbar
380 // can be kept static when scrolling.
381 d.maxLine = null;
382 d.maxLineLength = 0;
383 d.maxLineChanged = false;
384
385 // Used for measuring wheel scrolling granularity
386 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
387
388 // True when shift is held down.
389 d.shift = false;
390
391 // Used to track whether anything happened since the context menu
392 // was opened.
393 d.selForContextMenu = null;
394
395 d.activeTouch = null;
396
397 input.init(d);
398 }
399
400 // Find the line object corresponding to the given line number.
401 function getLine(doc, n) {
402 n -= doc.first;
403 if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
404 var chunk = doc;
405 while (!chunk.lines) {
406 for (var i = 0;; ++i) {
407 var child = chunk.children[i], sz = child.chunkSize();
408 if (n < sz) { chunk = child; break }
409 n -= sz;
410 }
411 }
412 return chunk.lines[n]
413 }
414
415 // Get the part of a document between two positions, as an array of
416 // strings.
417 function getBetween(doc, start, end) {
418 var out = [], n = start.line;
419 doc.iter(start.line, end.line + 1, function (line) {
420 var text = line.text;
421 if (n == end.line) { text = text.slice(0, end.ch); }
422 if (n == start.line) { text = text.slice(start.ch); }
423 out.push(text);
424 ++n;
425 });
426 return out
427 }
428 // Get the lines between from and to, as array of strings.
429 function getLines(doc, from, to) {
430 var out = [];
431 doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
432 return out
433 }
434
435 // Update the height of a line, propagating the height change
436 // upwards to parent nodes.
437 function updateLineHeight(line, height) {
438 var diff = height - line.height;
439 if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
440 }
441
442 // Given a line object, find its line number by walking up through
443 // its parent links.
444 function lineNo(line) {
445 if (line.parent == null) { return null }
446 var cur = line.parent, no = indexOf(cur.lines, line);
447 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
448 for (var i = 0;; ++i) {
449 if (chunk.children[i] == cur) { break }
450 no += chunk.children[i].chunkSize();
451 }
452 }
453 return no + cur.first
454 }
455
456 // Find the line at the given vertical position, using the height
457 // information in the document tree.
458 function lineAtHeight(chunk, h) {
459 var n = chunk.first;
460 outer: do {
461 for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
462 var child = chunk.children[i$1], ch = child.height;
463 if (h < ch) { chunk = child; continue outer }
464 h -= ch;
465 n += child.chunkSize();
466 }
467 return n
468 } while (!chunk.lines)
469 var i = 0;
470 for (; i < chunk.lines.length; ++i) {
471 var line = chunk.lines[i], lh = line.height;
472 if (h < lh) { break }
473 h -= lh;
474 }
475 return n + i
476 }
477
478 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
479
480 function lineNumberFor(options, i) {
481 return String(options.lineNumberFormatter(i + options.firstLineNumber))
482 }
483
484 // A Pos instance represents a position within the text.
485 function Pos(line, ch, sticky) {
486 if ( sticky === void 0 ) sticky = null;
487
488 if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
489 this.line = line;
490 this.ch = ch;
491 this.sticky = sticky;
492 }
493
494 // Compare two positions, return 0 if they are the same, a negative
495 // number when a is less, and a positive number otherwise.
496 function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
497
498 function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
499
500 function copyPos(x) {return Pos(x.line, x.ch)}
501 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
502 function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
503
504 // Most of the external API clips given positions to make sure they
505 // actually exist within the document.
506 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
507 function clipPos(doc, pos) {
508 if (pos.line < doc.first) { return Pos(doc.first, 0) }
509 var last = doc.first + doc.size - 1;
510 if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
511 return clipToLen(pos, getLine(doc, pos.line).text.length)
512 }
513 function clipToLen(pos, linelen) {
514 var ch = pos.ch;
515 if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
516 else if (ch < 0) { return Pos(pos.line, 0) }
517 else { return pos }
518 }
519 function clipPosArray(doc, array) {
520 var out = [];
521 for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
522 return out
523 }
524
525 // Optimize some code when these features are not used.
526 var sawReadOnlySpans = false;
527 var sawCollapsedSpans = false;
528
529 function seeReadOnlySpans() {
530 sawReadOnlySpans = true;
531 }
532
533 function seeCollapsedSpans() {
534 sawCollapsedSpans = true;
535 }
536
537 // TEXTMARKER SPANS
538
539 function MarkedSpan(marker, from, to) {
540 this.marker = marker;
541 this.from = from; this.to = to;
542 }
543
544 // Search an array of spans for a span matching the given marker.
545 function getMarkedSpanFor(spans, marker) {
546 if (spans) { for (var i = 0; i < spans.length; ++i) {
547 var span = spans[i];
548 if (span.marker == marker) { return span }
549 } }
550 }
551 // Remove a span from an array, returning undefined if no spans are
552 // left (we don't store arrays for lines without spans).
553 function removeMarkedSpan(spans, span) {
554 var r;
555 for (var i = 0; i < spans.length; ++i)
556 { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
557 return r
558 }
559 // Add a span to a line.
560 function addMarkedSpan(line, span) {
561 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
562 span.marker.attachLine(line);
563 }
564
565 // Used for the algorithm that adjusts markers for a change in the
566 // document. These functions cut an array of spans at a given
567 // character position, returning an array of remaining chunks (or
568 // undefined if nothing remains).
569 function markedSpansBefore(old, startCh, isInsert) {
570 var nw;
571 if (old) { for (var i = 0; i < old.length; ++i) {
572 var span = old[i], marker = span.marker;
573 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
574 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
575 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
576 }
577 } }
578 return nw
579 }
580 function markedSpansAfter(old, endCh, isInsert) {
581 var nw;
582 if (old) { for (var i = 0; i < old.length; ++i) {
583 var span = old[i], marker = span.marker;
584 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
585 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
586 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
587 span.to == null ? null : span.to - endCh));
588 }
589 } }
590 return nw
591 }
592
593 // Given a change object, compute the new set of marker spans that
594 // cover the line in which the change took place. Removes spans
595 // entirely within the change, reconnects spans belonging to the
596 // same marker that appear on both sides of the change, and cuts off
597 // spans partially within the change. Returns an array of span
598 // arrays with one element for each line in (after) the change.
599 function stretchSpansOverChange(doc, change) {
600 if (change.full) { return null }
601 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
602 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
603 if (!oldFirst && !oldLast) { return null }
604
605 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
606 // Get the spans that 'stick out' on both sides
607 var first = markedSpansBefore(oldFirst, startCh, isInsert);
608 var last = markedSpansAfter(oldLast, endCh, isInsert);
609
610 // Next, merge those two ends
611 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
612 if (first) {
613 // Fix up .to properties of first
614 for (var i = 0; i < first.length; ++i) {
615 var span = first[i];
616 if (span.to == null) {
617 var found = getMarkedSpanFor(last, span.marker);
618 if (!found) { span.to = startCh; }
619 else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
620 }
621 }
622 }
623 if (last) {
624 // Fix up .from in last (or move them into first in case of sameLine)
625 for (var i$1 = 0; i$1 < last.length; ++i$1) {
626 var span$1 = last[i$1];
627 if (span$1.to != null) { span$1.to += offset; }
628 if (span$1.from == null) {
629 var found$1 = getMarkedSpanFor(first, span$1.marker);
630 if (!found$1) {
631 span$1.from = offset;
632 if (sameLine) { (first || (first = [])).push(span$1); }
633 }
634 } else {
635 span$1.from += offset;
636 if (sameLine) { (first || (first = [])).push(span$1); }
637 }
638 }
639 }
640 // Make sure we didn't create any zero-length spans
641 if (first) { first = clearEmptySpans(first); }
642 if (last && last != first) { last = clearEmptySpans(last); }
643
644 var newMarkers = [first];
645 if (!sameLine) {
646 // Fill gap with whole-line-spans
647 var gap = change.text.length - 2, gapMarkers;
648 if (gap > 0 && first)
649 { for (var i$2 = 0; i$2 < first.length; ++i$2)
650 { if (first[i$2].to == null)
651 { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
652 for (var i$3 = 0; i$3 < gap; ++i$3)
653 { newMarkers.push(gapMarkers); }
654 newMarkers.push(last);
655 }
656 return newMarkers
657 }
658
659 // Remove spans that are empty and don't have a clearWhenEmpty
660 // option of false.
661 function clearEmptySpans(spans) {
662 for (var i = 0; i < spans.length; ++i) {
663 var span = spans[i];
664 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
665 { spans.splice(i--, 1); }
666 }
667 if (!spans.length) { return null }
668 return spans
669 }
670
671 // Used to 'clip' out readOnly ranges when making a change.
672 function removeReadOnlyRanges(doc, from, to) {
673 var markers = null;
674 doc.iter(from.line, to.line + 1, function (line) {
675 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
676 var mark = line.markedSpans[i].marker;
677 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
678 { (markers || (markers = [])).push(mark); }
679 } }
680 });
681 if (!markers) { return null }
682 var parts = [{from: from, to: to}];
683 for (var i = 0; i < markers.length; ++i) {
684 var mk = markers[i], m = mk.find(0);
685 for (var j = 0; j < parts.length; ++j) {
686 var p = parts[j];
687 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
688 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
689 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
690 { newParts.push({from: p.from, to: m.from}); }
691 if (dto > 0 || !mk.inclusiveRight && !dto)
692 { newParts.push({from: m.to, to: p.to}); }
693 parts.splice.apply(parts, newParts);
694 j += newParts.length - 3;
695 }
696 }
697 return parts
698 }
699
700 // Connect or disconnect spans from a line.
701 function detachMarkedSpans(line) {
702 var spans = line.markedSpans;
703 if (!spans) { return }
704 for (var i = 0; i < spans.length; ++i)
705 { spans[i].marker.detachLine(line); }
706 line.markedSpans = null;
707 }
708 function attachMarkedSpans(line, spans) {
709 if (!spans) { return }
710 for (var i = 0; i < spans.length; ++i)
711 { spans[i].marker.attachLine(line); }
712 line.markedSpans = spans;
713 }
714
715 // Helpers used when computing which overlapping collapsed span
716 // counts as the larger one.
717 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
718 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
719
720 // Returns a number indicating which of two overlapping collapsed
721 // spans is larger (and thus includes the other). Falls back to
722 // comparing ids when the spans cover exactly the same range.
723 function compareCollapsedMarkers(a, b) {
724 var lenDiff = a.lines.length - b.lines.length;
725 if (lenDiff != 0) { return lenDiff }
726 var aPos = a.find(), bPos = b.find();
727 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
728 if (fromCmp) { return -fromCmp }
729 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
730 if (toCmp) { return toCmp }
731 return b.id - a.id
732 }
733
734 // Find out whether a line ends or starts in a collapsed span. If
735 // so, return the marker for that span.
736 function collapsedSpanAtSide(line, start) {
737 var sps = sawCollapsedSpans && line.markedSpans, found;
738 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
739 sp = sps[i];
740 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
741 (!found || compareCollapsedMarkers(found, sp.marker) < 0))
742 { found = sp.marker; }
743 } }
744 return found
745 }
746 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
747 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
748
749 // Test whether there exists a collapsed span that partially
750 // overlaps (covers the start or end, but not both) of a new span.
751 // Such overlap is not allowed.
752 function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
753 var line = getLine(doc, lineNo$$1);
754 var sps = sawCollapsedSpans && line.markedSpans;
755 if (sps) { for (var i = 0; i < sps.length; ++i) {
756 var sp = sps[i];
757 if (!sp.marker.collapsed) { continue }
758 var found = sp.marker.find(0);
759 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
760 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
761 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
762 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
763 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
764 { return true }
765 } }
766 }
767
768 // A visual line is a line as drawn on the screen. Folding, for
769 // example, can cause multiple logical lines to appear on the same
770 // visual line. This finds the start of the visual line that the
771 // given line is part of (usually that is the line itself).
772 function visualLine(line) {
773 var merged;
774 while (merged = collapsedSpanAtStart(line))
775 { line = merged.find(-1, true).line; }
776 return line
777 }
778
779 function visualLineEnd(line) {
780 var merged;
781 while (merged = collapsedSpanAtEnd(line))
782 { line = merged.find(1, true).line; }
783 return line
784 }
785
786 // Returns an array of logical lines that continue the visual line
787 // started by the argument, or undefined if there are no such lines.
788 function visualLineContinued(line) {
789 var merged, lines;
790 while (merged = collapsedSpanAtEnd(line)) {
791 line = merged.find(1, true).line
792 ;(lines || (lines = [])).push(line);
793 }
794 return lines
795 }
796
797 // Get the line number of the start of the visual line that the
798 // given line number is part of.
799 function visualLineNo(doc, lineN) {
800 var line = getLine(doc, lineN), vis = visualLine(line);
801 if (line == vis) { return lineN }
802 return lineNo(vis)
803 }
804
805 // Get the line number of the start of the next visual line after
806 // the given line.
807 function visualLineEndNo(doc, lineN) {
808 if (lineN > doc.lastLine()) { return lineN }
809 var line = getLine(doc, lineN), merged;
810 if (!lineIsHidden(doc, line)) { return lineN }
811 while (merged = collapsedSpanAtEnd(line))
812 { line = merged.find(1, true).line; }
813 return lineNo(line) + 1
814 }
815
816 // Compute whether a line is hidden. Lines count as hidden when they
817 // are part of a visual line that starts with another line, or when
818 // they are entirely covered by collapsed, non-widget span.
819 function lineIsHidden(doc, line) {
820 var sps = sawCollapsedSpans && line.markedSpans;
821 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
822 sp = sps[i];
823 if (!sp.marker.collapsed) { continue }
824 if (sp.from == null) { return true }
825 if (sp.marker.widgetNode) { continue }
826 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
827 { return true }
828 } }
829 }
830 function lineIsHiddenInner(doc, line, span) {
831 if (span.to == null) {
832 var end = span.marker.find(1, true);
833 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
834 }
835 if (span.marker.inclusiveRight && span.to == line.text.length)
836 { return true }
837 for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
838 sp = line.markedSpans[i];
839 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
840 (sp.to == null || sp.to != span.from) &&
841 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
842 lineIsHiddenInner(doc, line, sp)) { return true }
843 }
844 }
845
846 // Find the height above the given line.
847 function heightAtLine(lineObj) {
848 lineObj = visualLine(lineObj);
849
850 var h = 0, chunk = lineObj.parent;
851 for (var i = 0; i < chunk.lines.length; ++i) {
852 var line = chunk.lines[i];
853 if (line == lineObj) { break }
854 else { h += line.height; }
855 }
856 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
857 for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
858 var cur = p.children[i$1];
859 if (cur == chunk) { break }
860 else { h += cur.height; }
861 }
862 }
863 return h
864 }
865
866 // Compute the character length of a line, taking into account
867 // collapsed ranges (see markText) that might hide parts, and join
868 // other lines onto it.
869 function lineLength(line) {
870 if (line.height == 0) { return 0 }
871 var len = line.text.length, merged, cur = line;
872 while (merged = collapsedSpanAtStart(cur)) {
873 var found = merged.find(0, true);
874 cur = found.from.line;
875 len += found.from.ch - found.to.ch;
876 }
877 cur = line;
878 while (merged = collapsedSpanAtEnd(cur)) {
879 var found$1 = merged.find(0, true);
880 len -= cur.text.length - found$1.from.ch;
881 cur = found$1.to.line;
882 len += cur.text.length - found$1.to.ch;
883 }
884 return len
885 }
886
887 // Find the longest line in the document.
888 function findMaxLine(cm) {
889 var d = cm.display, doc = cm.doc;
890 d.maxLine = getLine(doc, doc.first);
891 d.maxLineLength = lineLength(d.maxLine);
892 d.maxLineChanged = true;
893 doc.iter(function (line) {
894 var len = lineLength(line);
895 if (len > d.maxLineLength) {
896 d.maxLineLength = len;
897 d.maxLine = line;
898 }
899 });
900 }
901
902 // BIDI HELPERS
903
904 function iterateBidiSections(order, from, to, f) {
905 if (!order) { return f(from, to, "ltr", 0) }
906 var found = false;
907 for (var i = 0; i < order.length; ++i) {
908 var part = order[i];
909 if (part.from < to && part.to > from || from == to && part.to == from) {
910 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
911 found = true;
912 }
913 }
914 if (!found) { f(from, to, "ltr"); }
915 }
916
917 var bidiOther = null;
918 function getBidiPartAt(order, ch, sticky) {
919 var found;
920 bidiOther = null;
921 for (var i = 0; i < order.length; ++i) {
922 var cur = order[i];
923 if (cur.from < ch && cur.to > ch) { return i }
924 if (cur.to == ch) {
925 if (cur.from != cur.to && sticky == "before") { found = i; }
926 else { bidiOther = i; }
927 }
928 if (cur.from == ch) {
929 if (cur.from != cur.to && sticky != "before") { found = i; }
930 else { bidiOther = i; }
931 }
932 }
933 return found != null ? found : bidiOther
934 }
935
936 // Bidirectional ordering algorithm
937 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
938 // that this (partially) implements.
939
940 // One-char codes used for character types:
941 // L (L): Left-to-Right
942 // R (R): Right-to-Left
943 // r (AL): Right-to-Left Arabic
944 // 1 (EN): European Number
945 // + (ES): European Number Separator
946 // % (ET): European Number Terminator
947 // n (AN): Arabic Number
948 // , (CS): Common Number Separator
949 // m (NSM): Non-Spacing Mark
950 // b (BN): Boundary Neutral
951 // s (B): Paragraph Separator
952 // t (S): Segment Separator
953 // w (WS): Whitespace
954 // N (ON): Other Neutrals
955
956 // Returns null if characters are ordered as they appear
957 // (left-to-right), or an array of sections ({from, to, level}
958 // objects) in the order in which they occur visually.
959 var bidiOrdering = (function() {
960 // Character types for codepoints 0 to 0xff
961 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
962 // Character types for codepoints 0x600 to 0x6f9
963 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
964 function charType(code) {
965 if (code <= 0xf7) { return lowTypes.charAt(code) }
966 else if (0x590 <= code && code <= 0x5f4) { return "R" }
967 else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
968 else if (0x6ee <= code && code <= 0x8ac) { return "r" }
969 else if (0x2000 <= code && code <= 0x200b) { return "w" }
970 else if (code == 0x200c) { return "b" }
971 else { return "L" }
972 }
973
974 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
975 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
976
977 function BidiSpan(level, from, to) {
978 this.level = level;
979 this.from = from; this.to = to;
980 }
981
982 return function(str, direction) {
983 var outerType = direction == "ltr" ? "L" : "R";
984
985 if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
986 var len = str.length, types = [];
987 for (var i = 0; i < len; ++i)
988 { types.push(charType(str.charCodeAt(i))); }
989
990 // W1. Examine each non-spacing mark (NSM) in the level run, and
991 // change the type of the NSM to the type of the previous
992 // character. If the NSM is at the start of the level run, it will
993 // get the type of sor.
994 for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
995 var type = types[i$1];
996 if (type == "m") { types[i$1] = prev; }
997 else { prev = type; }
998 }
999
1000 // W2. Search backwards from each instance of a European number
1001 // until the first strong type (R, L, AL, or sor) is found. If an
1002 // AL is found, change the type of the European number to Arabic
1003 // number.
1004 // W3. Change all ALs to R.
1005 for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
1006 var type$1 = types[i$2];
1007 if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
1008 else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
1009 }
1010
1011 // W4. A single European separator between two European numbers
1012 // changes to a European number. A single common separator between
1013 // two numbers of the same type changes to that type.
1014 for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
1015 var type$2 = types[i$3];
1016 if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
1017 else if (type$2 == "," && prev$1 == types[i$3+1] &&
1018 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
1019 prev$1 = type$2;
1020 }
1021
1022 // W5. A sequence of European terminators adjacent to European
1023 // numbers changes to all European numbers.
1024 // W6. Otherwise, separators and terminators change to Other
1025 // Neutral.
1026 for (var i$4 = 0; i$4 < len; ++i$4) {
1027 var type$3 = types[i$4];
1028 if (type$3 == ",") { types[i$4] = "N"; }
1029 else if (type$3 == "%") {
1030 var end = (void 0);
1031 for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
1032 var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
1033 for (var j = i$4; j < end; ++j) { types[j] = replace; }
1034 i$4 = end - 1;
1035 }
1036 }
1037
1038 // W7. Search backwards from each instance of a European number
1039 // until the first strong type (R, L, or sor) is found. If an L is
1040 // found, then change the type of the European number to L.
1041 for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
1042 var type$4 = types[i$5];
1043 if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
1044 else if (isStrong.test(type$4)) { cur$1 = type$4; }
1045 }
1046
1047 // N1. A sequence of neutrals takes the direction of the
1048 // surrounding strong text if the text on both sides has the same
1049 // direction. European and Arabic numbers act as if they were R in
1050 // terms of their influence on neutrals. Start-of-level-run (sor)
1051 // and end-of-level-run (eor) are used at level run boundaries.
1052 // N2. Any remaining neutrals take the embedding direction.
1053 for (var i$6 = 0; i$6 < len; ++i$6) {
1054 if (isNeutral.test(types[i$6])) {
1055 var end$1 = (void 0);
1056 for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
1057 var before = (i$6 ? types[i$6-1] : outerType) == "L";
1058 var after = (end$1 < len ? types[end$1] : outerType) == "L";
1059 var replace$1 = before == after ? (before ? "L" : "R") : outerType;
1060 for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
1061 i$6 = end$1 - 1;
1062 }
1063 }
1064
1065 // Here we depart from the documented algorithm, in order to avoid
1066 // building up an actual levels array. Since there are only three
1067 // levels (0, 1, 2) in an implementation that doesn't take
1068 // explicit embedding into account, we can build up the order on
1069 // the fly, without following the level-based algorithm.
1070 var order = [], m;
1071 for (var i$7 = 0; i$7 < len;) {
1072 if (countsAsLeft.test(types[i$7])) {
1073 var start = i$7;
1074 for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
1075 order.push(new BidiSpan(0, start, i$7));
1076 } else {
1077 var pos = i$7, at = order.length;
1078 for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
1079 for (var j$2 = pos; j$2 < i$7;) {
1080 if (countsAsNum.test(types[j$2])) {
1081 if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
1082 var nstart = j$2;
1083 for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
1084 order.splice(at, 0, new BidiSpan(2, nstart, j$2));
1085 pos = j$2;
1086 } else { ++j$2; }
1087 }
1088 if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
1089 }
1090 }
1091 if (direction == "ltr") {
1092 if (order[0].level == 1 && (m = str.match(/^\s+/))) {
1093 order[0].from = m[0].length;
1094 order.unshift(new BidiSpan(0, 0, m[0].length));
1095 }
1096 if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
1097 lst(order).to -= m[0].length;
1098 order.push(new BidiSpan(0, len - m[0].length, len));
1099 }
1100 }
1101
1102 return direction == "rtl" ? order.reverse() : order
1103 }
1104 })();
1105
1106 // Get the bidi ordering for the given line (and cache it). Returns
1107 // false for lines that are fully left-to-right, and an array of
1108 // BidiSpan objects otherwise.
1109 function getOrder(line, direction) {
1110 var order = line.order;
1111 if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
1112 return order
1113 }
1114
1115 // EVENT HANDLING
1116
1117 // Lightweight event framework. on/off also work on DOM nodes,
1118 // registering native DOM handlers.
1119
1120 var noHandlers = [];
1121
1122 var on = function(emitter, type, f) {
1123 if (emitter.addEventListener) {
1124 emitter.addEventListener(type, f, false);
1125 } else if (emitter.attachEvent) {
1126 emitter.attachEvent("on" + type, f);
1127 } else {
1128 var map$$1 = emitter._handlers || (emitter._handlers = {});
1129 map$$1[type] = (map$$1[type] || noHandlers).concat(f);
1130 }
1131 };
1132
1133 function getHandlers(emitter, type) {
1134 return emitter._handlers && emitter._handlers[type] || noHandlers
1135 }
1136
1137 function off(emitter, type, f) {
1138 if (emitter.removeEventListener) {
1139 emitter.removeEventListener(type, f, false);
1140 } else if (emitter.detachEvent) {
1141 emitter.detachEvent("on" + type, f);
1142 } else {
1143 var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
1144 if (arr) {
1145 var index = indexOf(arr, f);
1146 if (index > -1)
1147 { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
1148 }
1149 }
1150 }
1151
1152 function signal(emitter, type /*, values...*/) {
1153 var handlers = getHandlers(emitter, type);
1154 if (!handlers.length) { return }
1155 var args = Array.prototype.slice.call(arguments, 2);
1156 for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
1157 }
1158
1159 // The DOM events that CodeMirror handles can be overridden by
1160 // registering a (non-DOM) handler on the editor for the event name,
1161 // and preventDefault-ing the event in that handler.
1162 function signalDOMEvent(cm, e, override) {
1163 if (typeof e == "string")
1164 { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
1165 signal(cm, override || e.type, cm, e);
1166 return e_defaultPrevented(e) || e.codemirrorIgnore
1167 }
1168
1169 function signalCursorActivity(cm) {
1170 var arr = cm._handlers && cm._handlers.cursorActivity;
1171 if (!arr) { return }
1172 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
1173 for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
1174 { set.push(arr[i]); } }
1175 }
1176
1177 function hasHandler(emitter, type) {
1178 return getHandlers(emitter, type).length > 0
1179 }
1180
1181 // Add on and off methods to a constructor's prototype, to make
1182 // registering events on such objects more convenient.
1183 function eventMixin(ctor) {
1184 ctor.prototype.on = function(type, f) {on(this, type, f);};
1185 ctor.prototype.off = function(type, f) {off(this, type, f);};
1186 }
1187
1188 // Due to the fact that we still support jurassic IE versions, some
1189 // compatibility wrappers are needed.
1190
1191 function e_preventDefault(e) {
1192 if (e.preventDefault) { e.preventDefault(); }
1193 else { e.returnValue = false; }
1194 }
1195 function e_stopPropagation(e) {
1196 if (e.stopPropagation) { e.stopPropagation(); }
1197 else { e.cancelBubble = true; }
1198 }
1199 function e_defaultPrevented(e) {
1200 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
1201 }
1202 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
1203
1204 function e_target(e) {return e.target || e.srcElement}
1205 function e_button(e) {
1206 var b = e.which;
1207 if (b == null) {
1208 if (e.button & 1) { b = 1; }
1209 else if (e.button & 2) { b = 3; }
1210 else if (e.button & 4) { b = 2; }
1211 }
1212 if (mac && e.ctrlKey && b == 1) { b = 3; }
1213 return b
1214 }
1215
1216 // Detect drag-and-drop
1217 var dragAndDrop = function() {
1218 // There is *some* kind of drag-and-drop support in IE6-8, but I
1219 // couldn't get it to work yet.
1220 if (ie && ie_version < 9) { return false }
1221 var div = elt('div');
1222 return "draggable" in div || "dragDrop" in div
1223 }();
1224
1225 var zwspSupported;
1226 function zeroWidthElement(measure) {
1227 if (zwspSupported == null) {
1228 var test = elt("span", "\u200b");
1229 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
1230 if (measure.firstChild.offsetHeight != 0)
1231 { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
1232 }
1233 var node = zwspSupported ? elt("span", "\u200b") :
1234 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
1235 node.setAttribute("cm-text", "");
1236 return node
1237 }
1238
1239 // Feature-detect IE's crummy client rect reporting for bidi text
1240 var badBidiRects;
1241 function hasBadBidiRects(measure) {
1242 if (badBidiRects != null) { return badBidiRects }
1243 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
1244 var r0 = range(txt, 0, 1).getBoundingClientRect();
1245 var r1 = range(txt, 1, 2).getBoundingClientRect();
1246 removeChildren(measure);
1247 if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
1248 return badBidiRects = (r1.right - r0.right < 3)
1249 }
1250
1251 // See if "".split is the broken IE version, if so, provide an
1252 // alternative way to split lines.
1253 var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
1254 var pos = 0, result = [], l = string.length;
1255 while (pos <= l) {
1256 var nl = string.indexOf("\n", pos);
1257 if (nl == -1) { nl = string.length; }
1258 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
1259 var rt = line.indexOf("\r");
1260 if (rt != -1) {
1261 result.push(line.slice(0, rt));
1262 pos += rt + 1;
1263 } else {
1264 result.push(line);
1265 pos = nl + 1;
1266 }
1267 }
1268 return result
1269 } : function (string) { return string.split(/\r\n?|\n/); };
1270
1271 var hasSelection = window.getSelection ? function (te) {
1272 try { return te.selectionStart != te.selectionEnd }
1273 catch(e) { return false }
1274 } : function (te) {
1275 var range$$1;
1276 try {range$$1 = te.ownerDocument.selection.createRange();}
1277 catch(e) {}
1278 if (!range$$1 || range$$1.parentElement() != te) { return false }
1279 return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
1280 };
1281
1282 var hasCopyEvent = (function () {
1283 var e = elt("div");
1284 if ("oncopy" in e) { return true }
1285 e.setAttribute("oncopy", "return;");
1286 return typeof e.oncopy == "function"
1287 })();
1288
1289 var badZoomedRects = null;
1290 function hasBadZoomedRects(measure) {
1291 if (badZoomedRects != null) { return badZoomedRects }
1292 var node = removeChildrenAndAdd(measure, elt("span", "x"));
1293 var normal = node.getBoundingClientRect();
1294 var fromRange = range(node, 0, 1).getBoundingClientRect();
1295 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
1296 }
1297
1298 // Known modes, by name and by MIME
1299 var modes = {};
1300 var mimeModes = {};
1301
1302 // Extra arguments are stored as the mode's dependencies, which is
1303 // used by (legacy) mechanisms like loadmode.js to automatically
1304 // load a mode. (Preferred mechanism is the require/define calls.)
1305 function defineMode(name, mode) {
1306 if (arguments.length > 2)
1307 { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
1308 modes[name] = mode;
1309 }
1310
1311 function defineMIME(mime, spec) {
1312 mimeModes[mime] = spec;
1313 }
1314
1315 // Given a MIME type, a {name, ...options} config object, or a name
1316 // string, return a mode config object.
1317 function resolveMode(spec) {
1318 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
1319 spec = mimeModes[spec];
1320 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
1321 var found = mimeModes[spec.name];
1322 if (typeof found == "string") { found = {name: found}; }
1323 spec = createObj(found, spec);
1324 spec.name = found.name;
1325 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
1326 return resolveMode("application/xml")
1327 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
1328 return resolveMode("application/json")
1329 }
1330 if (typeof spec == "string") { return {name: spec} }
1331 else { return spec || {name: "null"} }
1332 }
1333
1334 // Given a mode spec (anything that resolveMode accepts), find and
1335 // initialize an actual mode object.
1336 function getMode(options, spec) {
1337 spec = resolveMode(spec);
1338 var mfactory = modes[spec.name];
1339 if (!mfactory) { return getMode(options, "text/plain") }
1340 var modeObj = mfactory(options, spec);
1341 if (modeExtensions.hasOwnProperty(spec.name)) {
1342 var exts = modeExtensions[spec.name];
1343 for (var prop in exts) {
1344 if (!exts.hasOwnProperty(prop)) { continue }
1345 if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
1346 modeObj[prop] = exts[prop];
1347 }
1348 }
1349 modeObj.name = spec.name;
1350 if (spec.helperType) { modeObj.helperType = spec.helperType; }
1351 if (spec.modeProps) { for (var prop$1 in spec.modeProps)
1352 { modeObj[prop$1] = spec.modeProps[prop$1]; } }
1353
1354 return modeObj
1355 }
1356
1357 // This can be used to attach properties to mode objects from
1358 // outside the actual mode definition.
1359 var modeExtensions = {};
1360 function extendMode(mode, properties) {
1361 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
1362 copyObj(properties, exts);
1363 }
1364
1365 function copyState(mode, state) {
1366 if (state === true) { return state }
1367 if (mode.copyState) { return mode.copyState(state) }
1368 var nstate = {};
1369 for (var n in state) {
1370 var val = state[n];
1371 if (val instanceof Array) { val = val.concat([]); }
1372 nstate[n] = val;
1373 }
1374 return nstate
1375 }
1376
1377 // Given a mode and a state (for that mode), find the inner mode and
1378 // state at the position that the state refers to.
1379 function innerMode(mode, state) {
1380 var info;
1381 while (mode.innerMode) {
1382 info = mode.innerMode(state);
1383 if (!info || info.mode == mode) { break }
1384 state = info.state;
1385 mode = info.mode;
1386 }
1387 return info || {mode: mode, state: state}
1388 }
1389
1390 function startState(mode, a1, a2) {
1391 return mode.startState ? mode.startState(a1, a2) : true
1392 }
1393
1394 // STRING STREAM
1395
1396 // Fed to the mode parsers, provides helper functions to make
1397 // parsers more succinct.
1398
1399 var StringStream = function(string, tabSize, lineOracle) {
1400 this.pos = this.start = 0;
1401 this.string = string;
1402 this.tabSize = tabSize || 8;
1403 this.lastColumnPos = this.lastColumnValue = 0;
1404 this.lineStart = 0;
1405 this.lineOracle = lineOracle;
1406 };
1407
1408 StringStream.prototype.eol = function () {return this.pos >= this.string.length};
1409 StringStream.prototype.sol = function () {return this.pos == this.lineStart};
1410 StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
1411 StringStream.prototype.next = function () {
1412 if (this.pos < this.string.length)
1413 { return this.string.charAt(this.pos++) }
1414 };
1415 StringStream.prototype.eat = function (match) {
1416 var ch = this.string.charAt(this.pos);
1417 var ok;
1418 if (typeof match == "string") { ok = ch == match; }
1419 else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
1420 if (ok) {++this.pos; return ch}
1421 };
1422 StringStream.prototype.eatWhile = function (match) {
1423 var start = this.pos;
1424 while (this.eat(match)){}
1425 return this.pos > start
1426 };
1427 StringStream.prototype.eatSpace = function () {
1428 var this$1 = this;
1429
1430 var start = this.pos;
1431 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
1432 return this.pos > start
1433 };
1434 StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
1435 StringStream.prototype.skipTo = function (ch) {
1436 var found = this.string.indexOf(ch, this.pos);
1437 if (found > -1) {this.pos = found; return true}
1438 };
1439 StringStream.prototype.backUp = function (n) {this.pos -= n;};
1440 StringStream.prototype.column = function () {
1441 if (this.lastColumnPos < this.start) {
1442 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
1443 this.lastColumnPos = this.start;
1444 }
1445 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
1446 };
1447 StringStream.prototype.indentation = function () {
1448 return countColumn(this.string, null, this.tabSize) -
1449 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
1450 };
1451 StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
1452 if (typeof pattern == "string") {
1453 var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
1454 var substr = this.string.substr(this.pos, pattern.length);
1455 if (cased(substr) == cased(pattern)) {
1456 if (consume !== false) { this.pos += pattern.length; }
1457 return true
1458 }
1459 } else {
1460 var match = this.string.slice(this.pos).match(pattern);
1461 if (match && match.index > 0) { return null }
1462 if (match && consume !== false) { this.pos += match[0].length; }
1463 return match
1464 }
1465 };
1466 StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
1467 StringStream.prototype.hideFirstChars = function (n, inner) {
1468 this.lineStart += n;
1469 try { return inner() }
1470 finally { this.lineStart -= n; }
1471 };
1472 StringStream.prototype.lookAhead = function (n) {
1473 var oracle = this.lineOracle;
1474 return oracle && oracle.lookAhead(n)
1475 };
1476 StringStream.prototype.baseToken = function () {
1477 var oracle = this.lineOracle;
1478 return oracle && oracle.baseToken(this.pos)
1479 };
1480
1481 var SavedContext = function(state, lookAhead) {
1482 this.state = state;
1483 this.lookAhead = lookAhead;
1484 };
1485
1486 var Context = function(doc, state, line, lookAhead) {
1487 this.state = state;
1488 this.doc = doc;
1489 this.line = line;
1490 this.maxLookAhead = lookAhead || 0;
1491 this.baseTokens = null;
1492 this.baseTokenPos = 1;
1493 };
1494
1495 Context.prototype.lookAhead = function (n) {
1496 var line = this.doc.getLine(this.line + n);
1497 if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
1498 return line
1499 };
1500
1501 Context.prototype.baseToken = function (n) {
1502 var this$1 = this;
1503
1504 if (!this.baseTokens) { return null }
1505 while (this.baseTokens[this.baseTokenPos] <= n)
1506 { this$1.baseTokenPos += 2; }
1507 var type = this.baseTokens[this.baseTokenPos + 1];
1508 return {type: type && type.replace(/( |^)overlay .*/, ""),
1509 size: this.baseTokens[this.baseTokenPos] - n}
1510 };
1511
1512 Context.prototype.nextLine = function () {
1513 this.line++;
1514 if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1515 };
1516
1517 Context.fromSaved = function (doc, saved, line) {
1518 if (saved instanceof SavedContext)
1519 { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
1520 else
1521 { return new Context(doc, copyState(doc.mode, saved), line) }
1522 };
1523
1524 Context.prototype.save = function (copy) {
1525 var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
1526 return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
1527 };
1528
1529
1530 // Compute a style array (an array starting with a mode generation
1531 // -- for invalidation -- followed by pairs of end positions and
1532 // style strings), which is used to highlight the tokens on the
1533 // line.
1534 function highlightLine(cm, line, context, forceToEnd) {
1535 // A styles array always starts with a number identifying the
1536 // mode/overlays that it is based on (for easy invalidation).
1537 var st = [cm.state.modeGen], lineClasses = {};
1538 // Compute the base array of styles
1539 runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
1540 lineClasses, forceToEnd);
1541 var state = context.state;
1542
1543 // Run overlays, adjust style array.
1544 var loop = function ( o ) {
1545 context.baseTokens = st;
1546 var overlay = cm.state.overlays[o], i = 1, at = 0;
1547 context.state = true;
1548 runMode(cm, line.text, overlay.mode, context, function (end, style) {
1549 var start = i;
1550 // Ensure there's a token end at the current position, and that i points at it
1551 while (at < end) {
1552 var i_end = st[i];
1553 if (i_end > end)
1554 { st.splice(i, 1, end, st[i+1], i_end); }
1555 i += 2;
1556 at = Math.min(end, i_end);
1557 }
1558 if (!style) { return }
1559 if (overlay.opaque) {
1560 st.splice(start, i - start, end, "overlay " + style);
1561 i = start + 2;
1562 } else {
1563 for (; start < i; start += 2) {
1564 var cur = st[start+1];
1565 st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
1566 }
1567 }
1568 }, lineClasses);
1569 context.state = state;
1570 context.baseTokens = null;
1571 context.baseTokenPos = 1;
1572 };
1573
1574 for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1575
1576 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
1577 }
1578
1579 function getLineStyles(cm, line, updateFrontier) {
1580 if (!line.styles || line.styles[0] != cm.state.modeGen) {
1581 var context = getContextBefore(cm, lineNo(line));
1582 var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
1583 var result = highlightLine(cm, line, context);
1584 if (resetState) { context.state = resetState; }
1585 line.stateAfter = context.save(!resetState);
1586 line.styles = result.styles;
1587 if (result.classes) { line.styleClasses = result.classes; }
1588 else if (line.styleClasses) { line.styleClasses = null; }
1589 if (updateFrontier === cm.doc.highlightFrontier)
1590 { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
1591 }
1592 return line.styles
1593 }
1594
1595 function getContextBefore(cm, n, precise) {
1596 var doc = cm.doc, display = cm.display;
1597 if (!doc.mode.startState) { return new Context(doc, true, n) }
1598 var start = findStartLine(cm, n, precise);
1599 var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
1600 var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
1601
1602 doc.iter(start, n, function (line) {
1603 processLine(cm, line.text, context);
1604 var pos = context.line;
1605 line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
1606 context.nextLine();
1607 });
1608 if (precise) { doc.modeFrontier = context.line; }
1609 return context
1610 }
1611
1612 // Lightweight form of highlight -- proceed over this line and
1613 // update state, but don't save a style array. Used for lines that
1614 // aren't currently visible.
1615 function processLine(cm, text, context, startAt) {
1616 var mode = cm.doc.mode;
1617 var stream = new StringStream(text, cm.options.tabSize, context);
1618 stream.start = stream.pos = startAt || 0;
1619 if (text == "") { callBlankLine(mode, context.state); }
1620 while (!stream.eol()) {
1621 readToken(mode, stream, context.state);
1622 stream.start = stream.pos;
1623 }
1624 }
1625
1626 function callBlankLine(mode, state) {
1627 if (mode.blankLine) { return mode.blankLine(state) }
1628 if (!mode.innerMode) { return }
1629 var inner = innerMode(mode, state);
1630 if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
1631 }
1632
1633 function readToken(mode, stream, state, inner) {
1634 for (var i = 0; i < 10; i++) {
1635 if (inner) { inner[0] = innerMode(mode, state).mode; }
1636 var style = mode.token(stream, state);
1637 if (stream.pos > stream.start) { return style }
1638 }
1639 throw new Error("Mode " + mode.name + " failed to advance stream.")
1640 }
1641
1642 var Token = function(stream, type, state) {
1643 this.start = stream.start; this.end = stream.pos;
1644 this.string = stream.current();
1645 this.type = type || null;
1646 this.state = state;
1647 };
1648
1649 // Utility for getTokenAt and getLineTokens
1650 function takeToken(cm, pos, precise, asArray) {
1651 var doc = cm.doc, mode = doc.mode, style;
1652 pos = clipPos(doc, pos);
1653 var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
1654 var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
1655 if (asArray) { tokens = []; }
1656 while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
1657 stream.start = stream.pos;
1658 style = readToken(mode, stream, context.state);
1659 if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
1660 }
1661 return asArray ? tokens : new Token(stream, style, context.state)
1662 }
1663
1664 function extractLineClasses(type, output) {
1665 if (type) { for (;;) {
1666 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
1667 if (!lineClass) { break }
1668 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
1669 var prop = lineClass[1] ? "bgClass" : "textClass";
1670 if (output[prop] == null)
1671 { output[prop] = lineClass[2]; }
1672 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
1673 { output[prop] += " " + lineClass[2]; }
1674 } }
1675 return type
1676 }
1677
1678 // Run the given mode's parser over a line, calling f for each token.
1679 function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
1680 var flattenSpans = mode.flattenSpans;
1681 if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
1682 var curStart = 0, curStyle = null;
1683 var stream = new StringStream(text, cm.options.tabSize, context), style;
1684 var inner = cm.options.addModeClass && [null];
1685 if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
1686 while (!stream.eol()) {
1687 if (stream.pos > cm.options.maxHighlightLength) {
1688 flattenSpans = false;
1689 if (forceToEnd) { processLine(cm, text, context, stream.pos); }
1690 stream.pos = text.length;
1691 style = null;
1692 } else {
1693 style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
1694 }
1695 if (inner) {
1696 var mName = inner[0].name;
1697 if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
1698 }
1699 if (!flattenSpans || curStyle != style) {
1700 while (curStart < stream.start) {
1701 curStart = Math.min(stream.start, curStart + 5000);
1702 f(curStart, curStyle);
1703 }
1704 curStyle = style;
1705 }
1706 stream.start = stream.pos;
1707 }
1708 while (curStart < stream.pos) {
1709 // Webkit seems to refuse to render text nodes longer than 57444
1710 // characters, and returns inaccurate measurements in nodes
1711 // starting around 5000 chars.
1712 var pos = Math.min(stream.pos, curStart + 5000);
1713 f(pos, curStyle);
1714 curStart = pos;
1715 }
1716 }
1717
1718 // Finds the line to start with when starting a parse. Tries to
1719 // find a line with a stateAfter, so that it can start with a
1720 // valid state. If that fails, it returns the line with the
1721 // smallest indentation, which tends to need the least context to
1722 // parse correctly.
1723 function findStartLine(cm, n, precise) {
1724 var minindent, minline, doc = cm.doc;
1725 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1726 for (var search = n; search > lim; --search) {
1727 if (search <= doc.first) { return doc.first }
1728 var line = getLine(doc, search - 1), after = line.stateAfter;
1729 if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
1730 { return search }
1731 var indented = countColumn(line.text, null, cm.options.tabSize);
1732 if (minline == null || minindent > indented) {
1733 minline = search - 1;
1734 minindent = indented;
1735 }
1736 }
1737 return minline
1738 }
1739
1740 function retreatFrontier(doc, n) {
1741 doc.modeFrontier = Math.min(doc.modeFrontier, n);
1742 if (doc.highlightFrontier < n - 10) { return }
1743 var start = doc.first;
1744 for (var line = n - 1; line > start; line--) {
1745 var saved = getLine(doc, line).stateAfter;
1746 // change is on 3
1747 // state on line 1 looked ahead 2 -- so saw 3
1748 // test 1 + 2 < 3 should cover this
1749 if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
1750 start = line + 1;
1751 break
1752 }
1753 }
1754 doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1755 }
1756
1757 // LINE DATA STRUCTURE
1758
1759 // Line objects. These hold state related to a line, including
1760 // highlighting info (the styles array).
1761 var Line = function(text, markedSpans, estimateHeight) {
1762 this.text = text;
1763 attachMarkedSpans(this, markedSpans);
1764 this.height = estimateHeight ? estimateHeight(this) : 1;
1765 };
1766
1767 Line.prototype.lineNo = function () { return lineNo(this) };
1768 eventMixin(Line);
1769
1770 // Change the content (text, markers) of a line. Automatically
1771 // invalidates cached information and tries to re-estimate the
1772 // line's height.
1773 function updateLine(line, text, markedSpans, estimateHeight) {
1774 line.text = text;
1775 if (line.stateAfter) { line.stateAfter = null; }
1776 if (line.styles) { line.styles = null; }
1777 if (line.order != null) { line.order = null; }
1778 detachMarkedSpans(line);
1779 attachMarkedSpans(line, markedSpans);
1780 var estHeight = estimateHeight ? estimateHeight(line) : 1;
1781 if (estHeight != line.height) { updateLineHeight(line, estHeight); }
1782 }
1783
1784 // Detach a line from the document tree and its markers.
1785 function cleanUpLine(line) {
1786 line.parent = null;
1787 detachMarkedSpans(line);
1788 }
1789
1790 // Convert a style as returned by a mode (either null, or a string
1791 // containing one or more styles) to a CSS style. This is cached,
1792 // and also looks for line-wide styles.
1793 var styleToClassCache = {};
1794 var styleToClassCacheWithMode = {};
1795 function interpretTokenStyle(style, options) {
1796 if (!style || /^\s*$/.test(style)) { return null }
1797 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
1798 return cache[style] ||
1799 (cache[style] = style.replace(/\S+/g, "cm-$&"))
1800 }
1801
1802 // Render the DOM representation of the text of a line. Also builds
1803 // up a 'line map', which points at the DOM nodes that represent
1804 // specific stretches of text, and is used by the measuring code.
1805 // The returned object contains the DOM node, this map, and
1806 // information about line-wide styles that were set by the mode.
1807 function buildLineContent(cm, lineView) {
1808 // The padding-right forces the element to have a 'border', which
1809 // is needed on Webkit to be able to get line-level bounding
1810 // rectangles for it (in measureChar).
1811 var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
1812 var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
1813 col: 0, pos: 0, cm: cm,
1814 trailingSpace: false,
1815 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
1816 lineView.measure = {};
1817
1818 // Iterate over the logical lines that make up this visual line.
1819 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
1820 var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
1821 builder.pos = 0;
1822 builder.addToken = buildToken;
1823 // Optionally wire in some hacks into the token-rendering
1824 // algorithm, to deal with browser quirks.
1825 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
1826 { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
1827 builder.map = [];
1828 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
1829 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
1830 if (line.styleClasses) {
1831 if (line.styleClasses.bgClass)
1832 { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
1833 if (line.styleClasses.textClass)
1834 { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
1835 }
1836
1837 // Ensure at least a single node is present, for measuring.
1838 if (builder.map.length == 0)
1839 { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
1840
1841 // Store the map and a cache object for the current logical line
1842 if (i == 0) {
1843 lineView.measure.map = builder.map;
1844 lineView.measure.cache = {};
1845 } else {
1846 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
1847 ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
1848 }
1849 }
1850
1851 // See issue #2901
1852 if (webkit) {
1853 var last = builder.content.lastChild;
1854 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
1855 { builder.content.className = "cm-tab-wrap-hack"; }
1856 }
1857
1858 signal(cm, "renderLine", cm, lineView.line, builder.pre);
1859 if (builder.pre.className)
1860 { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1861
1862 return builder
1863 }
1864
1865 function defaultSpecialCharPlaceholder(ch) {
1866 var token = elt("span", "\u2022", "cm-invalidchar");
1867 token.title = "\\u" + ch.charCodeAt(0).toString(16);
1868 token.setAttribute("aria-label", token.title);
1869 return token
1870 }
1871
1872 // Build up the DOM representation for a single token, and add it to
1873 // the line map. Takes care to render special characters separately.
1874 function buildToken(builder, text, style, startStyle, endStyle, title, css) {
1875 if (!text) { return }
1876 var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
1877 var special = builder.cm.state.specialChars, mustWrap = false;
1878 var content;
1879 if (!special.test(text)) {
1880 builder.col += text.length;
1881 content = document.createTextNode(displayText);
1882 builder.map.push(builder.pos, builder.pos + text.length, content);
1883 if (ie && ie_version < 9) { mustWrap = true; }
1884 builder.pos += text.length;
1885 } else {
1886 content = document.createDocumentFragment();
1887 var pos = 0;
1888 while (true) {
1889 special.lastIndex = pos;
1890 var m = special.exec(text);
1891 var skipped = m ? m.index - pos : text.length - pos;
1892 if (skipped) {
1893 var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
1894 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
1895 else { content.appendChild(txt); }
1896 builder.map.push(builder.pos, builder.pos + skipped, txt);
1897 builder.col += skipped;
1898 builder.pos += skipped;
1899 }
1900 if (!m) { break }
1901 pos += skipped + 1;
1902 var txt$1 = (void 0);
1903 if (m[0] == "\t") {
1904 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
1905 txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
1906 txt$1.setAttribute("role", "presentation");
1907 txt$1.setAttribute("cm-text", "\t");
1908 builder.col += tabWidth;
1909 } else if (m[0] == "\r" || m[0] == "\n") {
1910 txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
1911 txt$1.setAttribute("cm-text", m[0]);
1912 builder.col += 1;
1913 } else {
1914 txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
1915 txt$1.setAttribute("cm-text", m[0]);
1916 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
1917 else { content.appendChild(txt$1); }
1918 builder.col += 1;
1919 }
1920 builder.map.push(builder.pos, builder.pos + 1, txt$1);
1921 builder.pos++;
1922 }
1923 }
1924 builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
1925 if (style || startStyle || endStyle || mustWrap || css) {
1926 var fullStyle = style || "";
1927 if (startStyle) { fullStyle += startStyle; }
1928 if (endStyle) { fullStyle += endStyle; }
1929 var token = elt("span", [content], fullStyle, css);
1930 if (title) { token.title = title; }
1931 return builder.content.appendChild(token)
1932 }
1933 builder.content.appendChild(content);
1934 }
1935
1936 function splitSpaces(text, trailingBefore) {
1937 if (text.length > 1 && !/ /.test(text)) { return text }
1938 var spaceBefore = trailingBefore, result = "";
1939 for (var i = 0; i < text.length; i++) {
1940 var ch = text.charAt(i);
1941 if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
1942 { ch = "\u00a0"; }
1943 result += ch;
1944 spaceBefore = ch == " ";
1945 }
1946 return result
1947 }
1948
1949 // Work around nonsense dimensions being reported for stretches of
1950 // right-to-left text.
1951 function buildTokenBadBidi(inner, order) {
1952 return function (builder, text, style, startStyle, endStyle, title, css) {
1953 style = style ? style + " cm-force-border" : "cm-force-border";
1954 var start = builder.pos, end = start + text.length;
1955 for (;;) {
1956 // Find the part that overlaps with the start of this text
1957 var part = (void 0);
1958 for (var i = 0; i < order.length; i++) {
1959 part = order[i];
1960 if (part.to > start && part.from <= start) { break }
1961 }
1962 if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
1963 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
1964 startStyle = null;
1965 text = text.slice(part.to - start);
1966 start = part.to;
1967 }
1968 }
1969 }
1970
1971 function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
1972 var widget = !ignoreWidget && marker.widgetNode;
1973 if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
1974 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
1975 if (!widget)
1976 { widget = builder.content.appendChild(document.createElement("span")); }
1977 widget.setAttribute("cm-marker", marker.id);
1978 }
1979 if (widget) {
1980 builder.cm.display.input.setUneditable(widget);
1981 builder.content.appendChild(widget);
1982 }
1983 builder.pos += size;
1984 builder.trailingSpace = false;
1985 }
1986
1987 // Outputs a number of spans to make up a line, taking highlighting
1988 // and marked text into account.
1989 function insertLineContent(line, builder, styles) {
1990 var spans = line.markedSpans, allText = line.text, at = 0;
1991 if (!spans) {
1992 for (var i$1 = 1; i$1 < styles.length; i$1+=2)
1993 { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
1994 return
1995 }
1996
1997 var len = allText.length, pos = 0, i = 1, text = "", style, css;
1998 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
1999 for (;;) {
2000 if (nextChange == pos) { // Update current marker set
2001 spanStyle = spanEndStyle = spanStartStyle = title = css = "";
2002 collapsed = null; nextChange = Infinity;
2003 var foundBookmarks = [], endStyles = (void 0);
2004 for (var j = 0; j < spans.length; ++j) {
2005 var sp = spans[j], m = sp.marker;
2006 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
2007 foundBookmarks.push(m);
2008 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
2009 if (sp.to != null && sp.to != pos && nextChange > sp.to) {
2010 nextChange = sp.to;
2011 spanEndStyle = "";
2012 }
2013 if (m.className) { spanStyle += " " + m.className; }
2014 if (m.css) { css = (css ? css + ";" : "") + m.css; }
2015 if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
2016 if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
2017 if (m.title && !title) { title = m.title; }
2018 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
2019 { collapsed = sp; }
2020 } else if (sp.from > pos && nextChange > sp.from) {
2021 nextChange = sp.from;
2022 }
2023 }
2024 if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
2025 { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
2026
2027 if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
2028 { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
2029 if (collapsed && (collapsed.from || 0) == pos) {
2030 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
2031 collapsed.marker, collapsed.from == null);
2032 if (collapsed.to == null) { return }
2033 if (collapsed.to == pos) { collapsed = false; }
2034 }
2035 }
2036 if (pos >= len) { break }
2037
2038 var upto = Math.min(len, nextChange);
2039 while (true) {
2040 if (text) {
2041 var end = pos + text.length;
2042 if (!collapsed) {
2043 var tokenText = end > upto ? text.slice(0, upto - pos) : text;
2044 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
2045 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
2046 }
2047 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
2048 pos = end;
2049 spanStartStyle = "";
2050 }
2051 text = allText.slice(at, at = styles[i++]);
2052 style = interpretTokenStyle(styles[i++], builder.cm.options);
2053 }
2054 }
2055 }
2056
2057
2058 // These objects are used to represent the visible (currently drawn)
2059 // part of the document. A LineView may correspond to multiple
2060 // logical lines, if those are connected by collapsed ranges.
2061 function LineView(doc, line, lineN) {
2062 // The starting line
2063 this.line = line;
2064 // Continuing lines, if any
2065 this.rest = visualLineContinued(line);
2066 // Number of logical lines in this visual line
2067 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
2068 this.node = this.text = null;
2069 this.hidden = lineIsHidden(doc, line);
2070 }
2071
2072 // Create a range of LineView objects for the given lines.
2073 function buildViewArray(cm, from, to) {
2074 var array = [], nextPos;
2075 for (var pos = from; pos < to; pos = nextPos) {
2076 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2077 nextPos = pos + view.size;
2078 array.push(view);
2079 }
2080 return array
2081 }
2082
2083 var operationGroup = null;
2084
2085 function pushOperation(op) {
2086 if (operationGroup) {
2087 operationGroup.ops.push(op);
2088 } else {
2089 op.ownsGroup = operationGroup = {
2090 ops: [op],
2091 delayedCallbacks: []
2092 };
2093 }
2094 }
2095
2096 function fireCallbacksForOps(group) {
2097 // Calls delayed callbacks and cursorActivity handlers until no
2098 // new ones appear
2099 var callbacks = group.delayedCallbacks, i = 0;
2100 do {
2101 for (; i < callbacks.length; i++)
2102 { callbacks[i].call(null); }
2103 for (var j = 0; j < group.ops.length; j++) {
2104 var op = group.ops[j];
2105 if (op.cursorActivityHandlers)
2106 { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2107 { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
2108 }
2109 } while (i < callbacks.length)
2110 }
2111
2112 function finishOperation(op, endCb) {
2113 var group = op.ownsGroup;
2114 if (!group) { return }
2115
2116 try { fireCallbacksForOps(group); }
2117 finally {
2118 operationGroup = null;
2119 endCb(group);
2120 }
2121 }
2122
2123 var orphanDelayedCallbacks = null;
2124
2125 // Often, we want to signal events at a point where we are in the
2126 // middle of some work, but don't want the handler to start calling
2127 // other methods on the editor, which might be in an inconsistent
2128 // state or simply not expect any other events to happen.
2129 // signalLater looks whether there are any handlers, and schedules
2130 // them to be executed when the last operation ends, or, if no
2131 // operation is active, when a timeout fires.
2132 function signalLater(emitter, type /*, values...*/) {
2133 var arr = getHandlers(emitter, type);
2134 if (!arr.length) { return }
2135 var args = Array.prototype.slice.call(arguments, 2), list;
2136 if (operationGroup) {
2137 list = operationGroup.delayedCallbacks;
2138 } else if (orphanDelayedCallbacks) {
2139 list = orphanDelayedCallbacks;
2140 } else {
2141 list = orphanDelayedCallbacks = [];
2142 setTimeout(fireOrphanDelayed, 0);
2143 }
2144 var loop = function ( i ) {
2145 list.push(function () { return arr[i].apply(null, args); });
2146 };
2147
2148 for (var i = 0; i < arr.length; ++i)
2149 loop( i );
2150 }
2151
2152 function fireOrphanDelayed() {
2153 var delayed = orphanDelayedCallbacks;
2154 orphanDelayedCallbacks = null;
2155 for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
2156 }
2157
2158 // When an aspect of a line changes, a string is added to
2159 // lineView.changes. This updates the relevant part of the line's
2160 // DOM structure.
2161 function updateLineForChanges(cm, lineView, lineN, dims) {
2162 for (var j = 0; j < lineView.changes.length; j++) {
2163 var type = lineView.changes[j];
2164 if (type == "text") { updateLineText(cm, lineView); }
2165 else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
2166 else if (type == "class") { updateLineClasses(cm, lineView); }
2167 else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
2168 }
2169 lineView.changes = null;
2170 }
2171
2172 // Lines with gutter elements, widgets or a background class need to
2173 // be wrapped, and have the extra elements added to the wrapper div
2174 function ensureLineWrapped(lineView) {
2175 if (lineView.node == lineView.text) {
2176 lineView.node = elt("div", null, null, "position: relative");
2177 if (lineView.text.parentNode)
2178 { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
2179 lineView.node.appendChild(lineView.text);
2180 if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
2181 }
2182 return lineView.node
2183 }
2184
2185 function updateLineBackground(cm, lineView) {
2186 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
2187 if (cls) { cls += " CodeMirror-linebackground"; }
2188 if (lineView.background) {
2189 if (cls) { lineView.background.className = cls; }
2190 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
2191 } else if (cls) {
2192 var wrap = ensureLineWrapped(lineView);
2193 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
2194 cm.display.input.setUneditable(lineView.background);
2195 }
2196 }
2197
2198 // Wrapper around buildLineContent which will reuse the structure
2199 // in display.externalMeasured when possible.
2200 function getLineContent(cm, lineView) {
2201 var ext = cm.display.externalMeasured;
2202 if (ext && ext.line == lineView.line) {
2203 cm.display.externalMeasured = null;
2204 lineView.measure = ext.measure;
2205 return ext.built
2206 }
2207 return buildLineContent(cm, lineView)
2208 }
2209
2210 // Redraw the line's text. Interacts with the background and text
2211 // classes because the mode may output tokens that influence these
2212 // classes.
2213 function updateLineText(cm, lineView) {
2214 var cls = lineView.text.className;
2215 var built = getLineContent(cm, lineView);
2216 if (lineView.text == lineView.node) { lineView.node = built.pre; }
2217 lineView.text.parentNode.replaceChild(built.pre, lineView.text);
2218 lineView.text = built.pre;
2219 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
2220 lineView.bgClass = built.bgClass;
2221 lineView.textClass = built.textClass;
2222 updateLineClasses(cm, lineView);
2223 } else if (cls) {
2224 lineView.text.className = cls;
2225 }
2226 }
2227
2228 function updateLineClasses(cm, lineView) {
2229 updateLineBackground(cm, lineView);
2230 if (lineView.line.wrapClass)
2231 { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
2232 else if (lineView.node != lineView.text)
2233 { lineView.node.className = ""; }
2234 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
2235 lineView.text.className = textClass || "";
2236 }
2237
2238 function updateLineGutter(cm, lineView, lineN, dims) {
2239 if (lineView.gutter) {
2240 lineView.node.removeChild(lineView.gutter);
2241 lineView.gutter = null;
2242 }
2243 if (lineView.gutterBackground) {
2244 lineView.node.removeChild(lineView.gutterBackground);
2245 lineView.gutterBackground = null;
2246 }
2247 if (lineView.line.gutterClass) {
2248 var wrap = ensureLineWrapped(lineView);
2249 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
2250 ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
2251 cm.display.input.setUneditable(lineView.gutterBackground);
2252 wrap.insertBefore(lineView.gutterBackground, lineView.text);
2253 }
2254 var markers = lineView.line.gutterMarkers;
2255 if (cm.options.lineNumbers || markers) {
2256 var wrap$1 = ensureLineWrapped(lineView);
2257 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
2258 cm.display.input.setUneditable(gutterWrap);
2259 wrap$1.insertBefore(gutterWrap, lineView.text);
2260 if (lineView.line.gutterClass)
2261 { gutterWrap.className += " " + lineView.line.gutterClass; }
2262 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
2263 { lineView.lineNumber = gutterWrap.appendChild(
2264 elt("div", lineNumberFor(cm.options, lineN),
2265 "CodeMirror-linenumber CodeMirror-gutter-elt",
2266 ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
2267 if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
2268 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
2269 if (found)
2270 { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
2271 ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
2272 } }
2273 }
2274 }
2275
2276 function updateLineWidgets(cm, lineView, dims) {
2277 if (lineView.alignable) { lineView.alignable = null; }
2278 for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
2279 next = node.nextSibling;
2280 if (node.className == "CodeMirror-linewidget")
2281 { lineView.node.removeChild(node); }
2282 }
2283 insertLineWidgets(cm, lineView, dims);
2284 }
2285
2286 // Build a line's DOM representation from scratch
2287 function buildLineElement(cm, lineView, lineN, dims) {
2288 var built = getLineContent(cm, lineView);
2289 lineView.text = lineView.node = built.pre;
2290 if (built.bgClass) { lineView.bgClass = built.bgClass; }
2291 if (built.textClass) { lineView.textClass = built.textClass; }
2292
2293 updateLineClasses(cm, lineView);
2294 updateLineGutter(cm, lineView, lineN, dims);
2295 insertLineWidgets(cm, lineView, dims);
2296 return lineView.node
2297 }
2298
2299 // A lineView may contain multiple logical lines (when merged by
2300 // collapsed spans). The widgets for all of them need to be drawn.
2301 function insertLineWidgets(cm, lineView, dims) {
2302 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
2303 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2304 { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
2305 }
2306
2307 function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
2308 if (!line.widgets) { return }
2309 var wrap = ensureLineWrapped(lineView);
2310 for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
2311 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
2312 if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
2313 positionLineWidget(widget, node, lineView, dims);
2314 cm.display.input.setUneditable(node);
2315 if (allowAbove && widget.above)
2316 { wrap.insertBefore(node, lineView.gutter || lineView.text); }
2317 else
2318 { wrap.appendChild(node); }
2319 signalLater(widget, "redraw");
2320 }
2321 }
2322
2323 function positionLineWidget(widget, node, lineView, dims) {
2324 if (widget.noHScroll) {
2325 (lineView.alignable || (lineView.alignable = [])).push(node);
2326 var width = dims.wrapperWidth;
2327 node.style.left = dims.fixedPos + "px";
2328 if (!widget.coverGutter) {
2329 width -= dims.gutterTotalWidth;
2330 node.style.paddingLeft = dims.gutterTotalWidth + "px";
2331 }
2332 node.style.width = width + "px";
2333 }
2334 if (widget.coverGutter) {
2335 node.style.zIndex = 5;
2336 node.style.position = "relative";
2337 if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2338 }
2339 }
2340
2341 function widgetHeight(widget) {
2342 if (widget.height != null) { return widget.height }
2343 var cm = widget.doc.cm;
2344 if (!cm) { return 0 }
2345 if (!contains(document.body, widget.node)) {
2346 var parentStyle = "position: relative;";
2347 if (widget.coverGutter)
2348 { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
2349 if (widget.noHScroll)
2350 { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
2351 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
2352 }
2353 return widget.height = widget.node.parentNode.offsetHeight
2354 }
2355
2356 // Return true when the given mouse event happened in a widget
2357 function eventInWidget(display, e) {
2358 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2359 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
2360 (n.parentNode == display.sizer && n != display.mover))
2361 { return true }
2362 }
2363 }
2364
2365 // POSITION MEASUREMENT
2366
2367 function paddingTop(display) {return display.lineSpace.offsetTop}
2368 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
2369 function paddingH(display) {
2370 if (display.cachedPaddingH) { return display.cachedPaddingH }
2371 var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2372 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2373 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2374 if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
2375 return data
2376 }
2377
2378 function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
2379 function displayWidth(cm) {
2380 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
2381 }
2382 function displayHeight(cm) {
2383 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
2384 }
2385
2386 // Ensure the lineView.wrapping.heights array is populated. This is
2387 // an array of bottom offsets for the lines that make up a drawn
2388 // line. When lineWrapping is on, there might be more than one
2389 // height.
2390 function ensureLineHeights(cm, lineView, rect) {
2391 var wrapping = cm.options.lineWrapping;
2392 var curWidth = wrapping && displayWidth(cm);
2393 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2394 var heights = lineView.measure.heights = [];
2395 if (wrapping) {
2396 lineView.measure.width = curWidth;
2397 var rects = lineView.text.firstChild.getClientRects();
2398 for (var i = 0; i < rects.length - 1; i++) {
2399 var cur = rects[i], next = rects[i + 1];
2400 if (Math.abs(cur.bottom - next.bottom) > 2)
2401 { heights.push((cur.bottom + next.top) / 2 - rect.top); }
2402 }
2403 }
2404 heights.push(rect.bottom - rect.top);
2405 }
2406 }
2407
2408 // Find a line map (mapping character offsets to text nodes) and a
2409 // measurement cache for the given line number. (A line view might
2410 // contain multiple lines when collapsed ranges are present.)
2411 function mapFromLineView(lineView, line, lineN) {
2412 if (lineView.line == line)
2413 { return {map: lineView.measure.map, cache: lineView.measure.cache} }
2414 for (var i = 0; i < lineView.rest.length; i++)
2415 { if (lineView.rest[i] == line)
2416 { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
2417 for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
2418 { if (lineNo(lineView.rest[i$1]) > lineN)
2419 { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
2420 }
2421
2422 // Render a line into the hidden node display.externalMeasured. Used
2423 // when measurement is needed for a line that's not in the viewport.
2424 function updateExternalMeasurement(cm, line) {
2425 line = visualLine(line);
2426 var lineN = lineNo(line);
2427 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2428 view.lineN = lineN;
2429 var built = view.built = buildLineContent(cm, view);
2430 view.text = built.pre;
2431 removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2432 return view
2433 }
2434
2435 // Get a {top, bottom, left, right} box (in line-local coordinates)
2436 // for a given character.
2437 function measureChar(cm, line, ch, bias) {
2438 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
2439 }
2440
2441 // Find a line view that corresponds to the given line number.
2442 function findViewForLine(cm, lineN) {
2443 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2444 { return cm.display.view[findViewIndex(cm, lineN)] }
2445 var ext = cm.display.externalMeasured;
2446 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2447 { return ext }
2448 }
2449
2450 // Measurement can be split in two steps, the set-up work that
2451 // applies to the whole line, and the measurement of the actual
2452 // character. Functions like coordsChar, that need to do a lot of
2453 // measurements in a row, can thus ensure that the set-up work is
2454 // only done once.
2455 function prepareMeasureForLine(cm, line) {
2456 var lineN = lineNo(line);
2457 var view = findViewForLine(cm, lineN);
2458 if (view && !view.text) {
2459 view = null;
2460 } else if (view && view.changes) {
2461 updateLineForChanges(cm, view, lineN, getDimensions(cm));
2462 cm.curOp.forceUpdate = true;
2463 }
2464 if (!view)
2465 { view = updateExternalMeasurement(cm, line); }
2466
2467 var info = mapFromLineView(view, line, lineN);
2468 return {
2469 line: line, view: view, rect: null,
2470 map: info.map, cache: info.cache, before: info.before,
2471 hasHeights: false
2472 }
2473 }
2474
2475 // Given a prepared measurement object, measures the position of an
2476 // actual character (or fetches it from the cache).
2477 function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2478 if (prepared.before) { ch = -1; }
2479 var key = ch + (bias || ""), found;
2480 if (prepared.cache.hasOwnProperty(key)) {
2481 found = prepared.cache[key];
2482 } else {
2483 if (!prepared.rect)
2484 { prepared.rect = prepared.view.text.getBoundingClientRect(); }
2485 if (!prepared.hasHeights) {
2486 ensureLineHeights(cm, prepared.view, prepared.rect);
2487 prepared.hasHeights = true;
2488 }
2489 found = measureCharInner(cm, prepared, ch, bias);
2490 if (!found.bogus) { prepared.cache[key] = found; }
2491 }
2492 return {left: found.left, right: found.right,
2493 top: varHeight ? found.rtop : found.top,
2494 bottom: varHeight ? found.rbottom : found.bottom}
2495 }
2496
2497 var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2498
2499 function nodeAndOffsetInLineMap(map$$1, ch, bias) {
2500 var node, start, end, collapse, mStart, mEnd;
2501 // First, search the line map for the text node corresponding to,
2502 // or closest to, the target character.
2503 for (var i = 0; i < map$$1.length; i += 3) {
2504 mStart = map$$1[i];
2505 mEnd = map$$1[i + 1];
2506 if (ch < mStart) {
2507 start = 0; end = 1;
2508 collapse = "left";
2509 } else if (ch < mEnd) {
2510 start = ch - mStart;
2511 end = start + 1;
2512 } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
2513 end = mEnd - mStart;
2514 start = end - 1;
2515 if (ch >= mEnd) { collapse = "right"; }
2516 }
2517 if (start != null) {
2518 node = map$$1[i + 2];
2519 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2520 { collapse = bias; }
2521 if (bias == "left" && start == 0)
2522 { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
2523 node = map$$1[(i -= 3) + 2];
2524 collapse = "left";
2525 } }
2526 if (bias == "right" && start == mEnd - mStart)
2527 { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
2528 node = map$$1[(i += 3) + 2];
2529 collapse = "right";
2530 } }
2531 break
2532 }
2533 }
2534 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
2535 }
2536
2537 function getUsefulRect(rects, bias) {
2538 var rect = nullRect;
2539 if (bias == "left") { for (var i = 0; i < rects.length; i++) {
2540 if ((rect = rects[i]).left != rect.right) { break }
2541 } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
2542 if ((rect = rects[i$1]).left != rect.right) { break }
2543 } }
2544 return rect
2545 }
2546
2547 function measureCharInner(cm, prepared, ch, bias) {
2548 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2549 var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2550
2551 var rect;
2552 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2553 for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2554 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
2555 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
2556 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2557 { rect = node.parentNode.getBoundingClientRect(); }
2558 else
2559 { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
2560 if (rect.left || rect.right || start == 0) { break }
2561 end = start;
2562 start = start - 1;
2563 collapse = "right";
2564 }
2565 if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
2566 } else { // If it is a widget, simply get the box for the whole widget.
2567 if (start > 0) { collapse = bias = "right"; }
2568 var rects;
2569 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2570 { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
2571 else
2572 { rect = node.getBoundingClientRect(); }
2573 }
2574 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2575 var rSpan = node.parentNode.getClientRects()[0];
2576 if (rSpan)
2577 { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
2578 else
2579 { rect = nullRect; }
2580 }
2581
2582 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2583 var mid = (rtop + rbot) / 2;
2584 var heights = prepared.view.measure.heights;
2585 var i = 0;
2586 for (; i < heights.length - 1; i++)
2587 { if (mid < heights[i]) { break } }
2588 var top = i ? heights[i - 1] : 0, bot = heights[i];
2589 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2590 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2591 top: top, bottom: bot};
2592 if (!rect.left && !rect.right) { result.bogus = true; }
2593 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2594
2595 return result
2596 }
2597
2598 // Work around problem with bounding client rects on ranges being
2599 // returned incorrectly when zoomed on IE10 and below.
2600 function maybeUpdateRectForZooming(measure, rect) {
2601 if (!window.screen || screen.logicalXDPI == null ||
2602 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2603 { return rect }
2604 var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2605 var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2606 return {left: rect.left * scaleX, right: rect.right * scaleX,
2607 top: rect.top * scaleY, bottom: rect.bottom * scaleY}
2608 }
2609
2610 function clearLineMeasurementCacheFor(lineView) {
2611 if (lineView.measure) {
2612 lineView.measure.cache = {};
2613 lineView.measure.heights = null;
2614 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2615 { lineView.measure.caches[i] = {}; } }
2616 }
2617 }
2618
2619 function clearLineMeasurementCache(cm) {
2620 cm.display.externalMeasure = null;
2621 removeChildren(cm.display.lineMeasure);
2622 for (var i = 0; i < cm.display.view.length; i++)
2623 { clearLineMeasurementCacheFor(cm.display.view[i]); }
2624 }
2625
2626 function clearCaches(cm) {
2627 clearLineMeasurementCache(cm);
2628 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2629 if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
2630 cm.display.lineNumChars = null;
2631 }
2632
2633 function pageScrollX() {
2634 // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
2635 // which causes page_Offset and bounding client rects to use
2636 // different reference viewports and invalidate our calculations.
2637 if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
2638 return window.pageXOffset || (document.documentElement || document.body).scrollLeft
2639 }
2640 function pageScrollY() {
2641 if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
2642 return window.pageYOffset || (document.documentElement || document.body).scrollTop
2643 }
2644
2645 function widgetTopHeight(lineObj) {
2646 var height = 0;
2647 if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
2648 { height += widgetHeight(lineObj.widgets[i]); } } }
2649 return height
2650 }
2651
2652 // Converts a {top, bottom, left, right} box from line-local
2653 // coordinates into another coordinate system. Context may be one of
2654 // "line", "div" (display.lineDiv), "local"./null (editor), "window",
2655 // or "page".
2656 function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
2657 if (!includeWidgets) {
2658 var height = widgetTopHeight(lineObj);
2659 rect.top += height; rect.bottom += height;
2660 }
2661 if (context == "line") { return rect }
2662 if (!context) { context = "local"; }
2663 var yOff = heightAtLine(lineObj);
2664 if (context == "local") { yOff += paddingTop(cm.display); }
2665 else { yOff -= cm.display.viewOffset; }
2666 if (context == "page" || context == "window") {
2667 var lOff = cm.display.lineSpace.getBoundingClientRect();
2668 yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2669 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2670 rect.left += xOff; rect.right += xOff;
2671 }
2672 rect.top += yOff; rect.bottom += yOff;
2673 return rect
2674 }
2675
2676 // Coverts a box from "div" coords to another coordinate system.
2677 // Context may be "window", "page", "div", or "local"./null.
2678 function fromCoordSystem(cm, coords, context) {
2679 if (context == "div") { return coords }
2680 var left = coords.left, top = coords.top;
2681 // First move into "page" coordinate system
2682 if (context == "page") {
2683 left -= pageScrollX();
2684 top -= pageScrollY();
2685 } else if (context == "local" || !context) {
2686 var localBox = cm.display.sizer.getBoundingClientRect();
2687 left += localBox.left;
2688 top += localBox.top;
2689 }
2690
2691 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2692 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
2693 }
2694
2695 function charCoords(cm, pos, context, lineObj, bias) {
2696 if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
2697 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
2698 }
2699
2700 // Returns a box for a given cursor position, which may have an
2701 // 'other' property containing the position of the secondary cursor
2702 // on a bidi boundary.
2703 // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
2704 // and after `char - 1` in writing order of `char - 1`
2705 // A cursor Pos(line, char, "after") is on the same visual line as `char`
2706 // and before `char` in writing order of `char`
2707 // Examples (upper-case letters are RTL, lower-case are LTR):
2708 // Pos(0, 1, ...)
2709 // before after
2710 // ab a|b a|b
2711 // aB a|B aB|
2712 // Ab |Ab A|b
2713 // AB B|A B|A
2714 // Every position after the last character on a line is considered to stick
2715 // to the last character on the line.
2716 function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2717 lineObj = lineObj || getLine(cm.doc, pos.line);
2718 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2719 function get(ch, right) {
2720 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2721 if (right) { m.left = m.right; } else { m.right = m.left; }
2722 return intoCoordSystem(cm, lineObj, m, context)
2723 }
2724 var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
2725 if (ch >= lineObj.text.length) {
2726 ch = lineObj.text.length;
2727 sticky = "before";
2728 } else if (ch <= 0) {
2729 ch = 0;
2730 sticky = "after";
2731 }
2732 if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
2733
2734 function getBidi(ch, partPos, invert) {
2735 var part = order[partPos], right = part.level == 1;
2736 return get(invert ? ch - 1 : ch, right != invert)
2737 }
2738 var partPos = getBidiPartAt(order, ch, sticky);
2739 var other = bidiOther;
2740 var val = getBidi(ch, partPos, sticky == "before");
2741 if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
2742 return val
2743 }
2744
2745 // Used to cheaply estimate the coordinates for a position. Used for
2746 // intermediate scroll updates.
2747 function estimateCoords(cm, pos) {
2748 var left = 0;
2749 pos = clipPos(cm.doc, pos);
2750 if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
2751 var lineObj = getLine(cm.doc, pos.line);
2752 var top = heightAtLine(lineObj) + paddingTop(cm.display);
2753 return {left: left, right: left, top: top, bottom: top + lineObj.height}
2754 }
2755
2756 // Positions returned by coordsChar contain some extra information.
2757 // xRel is the relative x position of the input coordinates compared
2758 // to the found position (so xRel > 0 means the coordinates are to
2759 // the right of the character position, for example). When outside
2760 // is true, that means the coordinates lie outside the line's
2761 // vertical range.
2762 function PosWithInfo(line, ch, sticky, outside, xRel) {
2763 var pos = Pos(line, ch, sticky);
2764 pos.xRel = xRel;
2765 if (outside) { pos.outside = true; }
2766 return pos
2767 }
2768
2769 // Compute the character position closest to the given coordinates.
2770 // Input must be lineSpace-local ("div" coordinate system).
2771 function coordsChar(cm, x, y) {
2772 var doc = cm.doc;
2773 y += cm.display.viewOffset;
2774 if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
2775 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2776 if (lineN > last)
2777 { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
2778 if (x < 0) { x = 0; }
2779
2780 var lineObj = getLine(doc, lineN);
2781 for (;;) {
2782 var found = coordsCharInner(cm, lineObj, lineN, x, y);
2783 var merged = collapsedSpanAtEnd(lineObj);
2784 var mergedPos = merged && merged.find(0, true);
2785 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2786 { lineN = lineNo(lineObj = mergedPos.to.line); }
2787 else
2788 { return found }
2789 }
2790 }
2791
2792 function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
2793 y -= widgetTopHeight(lineObj);
2794 var end = lineObj.text.length;
2795 var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
2796 end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
2797 return {begin: begin, end: end}
2798 }
2799
2800 function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
2801 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2802 var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
2803 return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
2804 }
2805
2806 // Returns true if the given side of a box is after the given
2807 // coordinates, in top-to-bottom, left-to-right order.
2808 function boxIsAfter(box, x, y, left) {
2809 return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
2810 }
2811
2812 function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
2813 // Move y into line-local coordinate space
2814 y -= heightAtLine(lineObj);
2815 var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2816 // When directly calling `measureCharPrepared`, we have to adjust
2817 // for the widgets at this line.
2818 var widgetHeight$$1 = widgetTopHeight(lineObj);
2819 var begin = 0, end = lineObj.text.length, ltr = true;
2820
2821 var order = getOrder(lineObj, cm.doc.direction);
2822 // If the line isn't plain left-to-right text, first figure out
2823 // which bidi section the coordinates fall into.
2824 if (order) {
2825 var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
2826 (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
2827 ltr = part.level != 1;
2828 // The awkward -1 offsets are needed because findFirst (called
2829 // on these below) will treat its first bound as inclusive,
2830 // second as exclusive, but we want to actually address the
2831 // characters in the part's range
2832 begin = ltr ? part.from : part.to - 1;
2833 end = ltr ? part.to : part.from - 1;
2834 }
2835
2836 // A binary search to find the first character whose bounding box
2837 // starts after the coordinates. If we run across any whose box wrap
2838 // the coordinates, store that.
2839 var chAround = null, boxAround = null;
2840 var ch = findFirst(function (ch) {
2841 var box = measureCharPrepared(cm, preparedMeasure, ch);
2842 box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
2843 if (!boxIsAfter(box, x, y, false)) { return false }
2844 if (box.top <= y && box.left <= x) {
2845 chAround = ch;
2846 boxAround = box;
2847 }
2848 return true
2849 }, begin, end);
2850
2851 var baseX, sticky, outside = false;
2852 // If a box around the coordinates was found, use that
2853 if (boxAround) {
2854 // Distinguish coordinates nearer to the left or right side of the box
2855 var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
2856 ch = chAround + (atStart ? 0 : 1);
2857 sticky = atStart ? "after" : "before";
2858 baseX = atLeft ? boxAround.left : boxAround.right;
2859 } else {
2860 // (Adjust for extended bound, if necessary.)
2861 if (!ltr && (ch == end || ch == begin)) { ch++; }
2862 // To determine which side to associate with, get the box to the
2863 // left of the character and compare it's vertical position to the
2864 // coordinates
2865 sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
2866 (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
2867 "after" : "before";
2868 // Now get accurate coordinates for this place, in order to get a
2869 // base X position
2870 var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
2871 baseX = coords.left;
2872 outside = y < coords.top || y >= coords.bottom;
2873 }
2874
2875 ch = skipExtendingChars(lineObj.text, ch, 1);
2876 return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
2877 }
2878
2879 function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
2880 // Bidi parts are sorted left-to-right, and in a non-line-wrapping
2881 // situation, we can take this ordering to correspond to the visual
2882 // ordering. This finds the first part whose end is after the given
2883 // coordinates.
2884 var index = findFirst(function (i) {
2885 var part = order[i], ltr = part.level != 1;
2886 return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
2887 "line", lineObj, preparedMeasure), x, y, true)
2888 }, 0, order.length - 1);
2889 var part = order[index];
2890 // If this isn't the first part, the part's start is also after
2891 // the coordinates, and the coordinates aren't on the same line as
2892 // that start, move one part back.
2893 if (index > 0) {
2894 var ltr = part.level != 1;
2895 var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
2896 "line", lineObj, preparedMeasure);
2897 if (boxIsAfter(start, x, y, true) && start.top > y)
2898 { part = order[index - 1]; }
2899 }
2900 return part
2901 }
2902
2903 function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
2904 // In a wrapped line, rtl text on wrapping boundaries can do things
2905 // that don't correspond to the ordering in our `order` array at
2906 // all, so a binary search doesn't work, and we want to return a
2907 // part that only spans one line so that the binary search in
2908 // coordsCharInner is safe. As such, we first find the extent of the
2909 // wrapped line, and then do a flat search in which we discard any
2910 // spans that aren't on the line.
2911 var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
2912 var begin = ref.begin;
2913 var end = ref.end;
2914 if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
2915 var part = null, closestDist = null;
2916 for (var i = 0; i < order.length; i++) {
2917 var p = order[i];
2918 if (p.from >= end || p.to <= begin) { continue }
2919 var ltr = p.level != 1;
2920 var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
2921 // Weigh against spans ending before this, so that they are only
2922 // picked if nothing ends after
2923 var dist = endX < x ? x - endX + 1e9 : endX - x;
2924 if (!part || closestDist > dist) {
2925 part = p;
2926 closestDist = dist;
2927 }
2928 }
2929 if (!part) { part = order[order.length - 1]; }
2930 // Clip the part to the wrapped line.
2931 if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
2932 if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
2933 return part
2934 }
2935
2936 var measureText;
2937 // Compute the default text height.
2938 function textHeight(display) {
2939 if (display.cachedTextHeight != null) { return display.cachedTextHeight }
2940 if (measureText == null) {
2941 measureText = elt("pre");
2942 // Measure a bunch of lines, for browsers that compute
2943 // fractional heights.
2944 for (var i = 0; i < 49; ++i) {
2945 measureText.appendChild(document.createTextNode("x"));
2946 measureText.appendChild(elt("br"));
2947 }
2948 measureText.appendChild(document.createTextNode("x"));
2949 }
2950 removeChildrenAndAdd(display.measure, measureText);
2951 var height = measureText.offsetHeight / 50;
2952 if (height > 3) { display.cachedTextHeight = height; }
2953 removeChildren(display.measure);
2954 return height || 1
2955 }
2956
2957 // Compute the default character width.
2958 function charWidth(display) {
2959 if (display.cachedCharWidth != null) { return display.cachedCharWidth }
2960 var anchor = elt("span", "xxxxxxxxxx");
2961 var pre = elt("pre", [anchor]);
2962 removeChildrenAndAdd(display.measure, pre);
2963 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2964 if (width > 2) { display.cachedCharWidth = width; }
2965 return width || 10
2966 }
2967
2968 // Do a bulk-read of the DOM positions and sizes needed to draw the
2969 // view, so that we don't interleave reading and writing to the DOM.
2970 function getDimensions(cm) {
2971 var d = cm.display, left = {}, width = {};
2972 var gutterLeft = d.gutters.clientLeft;
2973 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
2974 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
2975 width[cm.options.gutters[i]] = n.clientWidth;
2976 }
2977 return {fixedPos: compensateForHScroll(d),
2978 gutterTotalWidth: d.gutters.offsetWidth,
2979 gutterLeft: left,
2980 gutterWidth: width,
2981 wrapperWidth: d.wrapper.clientWidth}
2982 }
2983
2984 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
2985 // but using getBoundingClientRect to get a sub-pixel-accurate
2986 // result.
2987 function compensateForHScroll(display) {
2988 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
2989 }
2990
2991 // Returns a function that estimates the height of a line, to use as
2992 // first approximation until the line becomes visible (and is thus
2993 // properly measurable).
2994 function estimateHeight(cm) {
2995 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
2996 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
2997 return function (line) {
2998 if (lineIsHidden(cm.doc, line)) { return 0 }
2999
3000 var widgetsHeight = 0;
3001 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
3002 if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
3003 } }
3004
3005 if (wrapping)
3006 { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
3007 else
3008 { return widgetsHeight + th }
3009 }
3010 }
3011
3012 function estimateLineHeights(cm) {
3013 var doc = cm.doc, est = estimateHeight(cm);
3014 doc.iter(function (line) {
3015 var estHeight = est(line);
3016 if (estHeight != line.height) { updateLineHeight(line, estHeight); }
3017 });
3018 }
3019
3020 // Given a mouse event, find the corresponding position. If liberal
3021 // is false, it checks whether a gutter or scrollbar was clicked,
3022 // and returns null if it was. forRect is used by rectangular
3023 // selections, and tries to estimate a character position even for
3024 // coordinates beyond the right of the text.
3025 function posFromMouse(cm, e, liberal, forRect) {
3026 var display = cm.display;
3027 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
3028
3029 var x, y, space = display.lineSpace.getBoundingClientRect();
3030 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3031 try { x = e.clientX - space.left; y = e.clientY - space.top; }
3032 catch (e) { return null }
3033 var coords = coordsChar(cm, x, y), line;
3034 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3035 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3036 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3037 }
3038 return coords
3039 }
3040
3041 // Find the view element corresponding to a given line. Return null
3042 // when the line isn't visible.
3043 function findViewIndex(cm, n) {
3044 if (n >= cm.display.viewTo) { return null }
3045 n -= cm.display.viewFrom;
3046 if (n < 0) { return null }
3047 var view = cm.display.view;
3048 for (var i = 0; i < view.length; i++) {
3049 n -= view[i].size;
3050 if (n < 0) { return i }
3051 }
3052 }
3053
3054 function updateSelection(cm) {
3055 cm.display.input.showSelection(cm.display.input.prepareSelection());
3056 }
3057
3058 function prepareSelection(cm, primary) {
3059 if ( primary === void 0 ) primary = true;
3060
3061 var doc = cm.doc, result = {};
3062 var curFragment = result.cursors = document.createDocumentFragment();
3063 var selFragment = result.selection = document.createDocumentFragment();
3064
3065 for (var i = 0; i < doc.sel.ranges.length; i++) {
3066 if (!primary && i == doc.sel.primIndex) { continue }
3067 var range$$1 = doc.sel.ranges[i];
3068 if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
3069 var collapsed = range$$1.empty();
3070 if (collapsed || cm.options.showCursorWhenSelecting)
3071 { drawSelectionCursor(cm, range$$1.head, curFragment); }
3072 if (!collapsed)
3073 { drawSelectionRange(cm, range$$1, selFragment); }
3074 }
3075 return result
3076 }
3077
3078 // Draws a cursor for the given range
3079 function drawSelectionCursor(cm, head, output) {
3080 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
3081
3082 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
3083 cursor.style.left = pos.left + "px";
3084 cursor.style.top = pos.top + "px";
3085 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
3086
3087 if (pos.other) {
3088 // Secondary cursor, shown when on a 'jump' in bi-directional text
3089 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
3090 otherCursor.style.display = "";
3091 otherCursor.style.left = pos.other.left + "px";
3092 otherCursor.style.top = pos.other.top + "px";
3093 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
3094 }
3095 }
3096
3097 function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3098
3099 // Draws the given range as a highlighted selection
3100 function drawSelectionRange(cm, range$$1, output) {
3101 var display = cm.display, doc = cm.doc;
3102 var fragment = document.createDocumentFragment();
3103 var padding = paddingH(cm.display), leftSide = padding.left;
3104 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
3105 var docLTR = doc.direction == "ltr";
3106
3107 function add(left, top, width, bottom) {
3108 if (top < 0) { top = 0; }
3109 top = Math.round(top);
3110 bottom = Math.round(bottom);
3111 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")));
3112 }
3113
3114 function drawForLine(line, fromArg, toArg) {
3115 var lineObj = getLine(doc, line);
3116 var lineLen = lineObj.text.length;
3117 var start, end;
3118 function coords(ch, bias) {
3119 return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
3120 }
3121
3122 function wrapX(pos, dir, side) {
3123 var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
3124 var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
3125 var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
3126 return coords(ch, prop)[prop]
3127 }
3128
3129 var order = getOrder(lineObj, doc.direction);
3130 iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
3131 var ltr = dir == "ltr";
3132 var fromPos = coords(from, ltr ? "left" : "right");
3133 var toPos = coords(to - 1, ltr ? "right" : "left");
3134
3135 var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
3136 var first = i == 0, last = !order || i == order.length - 1;
3137 if (toPos.top - fromPos.top <= 3) { // Single line
3138 var openLeft = (docLTR ? openStart : openEnd) && first;
3139 var openRight = (docLTR ? openEnd : openStart) && last;
3140 var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
3141 var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
3142 add(left, fromPos.top, right - left, fromPos.bottom);
3143 } else { // Multiple lines
3144 var topLeft, topRight, botLeft, botRight;
3145 if (ltr) {
3146 topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
3147 topRight = docLTR ? rightSide : wrapX(from, dir, "before");
3148 botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
3149 botRight = docLTR && openEnd && last ? rightSide : toPos.right;
3150 } else {
3151 topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
3152 topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
3153 botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
3154 botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
3155 }
3156 add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
3157 if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
3158 add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
3159 }
3160
3161 if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
3162 if (cmpCoords(toPos, start) < 0) { start = toPos; }
3163 if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
3164 if (cmpCoords(toPos, end) < 0) { end = toPos; }
3165 });
3166 return {start: start, end: end}
3167 }
3168
3169 var sFrom = range$$1.from(), sTo = range$$1.to();
3170 if (sFrom.line == sTo.line) {
3171 drawForLine(sFrom.line, sFrom.ch, sTo.ch);
3172 } else {
3173 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3174 var singleVLine = visualLine(fromLine) == visualLine(toLine);
3175 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
3176 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
3177 if (singleVLine) {
3178 if (leftEnd.top < rightStart.top - 2) {
3179 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
3180 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
3181 } else {
3182 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
3183 }
3184 }
3185 if (leftEnd.bottom < rightStart.top)
3186 { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3187 }
3188
3189 output.appendChild(fragment);
3190 }
3191
3192 // Cursor-blinking
3193 function restartBlink(cm) {
3194 if (!cm.state.focused) { return }
3195 var display = cm.display;
3196 clearInterval(display.blinker);
3197 var on = true;
3198 display.cursorDiv.style.visibility = "";
3199 if (cm.options.cursorBlinkRate > 0)
3200 { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
3201 cm.options.cursorBlinkRate); }
3202 else if (cm.options.cursorBlinkRate < 0)
3203 { display.cursorDiv.style.visibility = "hidden"; }
3204 }
3205
3206 function ensureFocus(cm) {
3207 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
3208 }
3209
3210 function delayBlurEvent(cm) {
3211 cm.state.delayingBlurEvent = true;
3212 setTimeout(function () { if (cm.state.delayingBlurEvent) {
3213 cm.state.delayingBlurEvent = false;
3214 onBlur(cm);
3215 } }, 100);
3216 }
3217
3218 function onFocus(cm, e) {
3219 if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
3220
3221 if (cm.options.readOnly == "nocursor") { return }
3222 if (!cm.state.focused) {
3223 signal(cm, "focus", cm, e);
3224 cm.state.focused = true;
3225 addClass(cm.display.wrapper, "CodeMirror-focused");
3226 // This test prevents this from firing when a context
3227 // menu is closed (since the input reset would kill the
3228 // select-all detection hack)
3229 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3230 cm.display.input.reset();
3231 if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
3232 }
3233 cm.display.input.receivedFocus();
3234 }
3235 restartBlink(cm);
3236 }
3237 function onBlur(cm, e) {
3238 if (cm.state.delayingBlurEvent) { return }
3239
3240 if (cm.state.focused) {
3241 signal(cm, "blur", cm, e);
3242 cm.state.focused = false;
3243 rmClass(cm.display.wrapper, "CodeMirror-focused");
3244 }
3245 clearInterval(cm.display.blinker);
3246 setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3247 }
3248
3249 // Read the actual heights of the rendered lines, and update their
3250 // stored heights to match.
3251 function updateHeightsInViewport(cm) {
3252 var display = cm.display;
3253 var prevBottom = display.lineDiv.offsetTop;
3254 for (var i = 0; i < display.view.length; i++) {
3255 var cur = display.view[i], height = (void 0);
3256 if (cur.hidden) { continue }
3257 if (ie && ie_version < 8) {
3258 var bot = cur.node.offsetTop + cur.node.offsetHeight;
3259 height = bot - prevBottom;
3260 prevBottom = bot;
3261 } else {
3262 var box = cur.node.getBoundingClientRect();
3263 height = box.bottom - box.top;
3264 }
3265 var diff = cur.line.height - height;
3266 if (height < 2) { height = textHeight(display); }
3267 if (diff > .005 || diff < -.005) {
3268 updateLineHeight(cur.line, height);
3269 updateWidgetHeight(cur.line);
3270 if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
3271 { updateWidgetHeight(cur.rest[j]); } }
3272 }
3273 }
3274 }
3275
3276 // Read and store the height of line widgets associated with the
3277 // given line.
3278 function updateWidgetHeight(line) {
3279 if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
3280 var w = line.widgets[i], parent = w.node.parentNode;
3281 if (parent) { w.height = parent.offsetHeight; }
3282 } }
3283 }
3284
3285 // Compute the lines that are visible in a given viewport (defaults
3286 // the the current scroll position). viewport may contain top,
3287 // height, and ensure (see op.scrollToPos) properties.
3288 function visibleLines(display, doc, viewport) {
3289 var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
3290 top = Math.floor(top - paddingTop(display));
3291 var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
3292
3293 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
3294 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
3295 // forces those lines into the viewport (if possible).
3296 if (viewport && viewport.ensure) {
3297 var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
3298 if (ensureFrom < from) {
3299 from = ensureFrom;
3300 to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
3301 } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
3302 from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
3303 to = ensureTo;
3304 }
3305 }
3306 return {from: from, to: Math.max(to, from + 1)}
3307 }
3308
3309 // Re-align line numbers and gutter marks to compensate for
3310 // horizontal scrolling.
3311 function alignHorizontally(cm) {
3312 var display = cm.display, view = display.view;
3313 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
3314 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
3315 var gutterW = display.gutters.offsetWidth, left = comp + "px";
3316 for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
3317 if (cm.options.fixedGutter) {
3318 if (view[i].gutter)
3319 { view[i].gutter.style.left = left; }
3320 if (view[i].gutterBackground)
3321 { view[i].gutterBackground.style.left = left; }
3322 }
3323 var align = view[i].alignable;
3324 if (align) { for (var j = 0; j < align.length; j++)
3325 { align[j].style.left = left; } }
3326 } }
3327 if (cm.options.fixedGutter)
3328 { display.gutters.style.left = (comp + gutterW) + "px"; }
3329 }
3330
3331 // Used to ensure that the line number gutter is still the right
3332 // size for the current document size. Returns true when an update
3333 // is needed.
3334 function maybeUpdateLineNumberWidth(cm) {
3335 if (!cm.options.lineNumbers) { return false }
3336 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
3337 if (last.length != display.lineNumChars) {
3338 var test = display.measure.appendChild(elt("div", [elt("div", last)],
3339 "CodeMirror-linenumber CodeMirror-gutter-elt"));
3340 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
3341 display.lineGutter.style.width = "";
3342 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
3343 display.lineNumWidth = display.lineNumInnerWidth + padding;
3344 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
3345 display.lineGutter.style.width = display.lineNumWidth + "px";
3346 updateGutterSpace(cm);
3347 return true
3348 }
3349 return false
3350 }
3351
3352 // SCROLLING THINGS INTO VIEW
3353
3354 // If an editor sits on the top or bottom of the window, partially
3355 // scrolled out of view, this ensures that the cursor is visible.
3356 function maybeScrollWindow(cm, rect) {
3357 if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
3358
3359 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
3360 if (rect.top + box.top < 0) { doScroll = true; }
3361 else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
3362 if (doScroll != null && !phantom) {
3363 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;"));
3364 cm.display.lineSpace.appendChild(scrollNode);
3365 scrollNode.scrollIntoView(doScroll);
3366 cm.display.lineSpace.removeChild(scrollNode);
3367 }
3368 }
3369
3370 // Scroll a given position into view (immediately), verifying that
3371 // it actually became visible (as line heights are accurately
3372 // measured, the position of something may 'drift' during drawing).
3373 function scrollPosIntoView(cm, pos, end, margin) {
3374 if (margin == null) { margin = 0; }
3375 var rect;
3376 if (!cm.options.lineWrapping && pos == end) {
3377 // Set pos and end to the cursor positions around the character pos sticks to
3378 // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
3379 // If pos == Pos(_, 0, "before"), pos and end are unchanged
3380 pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
3381 end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
3382 }
3383 for (var limit = 0; limit < 5; limit++) {
3384 var changed = false;
3385 var coords = cursorCoords(cm, pos);
3386 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3387 rect = {left: Math.min(coords.left, endCoords.left),
3388 top: Math.min(coords.top, endCoords.top) - margin,
3389 right: Math.max(coords.left, endCoords.left),
3390 bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
3391 var scrollPos = calculateScrollPos(cm, rect);
3392 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3393 if (scrollPos.scrollTop != null) {
3394 updateScrollTop(cm, scrollPos.scrollTop);
3395 if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
3396 }
3397 if (scrollPos.scrollLeft != null) {
3398 setScrollLeft(cm, scrollPos.scrollLeft);
3399 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3400 }
3401 if (!changed) { break }
3402 }
3403 return rect
3404 }
3405
3406 // Scroll a given set of coordinates into view (immediately).
3407 function scrollIntoView(cm, rect) {
3408 var scrollPos = calculateScrollPos(cm, rect);
3409 if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
3410 if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
3411 }
3412
3413 // Calculate a new scroll position needed to scroll the given
3414 // rectangle into view. Returns an object with scrollTop and
3415 // scrollLeft properties. When these are undefined, the
3416 // vertical/horizontal position does not need to be adjusted.
3417 function calculateScrollPos(cm, rect) {
3418 var display = cm.display, snapMargin = textHeight(cm.display);
3419 if (rect.top < 0) { rect.top = 0; }
3420 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3421 var screen = displayHeight(cm), result = {};
3422 if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
3423 var docBottom = cm.doc.height + paddingVert(display);
3424 var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
3425 if (rect.top < screentop) {
3426 result.scrollTop = atTop ? 0 : rect.top;
3427 } else if (rect.bottom > screentop + screen) {
3428 var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
3429 if (newTop != screentop) { result.scrollTop = newTop; }
3430 }
3431
3432 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
3433 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
3434 var tooWide = rect.right - rect.left > screenw;
3435 if (tooWide) { rect.right = rect.left + screenw; }
3436 if (rect.left < 10)
3437 { result.scrollLeft = 0; }
3438 else if (rect.left < screenleft)
3439 { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
3440 else if (rect.right > screenw + screenleft - 3)
3441 { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
3442 return result
3443 }
3444
3445 // Store a relative adjustment to the scroll position in the current
3446 // operation (to be applied when the operation finishes).
3447 function addToScrollTop(cm, top) {
3448 if (top == null) { return }
3449 resolveScrollToPos(cm);
3450 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3451 }
3452
3453 // Make sure that at the end of the operation the current cursor is
3454 // shown.
3455 function ensureCursorVisible(cm) {
3456 resolveScrollToPos(cm);
3457 var cur = cm.getCursor();
3458 cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
3459 }
3460
3461 function scrollToCoords(cm, x, y) {
3462 if (x != null || y != null) { resolveScrollToPos(cm); }
3463 if (x != null) { cm.curOp.scrollLeft = x; }
3464 if (y != null) { cm.curOp.scrollTop = y; }
3465 }
3466
3467 function scrollToRange(cm, range$$1) {
3468 resolveScrollToPos(cm);
3469 cm.curOp.scrollToPos = range$$1;
3470 }
3471
3472 // When an operation has its scrollToPos property set, and another
3473 // scroll action is applied before the end of the operation, this
3474 // 'simulates' scrolling that position into view in a cheap way, so
3475 // that the effect of intermediate scroll commands is not ignored.
3476 function resolveScrollToPos(cm) {
3477 var range$$1 = cm.curOp.scrollToPos;
3478 if (range$$1) {
3479 cm.curOp.scrollToPos = null;
3480 var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
3481 scrollToCoordsRange(cm, from, to, range$$1.margin);
3482 }
3483 }
3484
3485 function scrollToCoordsRange(cm, from, to, margin) {
3486 var sPos = calculateScrollPos(cm, {
3487 left: Math.min(from.left, to.left),
3488 top: Math.min(from.top, to.top) - margin,
3489 right: Math.max(from.right, to.right),
3490 bottom: Math.max(from.bottom, to.bottom) + margin
3491 });
3492 scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
3493 }
3494
3495 // Sync the scrollable area and scrollbars, ensure the viewport
3496 // covers the visible area.
3497 function updateScrollTop(cm, val) {
3498 if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
3499 if (!gecko) { updateDisplaySimple(cm, {top: val}); }
3500 setScrollTop(cm, val, true);
3501 if (gecko) { updateDisplaySimple(cm); }
3502 startWorker(cm, 100);
3503 }
3504
3505 function setScrollTop(cm, val, forceScroll) {
3506 val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
3507 if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
3508 cm.doc.scrollTop = val;
3509 cm.display.scrollbars.setScrollTop(val);
3510 if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
3511 }
3512
3513 // Sync scroller and scrollbar, ensure the gutter elements are
3514 // aligned.
3515 function setScrollLeft(cm, val, isScroller, forceScroll) {
3516 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3517 if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
3518 cm.doc.scrollLeft = val;
3519 alignHorizontally(cm);
3520 if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
3521 cm.display.scrollbars.setScrollLeft(val);
3522 }
3523
3524 // SCROLLBARS
3525
3526 // Prepare DOM reads needed to update the scrollbars. Done in one
3527 // shot to minimize update/measure roundtrips.
3528 function measureForScrollbars(cm) {
3529 var d = cm.display, gutterW = d.gutters.offsetWidth;
3530 var docH = Math.round(cm.doc.height + paddingVert(cm.display));
3531 return {
3532 clientHeight: d.scroller.clientHeight,
3533 viewHeight: d.wrapper.clientHeight,
3534 scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
3535 viewWidth: d.wrapper.clientWidth,
3536 barLeft: cm.options.fixedGutter ? gutterW : 0,
3537 docHeight: docH,
3538 scrollHeight: docH + scrollGap(cm) + d.barHeight,
3539 nativeBarWidth: d.nativeBarWidth,
3540 gutterWidth: gutterW
3541 }
3542 }
3543
3544 var NativeScrollbars = function(place, scroll, cm) {
3545 this.cm = cm;
3546 var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
3547 var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
3548 place(vert); place(horiz);
3549
3550 on(vert, "scroll", function () {
3551 if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
3552 });
3553 on(horiz, "scroll", function () {
3554 if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
3555 });
3556
3557 this.checkedZeroWidth = false;
3558 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
3559 if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
3560 };
3561
3562 NativeScrollbars.prototype.update = function (measure) {
3563 var needsH = measure.scrollWidth > measure.clientWidth + 1;
3564 var needsV = measure.scrollHeight > measure.clientHeight + 1;
3565 var sWidth = measure.nativeBarWidth;
3566
3567 if (needsV) {
3568 this.vert.style.display = "block";
3569 this.vert.style.bottom = needsH ? sWidth + "px" : "0";
3570 var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
3571 // A bug in IE8 can cause this value to be negative, so guard it.
3572 this.vert.firstChild.style.height =
3573 Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
3574 } else {
3575 this.vert.style.display = "";
3576 this.vert.firstChild.style.height = "0";
3577 }
3578
3579 if (needsH) {
3580 this.horiz.style.display = "block";
3581 this.horiz.style.right = needsV ? sWidth + "px" : "0";
3582 this.horiz.style.left = measure.barLeft + "px";
3583 var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
3584 this.horiz.firstChild.style.width =
3585 Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
3586 } else {
3587 this.horiz.style.display = "";
3588 this.horiz.firstChild.style.width = "0";
3589 }
3590
3591 if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3592 if (sWidth == 0) { this.zeroWidthHack(); }
3593 this.checkedZeroWidth = true;
3594 }
3595
3596 return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3597 };
3598
3599 NativeScrollbars.prototype.setScrollLeft = function (pos) {
3600 if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
3601 if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
3602 };
3603
3604 NativeScrollbars.prototype.setScrollTop = function (pos) {
3605 if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
3606 if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
3607 };
3608
3609 NativeScrollbars.prototype.zeroWidthHack = function () {
3610 var w = mac && !mac_geMountainLion ? "12px" : "18px";
3611 this.horiz.style.height = this.vert.style.width = w;
3612 this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
3613 this.disableHoriz = new Delayed;
3614 this.disableVert = new Delayed;
3615 };
3616
3617 NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
3618 bar.style.pointerEvents = "auto";
3619 function maybeDisable() {
3620 // To find out whether the scrollbar is still visible, we
3621 // check whether the element under the pixel in the bottom
3622 // right corner of the scrollbar box is the scrollbar box
3623 // itself (when the bar is still visible) or its filler child
3624 // (when the bar is hidden). If it is still visible, we keep
3625 // it enabled, if it's hidden, we disable pointer events.
3626 var box = bar.getBoundingClientRect();
3627 var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
3628 : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
3629 if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
3630 else { delay.set(1000, maybeDisable); }
3631 }
3632 delay.set(1000, maybeDisable);
3633 };
3634
3635 NativeScrollbars.prototype.clear = function () {
3636 var parent = this.horiz.parentNode;
3637 parent.removeChild(this.horiz);
3638 parent.removeChild(this.vert);
3639 };
3640
3641 var NullScrollbars = function () {};
3642
3643 NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
3644 NullScrollbars.prototype.setScrollLeft = function () {};
3645 NullScrollbars.prototype.setScrollTop = function () {};
3646 NullScrollbars.prototype.clear = function () {};
3647
3648 function updateScrollbars(cm, measure) {
3649 if (!measure) { measure = measureForScrollbars(cm); }
3650 var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
3651 updateScrollbarsInner(cm, measure);
3652 for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
3653 if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
3654 { updateHeightsInViewport(cm); }
3655 updateScrollbarsInner(cm, measureForScrollbars(cm));
3656 startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
3657 }
3658 }
3659
3660 // Re-synchronize the fake scrollbars with the actual size of the
3661 // content.
3662 function updateScrollbarsInner(cm, measure) {
3663 var d = cm.display;
3664 var sizes = d.scrollbars.update(measure);
3665
3666 d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
3667 d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
3668 d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
3669
3670 if (sizes.right && sizes.bottom) {
3671 d.scrollbarFiller.style.display = "block";
3672 d.scrollbarFiller.style.height = sizes.bottom + "px";
3673 d.scrollbarFiller.style.width = sizes.right + "px";
3674 } else { d.scrollbarFiller.style.display = ""; }
3675 if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
3676 d.gutterFiller.style.display = "block";
3677 d.gutterFiller.style.height = sizes.bottom + "px";
3678 d.gutterFiller.style.width = measure.gutterWidth + "px";
3679 } else { d.gutterFiller.style.display = ""; }
3680 }
3681
3682 var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3683
3684 function initScrollbars(cm) {
3685 if (cm.display.scrollbars) {
3686 cm.display.scrollbars.clear();
3687 if (cm.display.scrollbars.addClass)
3688 { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3689 }
3690
3691 cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
3692 cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
3693 // Prevent clicks in the scrollbars from killing focus
3694 on(node, "mousedown", function () {
3695 if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
3696 });
3697 node.setAttribute("cm-not-content", "true");
3698 }, function (pos, axis) {
3699 if (axis == "horizontal") { setScrollLeft(cm, pos); }
3700 else { updateScrollTop(cm, pos); }
3701 }, cm);
3702 if (cm.display.scrollbars.addClass)
3703 { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3704 }
3705
3706 // Operations are used to wrap a series of changes to the editor
3707 // state in such a way that each change won't have to update the
3708 // cursor and display (which would be awkward, slow, and
3709 // error-prone). Instead, display updates are batched and then all
3710 // combined and executed at once.
3711
3712 var nextOpId = 0;
3713 // Start a new operation.
3714 function startOperation(cm) {
3715 cm.curOp = {
3716 cm: cm,
3717 viewChanged: false, // Flag that indicates that lines might need to be redrawn
3718 startHeight: cm.doc.height, // Used to detect need to update scrollbar
3719 forceUpdate: false, // Used to force a redraw
3720 updateInput: null, // Whether to reset the input textarea
3721 typing: false, // Whether this reset should be careful to leave existing text (for compositing)
3722 changeObjs: null, // Accumulated changes, for firing change events
3723 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3724 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3725 selectionChanged: false, // Whether the selection needs to be redrawn
3726 updateMaxLine: false, // Set when the widest line needs to be determined anew
3727 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3728 scrollToPos: null, // Used to scroll to a specific position
3729 focus: false,
3730 id: ++nextOpId // Unique ID
3731 };
3732 pushOperation(cm.curOp);
3733 }
3734
3735 // Finish an operation, updating the display and signalling delayed events
3736 function endOperation(cm) {
3737 var op = cm.curOp;
3738 finishOperation(op, function (group) {
3739 for (var i = 0; i < group.ops.length; i++)
3740 { group.ops[i].cm.curOp = null; }
3741 endOperations(group);
3742 });
3743 }
3744
3745 // The DOM updates done when an operation finishes are batched so
3746 // that the minimum number of relayouts are required.
3747 function endOperations(group) {
3748 var ops = group.ops;
3749 for (var i = 0; i < ops.length; i++) // Read DOM
3750 { endOperation_R1(ops[i]); }
3751 for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
3752 { endOperation_W1(ops[i$1]); }
3753 for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
3754 { endOperation_R2(ops[i$2]); }
3755 for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
3756 { endOperation_W2(ops[i$3]); }
3757 for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
3758 { endOperation_finish(ops[i$4]); }
3759 }
3760
3761 function endOperation_R1(op) {
3762 var cm = op.cm, display = cm.display;
3763 maybeClipScrollbars(cm);
3764 if (op.updateMaxLine) { findMaxLine(cm); }
3765
3766 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3767 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3768 op.scrollToPos.to.line >= display.viewTo) ||
3769 display.maxLineChanged && cm.options.lineWrapping;
3770 op.update = op.mustUpdate &&
3771 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3772 }
3773
3774 function endOperation_W1(op) {
3775 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3776 }
3777
3778 function endOperation_R2(op) {
3779 var cm = op.cm, display = cm.display;
3780 if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3781
3782 op.barMeasure = measureForScrollbars(cm);
3783
3784 // If the max line changed since it was last measured, measure it,
3785 // and ensure the document's width matches it.
3786 // updateDisplay_W2 will use these properties to do the actual resizing
3787 if (display.maxLineChanged && !cm.options.lineWrapping) {
3788 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3789 cm.display.sizerWidth = op.adjustWidthTo;
3790 op.barMeasure.scrollWidth =
3791 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3792 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3793 }
3794
3795 if (op.updatedDisplay || op.selectionChanged)
3796 { op.preparedSelection = display.input.prepareSelection(); }
3797 }
3798
3799 function endOperation_W2(op) {
3800 var cm = op.cm;
3801
3802 if (op.adjustWidthTo != null) {
3803 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3804 if (op.maxScrollLeft < cm.doc.scrollLeft)
3805 { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
3806 cm.display.maxLineChanged = false;
3807 }
3808
3809 var takeFocus = op.focus && op.focus == activeElt();
3810 if (op.preparedSelection)
3811 { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
3812 if (op.updatedDisplay || op.startHeight != cm.doc.height)
3813 { updateScrollbars(cm, op.barMeasure); }
3814 if (op.updatedDisplay)
3815 { setDocumentHeight(cm, op.barMeasure); }
3816
3817 if (op.selectionChanged) { restartBlink(cm); }
3818
3819 if (cm.state.focused && op.updateInput)
3820 { cm.display.input.reset(op.typing); }
3821 if (takeFocus) { ensureFocus(op.cm); }
3822 }
3823
3824 function endOperation_finish(op) {
3825 var cm = op.cm, display = cm.display, doc = cm.doc;
3826
3827 if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3828
3829 // Abort mouse wheel delta measurement, when scrolling explicitly
3830 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3831 { display.wheelStartX = display.wheelStartY = null; }
3832
3833 // Propagate the scroll position to the actual DOM scroller
3834 if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
3835
3836 if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
3837 // If we need to scroll a specific position into view, do so.
3838 if (op.scrollToPos) {
3839 var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3840 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3841 maybeScrollWindow(cm, rect);
3842 }
3843
3844 // Fire events for markers that are hidden/unidden by editing or
3845 // undoing
3846 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3847 if (hidden) { for (var i = 0; i < hidden.length; ++i)
3848 { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
3849 if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
3850 { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
3851
3852 if (display.wrapper.offsetHeight)
3853 { doc.scrollTop = cm.display.scroller.scrollTop; }
3854
3855 // Fire change events, and delayed event handlers
3856 if (op.changeObjs)
3857 { signal(cm, "changes", cm, op.changeObjs); }
3858 if (op.update)
3859 { op.update.finish(); }
3860 }
3861
3862 // Run the given function in an operation
3863 function runInOp(cm, f) {
3864 if (cm.curOp) { return f() }
3865 startOperation(cm);
3866 try { return f() }
3867 finally { endOperation(cm); }
3868 }
3869 // Wraps a function in an operation. Returns the wrapped function.
3870 function operation(cm, f) {
3871 return function() {
3872 if (cm.curOp) { return f.apply(cm, arguments) }
3873 startOperation(cm);
3874 try { return f.apply(cm, arguments) }
3875 finally { endOperation(cm); }
3876 }
3877 }
3878 // Used to add methods to editor and doc instances, wrapping them in
3879 // operations.
3880 function methodOp(f) {
3881 return function() {
3882 if (this.curOp) { return f.apply(this, arguments) }
3883 startOperation(this);
3884 try { return f.apply(this, arguments) }
3885 finally { endOperation(this); }
3886 }
3887 }
3888 function docMethodOp(f) {
3889 return function() {
3890 var cm = this.cm;
3891 if (!cm || cm.curOp) { return f.apply(this, arguments) }
3892 startOperation(cm);
3893 try { return f.apply(this, arguments) }
3894 finally { endOperation(cm); }
3895 }
3896 }
3897
3898 // Updates the display.view data structure for a given change to the
3899 // document. From and to are in pre-change coordinates. Lendiff is
3900 // the amount of lines added or subtracted by the change. This is
3901 // used for changes that span multiple lines, or change the way
3902 // lines are divided into visual lines. regLineChange (below)
3903 // registers single-line changes.
3904 function regChange(cm, from, to, lendiff) {
3905 if (from == null) { from = cm.doc.first; }
3906 if (to == null) { to = cm.doc.first + cm.doc.size; }
3907 if (!lendiff) { lendiff = 0; }
3908
3909 var display = cm.display;
3910 if (lendiff && to < display.viewTo &&
3911 (display.updateLineNumbers == null || display.updateLineNumbers > from))
3912 { display.updateLineNumbers = from; }
3913
3914 cm.curOp.viewChanged = true;
3915
3916 if (from >= display.viewTo) { // Change after
3917 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3918 { resetView(cm); }
3919 } else if (to <= display.viewFrom) { // Change before
3920 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3921 resetView(cm);
3922 } else {
3923 display.viewFrom += lendiff;
3924 display.viewTo += lendiff;
3925 }
3926 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3927 resetView(cm);
3928 } else if (from <= display.viewFrom) { // Top overlap
3929 var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3930 if (cut) {
3931 display.view = display.view.slice(cut.index);
3932 display.viewFrom = cut.lineN;
3933 display.viewTo += lendiff;
3934 } else {
3935 resetView(cm);
3936 }
3937 } else if (to >= display.viewTo) { // Bottom overlap
3938 var cut$1 = viewCuttingPoint(cm, from, from, -1);
3939 if (cut$1) {
3940 display.view = display.view.slice(0, cut$1.index);
3941 display.viewTo = cut$1.lineN;
3942 } else {
3943 resetView(cm);
3944 }
3945 } else { // Gap in the middle
3946 var cutTop = viewCuttingPoint(cm, from, from, -1);
3947 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3948 if (cutTop && cutBot) {
3949 display.view = display.view.slice(0, cutTop.index)
3950 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3951 .concat(display.view.slice(cutBot.index));
3952 display.viewTo += lendiff;
3953 } else {
3954 resetView(cm);
3955 }
3956 }
3957
3958 var ext = display.externalMeasured;
3959 if (ext) {
3960 if (to < ext.lineN)
3961 { ext.lineN += lendiff; }
3962 else if (from < ext.lineN + ext.size)
3963 { display.externalMeasured = null; }
3964 }
3965 }
3966
3967 // Register a change to a single line. Type must be one of "text",
3968 // "gutter", "class", "widget"
3969 function regLineChange(cm, line, type) {
3970 cm.curOp.viewChanged = true;
3971 var display = cm.display, ext = cm.display.externalMeasured;
3972 if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3973 { display.externalMeasured = null; }
3974
3975 if (line < display.viewFrom || line >= display.viewTo) { return }
3976 var lineView = display.view[findViewIndex(cm, line)];
3977 if (lineView.node == null) { return }
3978 var arr = lineView.changes || (lineView.changes = []);
3979 if (indexOf(arr, type) == -1) { arr.push(type); }
3980 }
3981
3982 // Clear the view.
3983 function resetView(cm) {
3984 cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3985 cm.display.view = [];
3986 cm.display.viewOffset = 0;
3987 }
3988
3989 function viewCuttingPoint(cm, oldN, newN, dir) {
3990 var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3991 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3992 { return {index: index, lineN: newN} }
3993 var n = cm.display.viewFrom;
3994 for (var i = 0; i < index; i++)
3995 { n += view[i].size; }
3996 if (n != oldN) {
3997 if (dir > 0) {
3998 if (index == view.length - 1) { return null }
3999 diff = (n + view[index].size) - oldN;
4000 index++;
4001 } else {
4002 diff = n - oldN;
4003 }
4004 oldN += diff; newN += diff;
4005 }
4006 while (visualLineNo(cm.doc, newN) != newN) {
4007 if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
4008 newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
4009 index += dir;
4010 }
4011 return {index: index, lineN: newN}
4012 }
4013
4014 // Force the view to cover a given range, adding empty view element
4015 // or clipping off existing ones as needed.
4016 function adjustView(cm, from, to) {
4017 var display = cm.display, view = display.view;
4018 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
4019 display.view = buildViewArray(cm, from, to);
4020 display.viewFrom = from;
4021 } else {
4022 if (display.viewFrom > from)
4023 { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
4024 else if (display.viewFrom < from)
4025 { display.view = display.view.slice(findViewIndex(cm, from)); }
4026 display.viewFrom = from;
4027 if (display.viewTo < to)
4028 { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
4029 else if (display.viewTo > to)
4030 { display.view = display.view.slice(0, findViewIndex(cm, to)); }
4031 }
4032 display.viewTo = to;
4033 }
4034
4035 // Count the number of lines in the view whose DOM representation is
4036 // out of date (or nonexistent).
4037 function countDirtyView(cm) {
4038 var view = cm.display.view, dirty = 0;
4039 for (var i = 0; i < view.length; i++) {
4040 var lineView = view[i];
4041 if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
4042 }
4043 return dirty
4044 }
4045
4046 // HIGHLIGHT WORKER
4047
4048 function startWorker(cm, time) {
4049 if (cm.doc.highlightFrontier < cm.display.viewTo)
4050 { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
4051 }
4052
4053 function highlightWorker(cm) {
4054 var doc = cm.doc;
4055 if (doc.highlightFrontier >= cm.display.viewTo) { return }
4056 var end = +new Date + cm.options.workTime;
4057 var context = getContextBefore(cm, doc.highlightFrontier);
4058 var changedLines = [];
4059
4060 doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
4061 if (context.line >= cm.display.viewFrom) { // Visible
4062 var oldStyles = line.styles;
4063 var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
4064 var highlighted = highlightLine(cm, line, context, true);
4065 if (resetState) { context.state = resetState; }
4066 line.styles = highlighted.styles;
4067 var oldCls = line.styleClasses, newCls = highlighted.classes;
4068 if (newCls) { line.styleClasses = newCls; }
4069 else if (oldCls) { line.styleClasses = null; }
4070 var ischange = !oldStyles || oldStyles.length != line.styles.length ||
4071 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
4072 for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
4073 if (ischange) { changedLines.push(context.line); }
4074 line.stateAfter = context.save();
4075 context.nextLine();
4076 } else {
4077 if (line.text.length <= cm.options.maxHighlightLength)
4078 { processLine(cm, line.text, context); }
4079 line.stateAfter = context.line % 5 == 0 ? context.save() : null;
4080 context.nextLine();
4081 }
4082 if (+new Date > end) {
4083 startWorker(cm, cm.options.workDelay);
4084 return true
4085 }
4086 });
4087 doc.highlightFrontier = context.line;
4088 doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
4089 if (changedLines.length) { runInOp(cm, function () {
4090 for (var i = 0; i < changedLines.length; i++)
4091 { regLineChange(cm, changedLines[i], "text"); }
4092 }); }
4093 }
4094
4095 // DISPLAY DRAWING
4096
4097 var DisplayUpdate = function(cm, viewport, force) {
4098 var display = cm.display;
4099
4100 this.viewport = viewport;
4101 // Store some values that we'll need later (but don't want to force a relayout for)
4102 this.visible = visibleLines(display, cm.doc, viewport);
4103 this.editorIsHidden = !display.wrapper.offsetWidth;
4104 this.wrapperHeight = display.wrapper.clientHeight;
4105 this.wrapperWidth = display.wrapper.clientWidth;
4106 this.oldDisplayWidth = displayWidth(cm);
4107 this.force = force;
4108 this.dims = getDimensions(cm);
4109 this.events = [];
4110 };
4111
4112 DisplayUpdate.prototype.signal = function (emitter, type) {
4113 if (hasHandler(emitter, type))
4114 { this.events.push(arguments); }
4115 };
4116 DisplayUpdate.prototype.finish = function () {
4117 var this$1 = this;
4118
4119 for (var i = 0; i < this.events.length; i++)
4120 { signal.apply(null, this$1.events[i]); }
4121 };
4122
4123 function maybeClipScrollbars(cm) {
4124 var display = cm.display;
4125 if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
4126 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
4127 display.heightForcer.style.height = scrollGap(cm) + "px";
4128 display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
4129 display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
4130 display.scrollbarsClipped = true;
4131 }
4132 }
4133
4134 function selectionSnapshot(cm) {
4135 if (cm.hasFocus()) { return null }
4136 var active = activeElt();
4137 if (!active || !contains(cm.display.lineDiv, active)) { return null }
4138 var result = {activeElt: active};
4139 if (window.getSelection) {
4140 var sel = window.getSelection();
4141 if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
4142 result.anchorNode = sel.anchorNode;
4143 result.anchorOffset = sel.anchorOffset;
4144 result.focusNode = sel.focusNode;
4145 result.focusOffset = sel.focusOffset;
4146 }
4147 }
4148 return result
4149 }
4150
4151 function restoreSelection(snapshot) {
4152 if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
4153 snapshot.activeElt.focus();
4154 if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
4155 var sel = window.getSelection(), range$$1 = document.createRange();
4156 range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
4157 range$$1.collapse(false);
4158 sel.removeAllRanges();
4159 sel.addRange(range$$1);
4160 sel.extend(snapshot.focusNode, snapshot.focusOffset);
4161 }
4162 }
4163
4164 // Does the actual updating of the line display. Bails out
4165 // (returning false) when there is nothing to be done and forced is
4166 // false.
4167 function updateDisplayIfNeeded(cm, update) {
4168 var display = cm.display, doc = cm.doc;
4169
4170 if (update.editorIsHidden) {
4171 resetView(cm);
4172 return false
4173 }
4174
4175 // Bail out if the visible area is already rendered and nothing changed.
4176 if (!update.force &&
4177 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
4178 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
4179 display.renderedView == display.view && countDirtyView(cm) == 0)
4180 { return false }
4181
4182 if (maybeUpdateLineNumberWidth(cm)) {
4183 resetView(cm);
4184 update.dims = getDimensions(cm);
4185 }
4186
4187 // Compute a suitable new viewport (from & to)
4188 var end = doc.first + doc.size;
4189 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
4190 var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
4191 if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
4192 if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
4193 if (sawCollapsedSpans) {
4194 from = visualLineNo(cm.doc, from);
4195 to = visualLineEndNo(cm.doc, to);
4196 }
4197
4198 var different = from != display.viewFrom || to != display.viewTo ||
4199 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
4200 adjustView(cm, from, to);
4201
4202 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
4203 // Position the mover div to align with the current scroll position
4204 cm.display.mover.style.top = display.viewOffset + "px";
4205
4206 var toUpdate = countDirtyView(cm);
4207 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
4208 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
4209 { return false }
4210
4211 // For big changes, we hide the enclosing element during the
4212 // update, since that speeds up the operations on most browsers.
4213 var selSnapshot = selectionSnapshot(cm);
4214 if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
4215 patchDisplay(cm, display.updateLineNumbers, update.dims);
4216 if (toUpdate > 4) { display.lineDiv.style.display = ""; }
4217 display.renderedView = display.view;
4218 // There might have been a widget with a focused element that got
4219 // hidden or updated, if so re-focus it.
4220 restoreSelection(selSnapshot);
4221
4222 // Prevent selection and cursors from interfering with the scroll
4223 // width and height.
4224 removeChildren(display.cursorDiv);
4225 removeChildren(display.selectionDiv);
4226 display.gutters.style.height = display.sizer.style.minHeight = 0;
4227
4228 if (different) {
4229 display.lastWrapHeight = update.wrapperHeight;
4230 display.lastWrapWidth = update.wrapperWidth;
4231 startWorker(cm, 400);
4232 }
4233
4234 display.updateLineNumbers = null;
4235
4236 return true
4237 }
4238
4239 function postUpdateDisplay(cm, update) {
4240 var viewport = update.viewport;
4241
4242 for (var first = true;; first = false) {
4243 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
4244 // Clip forced viewport to actual scrollable area.
4245 if (viewport && viewport.top != null)
4246 { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
4247 // Updated line heights might result in the drawn area not
4248 // actually covering the viewport. Keep looping until it does.
4249 update.visible = visibleLines(cm.display, cm.doc, viewport);
4250 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
4251 { break }
4252 }
4253 if (!updateDisplayIfNeeded(cm, update)) { break }
4254 updateHeightsInViewport(cm);
4255 var barMeasure = measureForScrollbars(cm);
4256 updateSelection(cm);
4257 updateScrollbars(cm, barMeasure);
4258 setDocumentHeight(cm, barMeasure);
4259 update.force = false;
4260 }
4261
4262 update.signal(cm, "update", cm);
4263 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
4264 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
4265 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
4266 }
4267 }
4268
4269 function updateDisplaySimple(cm, viewport) {
4270 var update = new DisplayUpdate(cm, viewport);
4271 if (updateDisplayIfNeeded(cm, update)) {
4272 updateHeightsInViewport(cm);
4273 postUpdateDisplay(cm, update);
4274 var barMeasure = measureForScrollbars(cm);
4275 updateSelection(cm);
4276 updateScrollbars(cm, barMeasure);
4277 setDocumentHeight(cm, barMeasure);
4278 update.finish();
4279 }
4280 }
4281
4282 // Sync the actual display DOM structure with display.view, removing
4283 // nodes for lines that are no longer in view, and creating the ones
4284 // that are not there yet, and updating the ones that are out of
4285 // date.
4286 function patchDisplay(cm, updateNumbersFrom, dims) {
4287 var display = cm.display, lineNumbers = cm.options.lineNumbers;
4288 var container = display.lineDiv, cur = container.firstChild;
4289
4290 function rm(node) {
4291 var next = node.nextSibling;
4292 // Works around a throw-scroll bug in OS X Webkit
4293 if (webkit && mac && cm.display.currentWheelTarget == node)
4294 { node.style.display = "none"; }
4295 else
4296 { node.parentNode.removeChild(node); }
4297 return next
4298 }
4299
4300 var view = display.view, lineN = display.viewFrom;
4301 // Loop over the elements in the view, syncing cur (the DOM nodes
4302 // in display.lineDiv) with the view as we go.
4303 for (var i = 0; i < view.length; i++) {
4304 var lineView = view[i];
4305 if (lineView.hidden) {
4306 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
4307 var node = buildLineElement(cm, lineView, lineN, dims);
4308 container.insertBefore(node, cur);
4309 } else { // Already drawn
4310 while (cur != lineView.node) { cur = rm(cur); }
4311 var updateNumber = lineNumbers && updateNumbersFrom != null &&
4312 updateNumbersFrom <= lineN && lineView.lineNumber;
4313 if (lineView.changes) {
4314 if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
4315 updateLineForChanges(cm, lineView, lineN, dims);
4316 }
4317 if (updateNumber) {
4318 removeChildren(lineView.lineNumber);
4319 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4320 }
4321 cur = lineView.node.nextSibling;
4322 }
4323 lineN += lineView.size;
4324 }
4325 while (cur) { cur = rm(cur); }
4326 }
4327
4328 function updateGutterSpace(cm) {
4329 var width = cm.display.gutters.offsetWidth;
4330 cm.display.sizer.style.marginLeft = width + "px";
4331 }
4332
4333 function setDocumentHeight(cm, measure) {
4334 cm.display.sizer.style.minHeight = measure.docHeight + "px";
4335 cm.display.heightForcer.style.top = measure.docHeight + "px";
4336 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
4337 }
4338
4339 // Rebuild the gutter elements, ensure the margin to the left of the
4340 // code matches their width.
4341 function updateGutters(cm) {
4342 var gutters = cm.display.gutters, specs = cm.options.gutters;
4343 removeChildren(gutters);
4344 var i = 0;
4345 for (; i < specs.length; ++i) {
4346 var gutterClass = specs[i];
4347 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
4348 if (gutterClass == "CodeMirror-linenumbers") {
4349 cm.display.lineGutter = gElt;
4350 gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
4351 }
4352 }
4353 gutters.style.display = i ? "" : "none";
4354 updateGutterSpace(cm);
4355 }
4356
4357 // Make sure the gutters options contains the element
4358 // "CodeMirror-linenumbers" when the lineNumbers option is true.
4359 function setGuttersForLineNumbers(options) {
4360 var found = indexOf(options.gutters, "CodeMirror-linenumbers");
4361 if (found == -1 && options.lineNumbers) {
4362 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
4363 } else if (found > -1 && !options.lineNumbers) {
4364 options.gutters = options.gutters.slice(0);
4365 options.gutters.splice(found, 1);
4366 }
4367 }
4368
4369 // Since the delta values reported on mouse wheel events are
4370 // unstandardized between browsers and even browser versions, and
4371 // generally horribly unpredictable, this code starts by measuring
4372 // the scroll effect that the first few mouse wheel events have,
4373 // and, from that, detects the way it can convert deltas to pixel
4374 // offsets afterwards.
4375 //
4376 // The reason we want to know the amount a wheel event will scroll
4377 // is that it gives us a chance to update the display before the
4378 // actual scrolling happens, reducing flickering.
4379
4380 var wheelSamples = 0;
4381 var wheelPixelsPerUnit = null;
4382 // Fill in a browser-detected starting value on browsers where we
4383 // know one. These don't have to be accurate -- the result of them
4384 // being wrong would just be a slight flicker on the first wheel
4385 // scroll (if it is large enough).
4386 if (ie) { wheelPixelsPerUnit = -.53; }
4387 else if (gecko) { wheelPixelsPerUnit = 15; }
4388 else if (chrome) { wheelPixelsPerUnit = -.7; }
4389 else if (safari) { wheelPixelsPerUnit = -1/3; }
4390
4391 function wheelEventDelta(e) {
4392 var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4393 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
4394 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
4395 else if (dy == null) { dy = e.wheelDelta; }
4396 return {x: dx, y: dy}
4397 }
4398 function wheelEventPixels(e) {
4399 var delta = wheelEventDelta(e);
4400 delta.x *= wheelPixelsPerUnit;
4401 delta.y *= wheelPixelsPerUnit;
4402 return delta
4403 }
4404
4405 function onScrollWheel(cm, e) {
4406 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
4407
4408 var display = cm.display, scroll = display.scroller;
4409 // Quit if there's nothing to scroll here
4410 var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4411 var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4412 if (!(dx && canScrollX || dy && canScrollY)) { return }
4413
4414 // Webkit browsers on OS X abort momentum scrolls when the target
4415 // of the scroll event is removed from the scrollable element.
4416 // This hack (see related code in patchDisplay) makes sure the
4417 // element is kept around.
4418 if (dy && mac && webkit) {
4419 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4420 for (var i = 0; i < view.length; i++) {
4421 if (view[i].node == cur) {
4422 cm.display.currentWheelTarget = cur;
4423 break outer
4424 }
4425 }
4426 }
4427 }
4428
4429 // On some browsers, horizontal scrolling will cause redraws to
4430 // happen before the gutter has been realigned, causing it to
4431 // wriggle around in a most unseemly way. When we have an
4432 // estimated pixels/delta value, we just handle horizontal
4433 // scrolling entirely here. It'll be slightly off from native, but
4434 // better than glitching out.
4435 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4436 if (dy && canScrollY)
4437 { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
4438 setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
4439 // Only prevent default scrolling if vertical scrolling is
4440 // actually possible. Otherwise, it causes vertical scroll
4441 // jitter on OSX trackpads when deltaX is small and deltaY
4442 // is large (issue #3579)
4443 if (!dy || (dy && canScrollY))
4444 { e_preventDefault(e); }
4445 display.wheelStartX = null; // Abort measurement, if in progress
4446 return
4447 }
4448
4449 // 'Project' the visible viewport to cover the area that is being
4450 // scrolled into view (if we know enough to estimate it).
4451 if (dy && wheelPixelsPerUnit != null) {
4452 var pixels = dy * wheelPixelsPerUnit;
4453 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4454 if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
4455 else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
4456 updateDisplaySimple(cm, {top: top, bottom: bot});
4457 }
4458
4459 if (wheelSamples < 20) {
4460 if (display.wheelStartX == null) {
4461 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4462 display.wheelDX = dx; display.wheelDY = dy;
4463 setTimeout(function () {
4464 if (display.wheelStartX == null) { return }
4465 var movedX = scroll.scrollLeft - display.wheelStartX;
4466 var movedY = scroll.scrollTop - display.wheelStartY;
4467 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4468 (movedX && display.wheelDX && movedX / display.wheelDX);
4469 display.wheelStartX = display.wheelStartY = null;
4470 if (!sample) { return }
4471 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4472 ++wheelSamples;
4473 }, 200);
4474 } else {
4475 display.wheelDX += dx; display.wheelDY += dy;
4476 }
4477 }
4478 }
4479
4480 // Selection objects are immutable. A new one is created every time
4481 // the selection changes. A selection is one or more non-overlapping
4482 // (and non-touching) ranges, sorted, and an integer that indicates
4483 // which one is the primary selection (the one that's scrolled into
4484 // view, that getCursor returns, etc).
4485 var Selection = function(ranges, primIndex) {
4486 this.ranges = ranges;
4487 this.primIndex = primIndex;
4488 };
4489
4490 Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
4491
4492 Selection.prototype.equals = function (other) {
4493 var this$1 = this;
4494
4495 if (other == this) { return true }
4496 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
4497 for (var i = 0; i < this.ranges.length; i++) {
4498 var here = this$1.ranges[i], there = other.ranges[i];
4499 if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
4500 }
4501 return true
4502 };
4503
4504 Selection.prototype.deepCopy = function () {
4505 var this$1 = this;
4506
4507 var out = [];
4508 for (var i = 0; i < this.ranges.length; i++)
4509 { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
4510 return new Selection(out, this.primIndex)
4511 };
4512
4513 Selection.prototype.somethingSelected = function () {
4514 var this$1 = this;
4515
4516 for (var i = 0; i < this.ranges.length; i++)
4517 { if (!this$1.ranges[i].empty()) { return true } }
4518 return false
4519 };
4520
4521 Selection.prototype.contains = function (pos, end) {
4522 var this$1 = this;
4523
4524 if (!end) { end = pos; }
4525 for (var i = 0; i < this.ranges.length; i++) {
4526 var range = this$1.ranges[i];
4527 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
4528 { return i }
4529 }
4530 return -1
4531 };
4532
4533 var Range = function(anchor, head) {
4534 this.anchor = anchor; this.head = head;
4535 };
4536
4537 Range.prototype.from = function () { return minPos(this.anchor, this.head) };
4538 Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
4539 Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
4540
4541 // Take an unsorted, potentially overlapping set of ranges, and
4542 // build a selection out of it. 'Consumes' ranges array (modifying
4543 // it).
4544 function normalizeSelection(ranges, primIndex) {
4545 var prim = ranges[primIndex];
4546 ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
4547 primIndex = indexOf(ranges, prim);
4548 for (var i = 1; i < ranges.length; i++) {
4549 var cur = ranges[i], prev = ranges[i - 1];
4550 if (cmp(prev.to(), cur.from()) >= 0) {
4551 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
4552 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
4553 if (i <= primIndex) { --primIndex; }
4554 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
4555 }
4556 }
4557 return new Selection(ranges, primIndex)
4558 }
4559
4560 function simpleSelection(anchor, head) {
4561 return new Selection([new Range(anchor, head || anchor)], 0)
4562 }
4563
4564 // Compute the position of the end of a change (its 'to' property
4565 // refers to the pre-change end).
4566 function changeEnd(change) {
4567 if (!change.text) { return change.to }
4568 return Pos(change.from.line + change.text.length - 1,
4569 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
4570 }
4571
4572 // Adjust a position to refer to the post-change position of the
4573 // same text, or the end of the change if the change covers it.
4574 function adjustForChange(pos, change) {
4575 if (cmp(pos, change.from) < 0) { return pos }
4576 if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
4577
4578 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4579 if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
4580 return Pos(line, ch)
4581 }
4582
4583 function computeSelAfterChange(doc, change) {
4584 var out = [];
4585 for (var i = 0; i < doc.sel.ranges.length; i++) {
4586 var range = doc.sel.ranges[i];
4587 out.push(new Range(adjustForChange(range.anchor, change),
4588 adjustForChange(range.head, change)));
4589 }
4590 return normalizeSelection(out, doc.sel.primIndex)
4591 }
4592
4593 function offsetPos(pos, old, nw) {
4594 if (pos.line == old.line)
4595 { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
4596 else
4597 { return Pos(nw.line + (pos.line - old.line), pos.ch) }
4598 }
4599
4600 // Used by replaceSelections to allow moving the selection to the
4601 // start or around the replaced test. Hint may be "start" or "around".
4602 function computeReplacedSel(doc, changes, hint) {
4603 var out = [];
4604 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4605 for (var i = 0; i < changes.length; i++) {
4606 var change = changes[i];
4607 var from = offsetPos(change.from, oldPrev, newPrev);
4608 var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4609 oldPrev = change.to;
4610 newPrev = to;
4611 if (hint == "around") {
4612 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4613 out[i] = new Range(inv ? to : from, inv ? from : to);
4614 } else {
4615 out[i] = new Range(from, from);
4616 }
4617 }
4618 return new Selection(out, doc.sel.primIndex)
4619 }
4620
4621 // Used to get the editor into a consistent state again when options change.
4622
4623 function loadMode(cm) {
4624 cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4625 resetModeState(cm);
4626 }
4627
4628 function resetModeState(cm) {
4629 cm.doc.iter(function (line) {
4630 if (line.stateAfter) { line.stateAfter = null; }
4631 if (line.styles) { line.styles = null; }
4632 });
4633 cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
4634 startWorker(cm, 100);
4635 cm.state.modeGen++;
4636 if (cm.curOp) { regChange(cm); }
4637 }
4638
4639 // DOCUMENT DATA STRUCTURE
4640
4641 // By default, updates that start and end at the beginning of a line
4642 // are treated specially, in order to make the association of line
4643 // widgets and marker elements with the text behave more intuitive.
4644 function isWholeLineUpdate(doc, change) {
4645 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
4646 (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
4647 }
4648
4649 // Perform a change on the document data structure.
4650 function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
4651 function spansFor(n) {return markedSpans ? markedSpans[n] : null}
4652 function update(line, text, spans) {
4653 updateLine(line, text, spans, estimateHeight$$1);
4654 signalLater(line, "change", line, change);
4655 }
4656 function linesFor(start, end) {
4657 var result = [];
4658 for (var i = start; i < end; ++i)
4659 { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
4660 return result
4661 }
4662
4663 var from = change.from, to = change.to, text = change.text;
4664 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4665 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4666
4667 // Adjust the line structure
4668 if (change.full) {
4669 doc.insert(0, linesFor(0, text.length));
4670 doc.remove(text.length, doc.size - text.length);
4671 } else if (isWholeLineUpdate(doc, change)) {
4672 // This is a whole-line replace. Treated specially to make
4673 // sure line objects move the way they are supposed to.
4674 var added = linesFor(0, text.length - 1);
4675 update(lastLine, lastLine.text, lastSpans);
4676 if (nlines) { doc.remove(from.line, nlines); }
4677 if (added.length) { doc.insert(from.line, added); }
4678 } else if (firstLine == lastLine) {
4679 if (text.length == 1) {
4680 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4681 } else {
4682 var added$1 = linesFor(1, text.length - 1);
4683 added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
4684 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4685 doc.insert(from.line + 1, added$1);
4686 }
4687 } else if (text.length == 1) {
4688 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4689 doc.remove(from.line + 1, nlines);
4690 } else {
4691 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4692 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4693 var added$2 = linesFor(1, text.length - 1);
4694 if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
4695 doc.insert(from.line + 1, added$2);
4696 }
4697
4698 signalLater(doc, "change", doc, change);
4699 }
4700
4701 // Call f for all linked documents.
4702 function linkedDocs(doc, f, sharedHistOnly) {
4703 function propagate(doc, skip, sharedHist) {
4704 if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
4705 var rel = doc.linked[i];
4706 if (rel.doc == skip) { continue }
4707 var shared = sharedHist && rel.sharedHist;
4708 if (sharedHistOnly && !shared) { continue }
4709 f(rel.doc, shared);
4710 propagate(rel.doc, doc, shared);
4711 } }
4712 }
4713 propagate(doc, null, true);
4714 }
4715
4716 // Attach a document to an editor.
4717 function attachDoc(cm, doc) {
4718 if (doc.cm) { throw new Error("This document is already in use.") }
4719 cm.doc = doc;
4720 doc.cm = cm;
4721 estimateLineHeights(cm);
4722 loadMode(cm);
4723 setDirectionClass(cm);
4724 if (!cm.options.lineWrapping) { findMaxLine(cm); }
4725 cm.options.mode = doc.modeOption;
4726 regChange(cm);
4727 }
4728
4729 function setDirectionClass(cm) {
4730 (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
4731 }
4732
4733 function directionChanged(cm) {
4734 runInOp(cm, function () {
4735 setDirectionClass(cm);
4736 regChange(cm);
4737 });
4738 }
4739
4740 function History(startGen) {
4741 // Arrays of change events and selections. Doing something adds an
4742 // event to done and clears undo. Undoing moves events from done
4743 // to undone, redoing moves them in the other direction.
4744 this.done = []; this.undone = [];
4745 this.undoDepth = Infinity;
4746 // Used to track when changes can be merged into a single undo
4747 // event
4748 this.lastModTime = this.lastSelTime = 0;
4749 this.lastOp = this.lastSelOp = null;
4750 this.lastOrigin = this.lastSelOrigin = null;
4751 // Used by the isClean() method
4752 this.generation = this.maxGeneration = startGen || 1;
4753 }
4754
4755 // Create a history change event from an updateDoc-style change
4756 // object.
4757 function historyChangeFromChange(doc, change) {
4758 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4759 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4760 linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
4761 return histChange
4762 }
4763
4764 // Pop all selection events off the end of a history array. Stop at
4765 // a change event.
4766 function clearSelectionEvents(array) {
4767 while (array.length) {
4768 var last = lst(array);
4769 if (last.ranges) { array.pop(); }
4770 else { break }
4771 }
4772 }
4773
4774 // Find the top change event in the history. Pop off selection
4775 // events that are in the way.
4776 function lastChangeEvent(hist, force) {
4777 if (force) {
4778 clearSelectionEvents(hist.done);
4779 return lst(hist.done)
4780 } else if (hist.done.length && !lst(hist.done).ranges) {
4781 return lst(hist.done)
4782 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
4783 hist.done.pop();
4784 return lst(hist.done)
4785 }
4786 }
4787
4788 // Register a change in the history. Merges changes that are within
4789 // a single operation, or are close together with an origin that
4790 // allows merging (starting with "+") into a single event.
4791 function addChangeToHistory(doc, change, selAfter, opId) {
4792 var hist = doc.history;
4793 hist.undone.length = 0;
4794 var time = +new Date, cur;
4795 var last;
4796
4797 if ((hist.lastOp == opId ||
4798 hist.lastOrigin == change.origin && change.origin &&
4799 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
4800 change.origin.charAt(0) == "*")) &&
4801 (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
4802 // Merge this change into the last event
4803 last = lst(cur.changes);
4804 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
4805 // Optimized case for simple insertion -- don't want to add
4806 // new changesets for every character typed
4807 last.to = changeEnd(change);
4808 } else {
4809 // Add new sub-event
4810 cur.changes.push(historyChangeFromChange(doc, change));
4811 }
4812 } else {
4813 // Can not be merged, start a new event.
4814 var before = lst(hist.done);
4815 if (!before || !before.ranges)
4816 { pushSelectionToHistory(doc.sel, hist.done); }
4817 cur = {changes: [historyChangeFromChange(doc, change)],
4818 generation: hist.generation};
4819 hist.done.push(cur);
4820 while (hist.done.length > hist.undoDepth) {
4821 hist.done.shift();
4822 if (!hist.done[0].ranges) { hist.done.shift(); }
4823 }
4824 }
4825 hist.done.push(selAfter);
4826 hist.generation = ++hist.maxGeneration;
4827 hist.lastModTime = hist.lastSelTime = time;
4828 hist.lastOp = hist.lastSelOp = opId;
4829 hist.lastOrigin = hist.lastSelOrigin = change.origin;
4830
4831 if (!last) { signal(doc, "historyAdded"); }
4832 }
4833
4834 function selectionEventCanBeMerged(doc, origin, prev, sel) {
4835 var ch = origin.charAt(0);
4836 return ch == "*" ||
4837 ch == "+" &&
4838 prev.ranges.length == sel.ranges.length &&
4839 prev.somethingSelected() == sel.somethingSelected() &&
4840 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
4841 }
4842
4843 // Called whenever the selection changes, sets the new selection as
4844 // the pending selection in the history, and pushes the old pending
4845 // selection into the 'done' array when it was significantly
4846 // different (in number of selected ranges, emptiness, or time).
4847 function addSelectionToHistory(doc, sel, opId, options) {
4848 var hist = doc.history, origin = options && options.origin;
4849
4850 // A new event is started when the previous origin does not match
4851 // the current, or the origins don't allow matching. Origins
4852 // starting with * are always merged, those starting with + are
4853 // merged when similar and close together in time.
4854 if (opId == hist.lastSelOp ||
4855 (origin && hist.lastSelOrigin == origin &&
4856 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
4857 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
4858 { hist.done[hist.done.length - 1] = sel; }
4859 else
4860 { pushSelectionToHistory(sel, hist.done); }
4861
4862 hist.lastSelTime = +new Date;
4863 hist.lastSelOrigin = origin;
4864 hist.lastSelOp = opId;
4865 if (options && options.clearRedo !== false)
4866 { clearSelectionEvents(hist.undone); }
4867 }
4868
4869 function pushSelectionToHistory(sel, dest) {
4870 var top = lst(dest);
4871 if (!(top && top.ranges && top.equals(sel)))
4872 { dest.push(sel); }
4873 }
4874
4875 // Used to store marked span information in the history.
4876 function attachLocalSpans(doc, change, from, to) {
4877 var existing = change["spans_" + doc.id], n = 0;
4878 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
4879 if (line.markedSpans)
4880 { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
4881 ++n;
4882 });
4883 }
4884
4885 // When un/re-doing restores text containing marked spans, those
4886 // that have been explicitly cleared should not be restored.
4887 function removeClearedSpans(spans) {
4888 if (!spans) { return null }
4889 var out;
4890 for (var i = 0; i < spans.length; ++i) {
4891 if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
4892 else if (out) { out.push(spans[i]); }
4893 }
4894 return !out ? spans : out.length ? out : null
4895 }
4896
4897 // Retrieve and filter the old marked spans stored in a change event.
4898 function getOldSpans(doc, change) {
4899 var found = change["spans_" + doc.id];
4900 if (!found) { return null }
4901 var nw = [];
4902 for (var i = 0; i < change.text.length; ++i)
4903 { nw.push(removeClearedSpans(found[i])); }
4904 return nw
4905 }
4906
4907 // Used for un/re-doing changes from the history. Combines the
4908 // result of computing the existing spans with the set of spans that
4909 // existed in the history (so that deleting around a span and then
4910 // undoing brings back the span).
4911 function mergeOldSpans(doc, change) {
4912 var old = getOldSpans(doc, change);
4913 var stretched = stretchSpansOverChange(doc, change);
4914 if (!old) { return stretched }
4915 if (!stretched) { return old }
4916
4917 for (var i = 0; i < old.length; ++i) {
4918 var oldCur = old[i], stretchCur = stretched[i];
4919 if (oldCur && stretchCur) {
4920 spans: for (var j = 0; j < stretchCur.length; ++j) {
4921 var span = stretchCur[j];
4922 for (var k = 0; k < oldCur.length; ++k)
4923 { if (oldCur[k].marker == span.marker) { continue spans } }
4924 oldCur.push(span);
4925 }
4926 } else if (stretchCur) {
4927 old[i] = stretchCur;
4928 }
4929 }
4930 return old
4931 }
4932
4933 // Used both to provide a JSON-safe object in .getHistory, and, when
4934 // detaching a document, to split the history in two
4935 function copyHistoryArray(events, newGroup, instantiateSel) {
4936 var copy = [];
4937 for (var i = 0; i < events.length; ++i) {
4938 var event = events[i];
4939 if (event.ranges) {
4940 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
4941 continue
4942 }
4943 var changes = event.changes, newChanges = [];
4944 copy.push({changes: newChanges});
4945 for (var j = 0; j < changes.length; ++j) {
4946 var change = changes[j], m = (void 0);
4947 newChanges.push({from: change.from, to: change.to, text: change.text});
4948 if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
4949 if (indexOf(newGroup, Number(m[1])) > -1) {
4950 lst(newChanges)[prop] = change[prop];
4951 delete change[prop];
4952 }
4953 } } }
4954 }
4955 }
4956 return copy
4957 }
4958
4959 // The 'scroll' parameter given to many of these indicated whether
4960 // the new cursor position should be scrolled into view after
4961 // modifying the selection.
4962
4963 // If shift is held or the extend flag is set, extends a range to
4964 // include a given position (and optionally a second position).
4965 // Otherwise, simply returns the range between the given positions.
4966 // Used for cursor motion and such.
4967 function extendRange(range, head, other, extend) {
4968 if (extend) {
4969 var anchor = range.anchor;
4970 if (other) {
4971 var posBefore = cmp(head, anchor) < 0;
4972 if (posBefore != (cmp(other, anchor) < 0)) {
4973 anchor = head;
4974 head = other;
4975 } else if (posBefore != (cmp(head, other) < 0)) {
4976 head = other;
4977 }
4978 }
4979 return new Range(anchor, head)
4980 } else {
4981 return new Range(other || head, head)
4982 }
4983 }
4984
4985 // Extend the primary selection range, discard the rest.
4986 function extendSelection(doc, head, other, options, extend) {
4987 if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
4988 setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
4989 }
4990
4991 // Extend all selections (pos is an array of selections with length
4992 // equal the number of selections)
4993 function extendSelections(doc, heads, options) {
4994 var out = [];
4995 var extend = doc.cm && (doc.cm.display.shift || doc.extend);
4996 for (var i = 0; i < doc.sel.ranges.length; i++)
4997 { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
4998 var newSel = normalizeSelection(out, doc.sel.primIndex);
4999 setSelection(doc, newSel, options);
5000 }
5001
5002 // Updates a single range in the selection.
5003 function replaceOneSelection(doc, i, range, options) {
5004 var ranges = doc.sel.ranges.slice(0);
5005 ranges[i] = range;
5006 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
5007 }
5008
5009 // Reset the selection to a single range.
5010 function setSimpleSelection(doc, anchor, head, options) {
5011 setSelection(doc, simpleSelection(anchor, head), options);
5012 }
5013
5014 // Give beforeSelectionChange handlers a change to influence a
5015 // selection update.
5016 function filterSelectionChange(doc, sel, options) {
5017 var obj = {
5018 ranges: sel.ranges,
5019 update: function(ranges) {
5020 var this$1 = this;
5021
5022 this.ranges = [];
5023 for (var i = 0; i < ranges.length; i++)
5024 { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
5025 clipPos(doc, ranges[i].head)); }
5026 },
5027 origin: options && options.origin
5028 };
5029 signal(doc, "beforeSelectionChange", doc, obj);
5030 if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
5031 if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
5032 else { return sel }
5033 }
5034
5035 function setSelectionReplaceHistory(doc, sel, options) {
5036 var done = doc.history.done, last = lst(done);
5037 if (last && last.ranges) {
5038 done[done.length - 1] = sel;
5039 setSelectionNoUndo(doc, sel, options);
5040 } else {
5041 setSelection(doc, sel, options);
5042 }
5043 }
5044
5045 // Set a new selection.
5046 function setSelection(doc, sel, options) {
5047 setSelectionNoUndo(doc, sel, options);
5048 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
5049 }
5050
5051 function setSelectionNoUndo(doc, sel, options) {
5052 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5053 { sel = filterSelectionChange(doc, sel, options); }
5054
5055 var bias = options && options.bias ||
5056 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
5057 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
5058
5059 if (!(options && options.scroll === false) && doc.cm)
5060 { ensureCursorVisible(doc.cm); }
5061 }
5062
5063 function setSelectionInner(doc, sel) {
5064 if (sel.equals(doc.sel)) { return }
5065
5066 doc.sel = sel;
5067
5068 if (doc.cm) {
5069 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
5070 signalCursorActivity(doc.cm);
5071 }
5072 signalLater(doc, "cursorActivity", doc);
5073 }
5074
5075 // Verify that the selection does not partially select any atomic
5076 // marked ranges.
5077 function reCheckSelection(doc) {
5078 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
5079 }
5080
5081 // Return a selection that does not partially select any atomic
5082 // ranges.
5083 function skipAtomicInSelection(doc, sel, bias, mayClear) {
5084 var out;
5085 for (var i = 0; i < sel.ranges.length; i++) {
5086 var range = sel.ranges[i];
5087 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
5088 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
5089 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
5090 if (out || newAnchor != range.anchor || newHead != range.head) {
5091 if (!out) { out = sel.ranges.slice(0, i); }
5092 out[i] = new Range(newAnchor, newHead);
5093 }
5094 }
5095 return out ? normalizeSelection(out, sel.primIndex) : sel
5096 }
5097
5098 function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
5099 var line = getLine(doc, pos.line);
5100 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
5101 var sp = line.markedSpans[i], m = sp.marker;
5102 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
5103 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
5104 if (mayClear) {
5105 signal(m, "beforeCursorEnter");
5106 if (m.explicitlyCleared) {
5107 if (!line.markedSpans) { break }
5108 else {--i; continue}
5109 }
5110 }
5111 if (!m.atomic) { continue }
5112
5113 if (oldPos) {
5114 var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
5115 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
5116 { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
5117 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
5118 { return skipAtomicInner(doc, near, pos, dir, mayClear) }
5119 }
5120
5121 var far = m.find(dir < 0 ? -1 : 1);
5122 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
5123 { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
5124 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
5125 }
5126 } }
5127 return pos
5128 }
5129
5130 // Ensure a given position is not inside an atomic range.
5131 function skipAtomic(doc, pos, oldPos, bias, mayClear) {
5132 var dir = bias || 1;
5133 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
5134 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
5135 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
5136 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
5137 if (!found) {
5138 doc.cantEdit = true;
5139 return Pos(doc.first, 0)
5140 }
5141 return found
5142 }
5143
5144 function movePos(doc, pos, dir, line) {
5145 if (dir < 0 && pos.ch == 0) {
5146 if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
5147 else { return null }
5148 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
5149 if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
5150 else { return null }
5151 } else {
5152 return new Pos(pos.line, pos.ch + dir)
5153 }
5154 }
5155
5156 function selectAll(cm) {
5157 cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
5158 }
5159
5160 // UPDATING
5161
5162 // Allow "beforeChange" event handlers to influence a change
5163 function filterChange(doc, change, update) {
5164 var obj = {
5165 canceled: false,
5166 from: change.from,
5167 to: change.to,
5168 text: change.text,
5169 origin: change.origin,
5170 cancel: function () { return obj.canceled = true; }
5171 };
5172 if (update) { obj.update = function (from, to, text, origin) {
5173 if (from) { obj.from = clipPos(doc, from); }
5174 if (to) { obj.to = clipPos(doc, to); }
5175 if (text) { obj.text = text; }
5176 if (origin !== undefined) { obj.origin = origin; }
5177 }; }
5178 signal(doc, "beforeChange", doc, obj);
5179 if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
5180
5181 if (obj.canceled) { return null }
5182 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
5183 }
5184
5185 // Apply a change to a document, and add it to the document's
5186 // history, and propagating it to all linked documents.
5187 function makeChange(doc, change, ignoreReadOnly) {
5188 if (doc.cm) {
5189 if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
5190 if (doc.cm.state.suppressEdits) { return }
5191 }
5192
5193 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5194 change = filterChange(doc, change, true);
5195 if (!change) { return }
5196 }
5197
5198 // Possibly split or suppress the update based on the presence
5199 // of read-only spans in its range.
5200 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
5201 if (split) {
5202 for (var i = split.length - 1; i >= 0; --i)
5203 { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
5204 } else {
5205 makeChangeInner(doc, change);
5206 }
5207 }
5208
5209 function makeChangeInner(doc, change) {
5210 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
5211 var selAfter = computeSelAfterChange(doc, change);
5212 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
5213
5214 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
5215 var rebased = [];
5216
5217 linkedDocs(doc, function (doc, sharedHist) {
5218 if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5219 rebaseHist(doc.history, change);
5220 rebased.push(doc.history);
5221 }
5222 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
5223 });
5224 }
5225
5226 // Revert a change stored in a document's history.
5227 function makeChangeFromHistory(doc, type, allowSelectionOnly) {
5228 if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
5229
5230 var hist = doc.history, event, selAfter = doc.sel;
5231 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
5232
5233 // Verify that there is a useable event (so that ctrl-z won't
5234 // needlessly clear selection events)
5235 var i = 0;
5236 for (; i < source.length; i++) {
5237 event = source[i];
5238 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
5239 { break }
5240 }
5241 if (i == source.length) { return }
5242 hist.lastOrigin = hist.lastSelOrigin = null;
5243
5244 for (;;) {
5245 event = source.pop();
5246 if (event.ranges) {
5247 pushSelectionToHistory(event, dest);
5248 if (allowSelectionOnly && !event.equals(doc.sel)) {
5249 setSelection(doc, event, {clearRedo: false});
5250 return
5251 }
5252 selAfter = event;
5253 }
5254 else { break }
5255 }
5256
5257 // Build up a reverse change object to add to the opposite history
5258 // stack (redo when undoing, and vice versa).
5259 var antiChanges = [];
5260 pushSelectionToHistory(selAfter, dest);
5261 dest.push({changes: antiChanges, generation: hist.generation});
5262 hist.generation = event.generation || ++hist.maxGeneration;
5263
5264 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
5265
5266 var loop = function ( i ) {
5267 var change = event.changes[i];
5268 change.origin = type;
5269 if (filter && !filterChange(doc, change, false)) {
5270 source.length = 0;
5271 return {}
5272 }
5273
5274 antiChanges.push(historyChangeFromChange(doc, change));
5275
5276 var after = i ? computeSelAfterChange(doc, change) : lst(source);
5277 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
5278 if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
5279 var rebased = [];
5280
5281 // Propagate to the linked documents
5282 linkedDocs(doc, function (doc, sharedHist) {
5283 if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5284 rebaseHist(doc.history, change);
5285 rebased.push(doc.history);
5286 }
5287 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5288 });
5289 };
5290
5291 for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5292 var returned = loop( i$1 );
5293
5294 if ( returned ) return returned.v;
5295 }
5296 }
5297
5298 // Sub-views need their line numbers shifted when text is added
5299 // above or below them in the parent document.
5300 function shiftDoc(doc, distance) {
5301 if (distance == 0) { return }
5302 doc.first += distance;
5303 doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
5304 Pos(range.anchor.line + distance, range.anchor.ch),
5305 Pos(range.head.line + distance, range.head.ch)
5306 ); }), doc.sel.primIndex);
5307 if (doc.cm) {
5308 regChange(doc.cm, doc.first, doc.first - distance, distance);
5309 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
5310 { regLineChange(doc.cm, l, "gutter"); }
5311 }
5312 }
5313
5314 // More lower-level change function, handling only a single document
5315 // (not linked ones).
5316 function makeChangeSingleDoc(doc, change, selAfter, spans) {
5317 if (doc.cm && !doc.cm.curOp)
5318 { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
5319
5320 if (change.to.line < doc.first) {
5321 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
5322 return
5323 }
5324 if (change.from.line > doc.lastLine()) { return }
5325
5326 // Clip the change to the size of this doc
5327 if (change.from.line < doc.first) {
5328 var shift = change.text.length - 1 - (doc.first - change.from.line);
5329 shiftDoc(doc, shift);
5330 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
5331 text: [lst(change.text)], origin: change.origin};
5332 }
5333 var last = doc.lastLine();
5334 if (change.to.line > last) {
5335 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
5336 text: [change.text[0]], origin: change.origin};
5337 }
5338
5339 change.removed = getBetween(doc, change.from, change.to);
5340
5341 if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
5342 if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
5343 else { updateDoc(doc, change, spans); }
5344 setSelectionNoUndo(doc, selAfter, sel_dontScroll);
5345 }
5346
5347 // Handle the interaction of a change to a document with the editor
5348 // that this document is part of.
5349 function makeChangeSingleDocInEditor(cm, change, spans) {
5350 var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
5351
5352 var recomputeMaxLength = false, checkWidthStart = from.line;
5353 if (!cm.options.lineWrapping) {
5354 checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
5355 doc.iter(checkWidthStart, to.line + 1, function (line) {
5356 if (line == display.maxLine) {
5357 recomputeMaxLength = true;
5358 return true
5359 }
5360 });
5361 }
5362
5363 if (doc.sel.contains(change.from, change.to) > -1)
5364 { signalCursorActivity(cm); }
5365
5366 updateDoc(doc, change, spans, estimateHeight(cm));
5367
5368 if (!cm.options.lineWrapping) {
5369 doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
5370 var len = lineLength(line);
5371 if (len > display.maxLineLength) {
5372 display.maxLine = line;
5373 display.maxLineLength = len;
5374 display.maxLineChanged = true;
5375 recomputeMaxLength = false;
5376 }
5377 });
5378 if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
5379 }
5380
5381 retreatFrontier(doc, from.line);
5382 startWorker(cm, 400);
5383
5384 var lendiff = change.text.length - (to.line - from.line) - 1;
5385 // Remember that these lines changed, for updating the display
5386 if (change.full)
5387 { regChange(cm); }
5388 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
5389 { regLineChange(cm, from.line, "text"); }
5390 else
5391 { regChange(cm, from.line, to.line + 1, lendiff); }
5392
5393 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
5394 if (changeHandler || changesHandler) {
5395 var obj = {
5396 from: from, to: to,
5397 text: change.text,
5398 removed: change.removed,
5399 origin: change.origin
5400 };
5401 if (changeHandler) { signalLater(cm, "change", cm, obj); }
5402 if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
5403 }
5404 cm.display.selForContextMenu = null;
5405 }
5406
5407 function replaceRange(doc, code, from, to, origin) {
5408 if (!to) { to = from; }
5409 if (cmp(to, from) < 0) { var assign;
5410 (assign = [to, from], from = assign[0], to = assign[1]); }
5411 if (typeof code == "string") { code = doc.splitLines(code); }
5412 makeChange(doc, {from: from, to: to, text: code, origin: origin});
5413 }
5414
5415 // Rebasing/resetting history to deal with externally-sourced changes
5416
5417 function rebaseHistSelSingle(pos, from, to, diff) {
5418 if (to < pos.line) {
5419 pos.line += diff;
5420 } else if (from < pos.line) {
5421 pos.line = from;
5422 pos.ch = 0;
5423 }
5424 }
5425
5426 // Tries to rebase an array of history events given a change in the
5427 // document. If the change touches the same lines as the event, the
5428 // event, and everything 'behind' it, is discarded. If the change is
5429 // before the event, the event's positions are updated. Uses a
5430 // copy-on-write scheme for the positions, to avoid having to
5431 // reallocate them all on every rebase, but also avoid problems with
5432 // shared position objects being unsafely updated.
5433 function rebaseHistArray(array, from, to, diff) {
5434 for (var i = 0; i < array.length; ++i) {
5435 var sub = array[i], ok = true;
5436 if (sub.ranges) {
5437 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
5438 for (var j = 0; j < sub.ranges.length; j++) {
5439 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
5440 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
5441 }
5442 continue
5443 }
5444 for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
5445 var cur = sub.changes[j$1];
5446 if (to < cur.from.line) {
5447 cur.from = Pos(cur.from.line + diff, cur.from.ch);
5448 cur.to = Pos(cur.to.line + diff, cur.to.ch);
5449 } else if (from <= cur.to.line) {
5450 ok = false;
5451 break
5452 }
5453 }
5454 if (!ok) {
5455 array.splice(0, i + 1);
5456 i = 0;
5457 }
5458 }
5459 }
5460
5461 function rebaseHist(hist, change) {
5462 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5463 rebaseHistArray(hist.done, from, to, diff);
5464 rebaseHistArray(hist.undone, from, to, diff);
5465 }
5466
5467 // Utility for applying a change to a line by handle or number,
5468 // returning the number and optionally registering the line as
5469 // changed.
5470 function changeLine(doc, handle, changeType, op) {
5471 var no = handle, line = handle;
5472 if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
5473 else { no = lineNo(handle); }
5474 if (no == null) { return null }
5475 if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
5476 return line
5477 }
5478
5479 // The document is represented as a BTree consisting of leaves, with
5480 // chunk of lines in them, and branches, with up to ten leaves or
5481 // other branch nodes below them. The top node is always a branch
5482 // node, and is the document object itself (meaning it has
5483 // additional methods and properties).
5484 //
5485 // All nodes have parent links. The tree is used both to go from
5486 // line numbers to line objects, and to go from objects to numbers.
5487 // It also indexes by height, and is used to convert between height
5488 // and line object, and to find the total height of the document.
5489 //
5490 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
5491
5492 function LeafChunk(lines) {
5493 var this$1 = this;
5494
5495 this.lines = lines;
5496 this.parent = null;
5497 var height = 0;
5498 for (var i = 0; i < lines.length; ++i) {
5499 lines[i].parent = this$1;
5500 height += lines[i].height;
5501 }
5502 this.height = height;
5503 }
5504
5505 LeafChunk.prototype = {
5506 chunkSize: function() { return this.lines.length },
5507
5508 // Remove the n lines at offset 'at'.
5509 removeInner: function(at, n) {
5510 var this$1 = this;
5511
5512 for (var i = at, e = at + n; i < e; ++i) {
5513 var line = this$1.lines[i];
5514 this$1.height -= line.height;
5515 cleanUpLine(line);
5516 signalLater(line, "delete");
5517 }
5518 this.lines.splice(at, n);
5519 },
5520
5521 // Helper used to collapse a small branch into a single leaf.
5522 collapse: function(lines) {
5523 lines.push.apply(lines, this.lines);
5524 },
5525
5526 // Insert the given array of lines at offset 'at', count them as
5527 // having the given height.
5528 insertInner: function(at, lines, height) {
5529 var this$1 = this;
5530
5531 this.height += height;
5532 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
5533 for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
5534 },
5535
5536 // Used to iterate over a part of the tree.
5537 iterN: function(at, n, op) {
5538 var this$1 = this;
5539
5540 for (var e = at + n; at < e; ++at)
5541 { if (op(this$1.lines[at])) { return true } }
5542 }
5543 };
5544
5545 function BranchChunk(children) {
5546 var this$1 = this;
5547
5548 this.children = children;
5549 var size = 0, height = 0;
5550 for (var i = 0; i < children.length; ++i) {
5551 var ch = children[i];
5552 size += ch.chunkSize(); height += ch.height;
5553 ch.parent = this$1;
5554 }
5555 this.size = size;
5556 this.height = height;
5557 this.parent = null;
5558 }
5559
5560 BranchChunk.prototype = {
5561 chunkSize: function() { return this.size },
5562
5563 removeInner: function(at, n) {
5564 var this$1 = this;
5565
5566 this.size -= n;
5567 for (var i = 0; i < this.children.length; ++i) {
5568 var child = this$1.children[i], sz = child.chunkSize();
5569 if (at < sz) {
5570 var rm = Math.min(n, sz - at), oldHeight = child.height;
5571 child.removeInner(at, rm);
5572 this$1.height -= oldHeight - child.height;
5573 if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
5574 if ((n -= rm) == 0) { break }
5575 at = 0;
5576 } else { at -= sz; }
5577 }
5578 // If the result is smaller than 25 lines, ensure that it is a
5579 // single leaf node.
5580 if (this.size - n < 25 &&
5581 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
5582 var lines = [];
5583 this.collapse(lines);
5584 this.children = [new LeafChunk(lines)];
5585 this.children[0].parent = this;
5586 }
5587 },
5588
5589 collapse: function(lines) {
5590 var this$1 = this;
5591
5592 for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
5593 },
5594
5595 insertInner: function(at, lines, height) {
5596 var this$1 = this;
5597
5598 this.size += lines.length;
5599 this.height += height;
5600 for (var i = 0; i < this.children.length; ++i) {
5601 var child = this$1.children[i], sz = child.chunkSize();
5602 if (at <= sz) {
5603 child.insertInner(at, lines, height);
5604 if (child.lines && child.lines.length > 50) {
5605 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
5606 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
5607 var remaining = child.lines.length % 25 + 25;
5608 for (var pos = remaining; pos < child.lines.length;) {
5609 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
5610 child.height -= leaf.height;
5611 this$1.children.splice(++i, 0, leaf);
5612 leaf.parent = this$1;
5613 }
5614 child.lines = child.lines.slice(0, remaining);
5615 this$1.maybeSpill();
5616 }
5617 break
5618 }
5619 at -= sz;
5620 }
5621 },
5622
5623 // When a node has grown, check whether it should be split.
5624 maybeSpill: function() {
5625 if (this.children.length <= 10) { return }
5626 var me = this;
5627 do {
5628 var spilled = me.children.splice(me.children.length - 5, 5);
5629 var sibling = new BranchChunk(spilled);
5630 if (!me.parent) { // Become the parent node
5631 var copy = new BranchChunk(me.children);
5632 copy.parent = me;
5633 me.children = [copy, sibling];
5634 me = copy;
5635 } else {
5636 me.size -= sibling.size;
5637 me.height -= sibling.height;
5638 var myIndex = indexOf(me.parent.children, me);
5639 me.parent.children.splice(myIndex + 1, 0, sibling);
5640 }
5641 sibling.parent = me.parent;
5642 } while (me.children.length > 10)
5643 me.parent.maybeSpill();
5644 },
5645
5646 iterN: function(at, n, op) {
5647 var this$1 = this;
5648
5649 for (var i = 0; i < this.children.length; ++i) {
5650 var child = this$1.children[i], sz = child.chunkSize();
5651 if (at < sz) {
5652 var used = Math.min(n, sz - at);
5653 if (child.iterN(at, used, op)) { return true }
5654 if ((n -= used) == 0) { break }
5655 at = 0;
5656 } else { at -= sz; }
5657 }
5658 }
5659 };
5660
5661 // Line widgets are block elements displayed above or below a line.
5662
5663 var LineWidget = function(doc, node, options) {
5664 var this$1 = this;
5665
5666 if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
5667 { this$1[opt] = options[opt]; } } }
5668 this.doc = doc;
5669 this.node = node;
5670 };
5671
5672 LineWidget.prototype.clear = function () {
5673 var this$1 = this;
5674
5675 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5676 if (no == null || !ws) { return }
5677 for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
5678 if (!ws.length) { line.widgets = null; }
5679 var height = widgetHeight(this);
5680 updateLineHeight(line, Math.max(0, line.height - height));
5681 if (cm) {
5682 runInOp(cm, function () {
5683 adjustScrollWhenAboveVisible(cm, line, -height);
5684 regLineChange(cm, no, "widget");
5685 });
5686 signalLater(cm, "lineWidgetCleared", cm, this, no);
5687 }
5688 };
5689
5690 LineWidget.prototype.changed = function () {
5691 var this$1 = this;
5692
5693 var oldH = this.height, cm = this.doc.cm, line = this.line;
5694 this.height = null;
5695 var diff = widgetHeight(this) - oldH;
5696 if (!diff) { return }
5697 updateLineHeight(line, line.height + diff);
5698 if (cm) {
5699 runInOp(cm, function () {
5700 cm.curOp.forceUpdate = true;
5701 adjustScrollWhenAboveVisible(cm, line, diff);
5702 signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
5703 });
5704 }
5705 };
5706 eventMixin(LineWidget);
5707
5708 function adjustScrollWhenAboveVisible(cm, line, diff) {
5709 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5710 { addToScrollTop(cm, diff); }
5711 }
5712
5713 function addLineWidget(doc, handle, node, options) {
5714 var widget = new LineWidget(doc, node, options);
5715 var cm = doc.cm;
5716 if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
5717 changeLine(doc, handle, "widget", function (line) {
5718 var widgets = line.widgets || (line.widgets = []);
5719 if (widget.insertAt == null) { widgets.push(widget); }
5720 else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
5721 widget.line = line;
5722 if (cm && !lineIsHidden(doc, line)) {
5723 var aboveVisible = heightAtLine(line) < doc.scrollTop;
5724 updateLineHeight(line, line.height + widgetHeight(widget));
5725 if (aboveVisible) { addToScrollTop(cm, widget.height); }
5726 cm.curOp.forceUpdate = true;
5727 }
5728 return true
5729 });
5730 signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
5731 return widget
5732 }
5733
5734 // TEXTMARKERS
5735
5736 // Created with markText and setBookmark methods. A TextMarker is a
5737 // handle that can be used to clear or find a marked position in the
5738 // document. Line objects hold arrays (markedSpans) containing
5739 // {from, to, marker} object pointing to such marker objects, and
5740 // indicating that such a marker is present on that line. Multiple
5741 // lines may point to the same marker when it spans across lines.
5742 // The spans will have null for their from/to properties when the
5743 // marker continues beyond the start/end of the line. Markers have
5744 // links back to the lines they currently touch.
5745
5746 // Collapsed markers have unique ids, in order to be able to order
5747 // them, which is needed for uniquely determining an outer marker
5748 // when they overlap (they may nest, but not partially overlap).
5749 var nextMarkerId = 0;
5750
5751 var TextMarker = function(doc, type) {
5752 this.lines = [];
5753 this.type = type;
5754 this.doc = doc;
5755 this.id = ++nextMarkerId;
5756 };
5757
5758 // Clear the marker.
5759 TextMarker.prototype.clear = function () {
5760 var this$1 = this;
5761
5762 if (this.explicitlyCleared) { return }
5763 var cm = this.doc.cm, withOp = cm && !cm.curOp;
5764 if (withOp) { startOperation(cm); }
5765 if (hasHandler(this, "clear")) {
5766 var found = this.find();
5767 if (found) { signalLater(this, "clear", found.from, found.to); }
5768 }
5769 var min = null, max = null;
5770 for (var i = 0; i < this.lines.length; ++i) {
5771 var line = this$1.lines[i];
5772 var span = getMarkedSpanFor(line.markedSpans, this$1);
5773 if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
5774 else if (cm) {
5775 if (span.to != null) { max = lineNo(line); }
5776 if (span.from != null) { min = lineNo(line); }
5777 }
5778 line.markedSpans = removeMarkedSpan(line.markedSpans, span);
5779 if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
5780 { updateLineHeight(line, textHeight(cm.display)); }
5781 }
5782 if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
5783 var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
5784 if (len > cm.display.maxLineLength) {
5785 cm.display.maxLine = visual;
5786 cm.display.maxLineLength = len;
5787 cm.display.maxLineChanged = true;
5788 }
5789 } }
5790
5791 if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
5792 this.lines.length = 0;
5793 this.explicitlyCleared = true;
5794 if (this.atomic && this.doc.cantEdit) {
5795 this.doc.cantEdit = false;
5796 if (cm) { reCheckSelection(cm.doc); }
5797 }
5798 if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
5799 if (withOp) { endOperation(cm); }
5800 if (this.parent) { this.parent.clear(); }
5801 };
5802
5803 // Find the position of the marker in the document. Returns a {from,
5804 // to} object by default. Side can be passed to get a specific side
5805 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5806 // Pos objects returned contain a line object, rather than a line
5807 // number (used to prevent looking up the same line twice).
5808 TextMarker.prototype.find = function (side, lineObj) {
5809 var this$1 = this;
5810
5811 if (side == null && this.type == "bookmark") { side = 1; }
5812 var from, to;
5813 for (var i = 0; i < this.lines.length; ++i) {
5814 var line = this$1.lines[i];
5815 var span = getMarkedSpanFor(line.markedSpans, this$1);
5816 if (span.from != null) {
5817 from = Pos(lineObj ? line : lineNo(line), span.from);
5818 if (side == -1) { return from }
5819 }
5820 if (span.to != null) {
5821 to = Pos(lineObj ? line : lineNo(line), span.to);
5822 if (side == 1) { return to }
5823 }
5824 }
5825 return from && {from: from, to: to}
5826 };
5827
5828 // Signals that the marker's widget changed, and surrounding layout
5829 // should be recomputed.
5830 TextMarker.prototype.changed = function () {
5831 var this$1 = this;
5832
5833 var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
5834 if (!pos || !cm) { return }
5835 runInOp(cm, function () {
5836 var line = pos.line, lineN = lineNo(pos.line);
5837 var view = findViewForLine(cm, lineN);
5838 if (view) {
5839 clearLineMeasurementCacheFor(view);
5840 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
5841 }
5842 cm.curOp.updateMaxLine = true;
5843 if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5844 var oldHeight = widget.height;
5845 widget.height = null;
5846 var dHeight = widgetHeight(widget) - oldHeight;
5847 if (dHeight)
5848 { updateLineHeight(line, line.height + dHeight); }
5849 }
5850 signalLater(cm, "markerChanged", cm, this$1);
5851 });
5852 };
5853
5854 TextMarker.prototype.attachLine = function (line) {
5855 if (!this.lines.length && this.doc.cm) {
5856 var op = this.doc.cm.curOp;
5857 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5858 { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
5859 }
5860 this.lines.push(line);
5861 };
5862
5863 TextMarker.prototype.detachLine = function (line) {
5864 this.lines.splice(indexOf(this.lines, line), 1);
5865 if (!this.lines.length && this.doc.cm) {
5866 var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5867 }
5868 };
5869 eventMixin(TextMarker);
5870
5871 // Create a marker, wire it up to the right lines, and
5872 function markText(doc, from, to, options, type) {
5873 // Shared markers (across linked documents) are handled separately
5874 // (markTextShared will call out to this again, once per
5875 // document).
5876 if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
5877 // Ensure we are in an operation.
5878 if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
5879
5880 var marker = new TextMarker(doc, type), diff = cmp(from, to);
5881 if (options) { copyObj(options, marker, false); }
5882 // Don't connect empty markers unless clearWhenEmpty is false
5883 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
5884 { return marker }
5885 if (marker.replacedWith) {
5886 // Showing up as a widget implies collapsed (widget replaces text)
5887 marker.collapsed = true;
5888 marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
5889 if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
5890 if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
5891 }
5892 if (marker.collapsed) {
5893 if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
5894 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
5895 { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
5896 seeCollapsedSpans();
5897 }
5898
5899 if (marker.addToHistory)
5900 { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
5901
5902 var curLine = from.line, cm = doc.cm, updateMaxLine;
5903 doc.iter(curLine, to.line + 1, function (line) {
5904 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
5905 { updateMaxLine = true; }
5906 if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
5907 addMarkedSpan(line, new MarkedSpan(marker,
5908 curLine == from.line ? from.ch : null,
5909 curLine == to.line ? to.ch : null));
5910 ++curLine;
5911 });
5912 // lineIsHidden depends on the presence of the spans, so needs a second pass
5913 if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
5914 if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
5915 }); }
5916
5917 if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
5918
5919 if (marker.readOnly) {
5920 seeReadOnlySpans();
5921 if (doc.history.done.length || doc.history.undone.length)
5922 { doc.clearHistory(); }
5923 }
5924 if (marker.collapsed) {
5925 marker.id = ++nextMarkerId;
5926 marker.atomic = true;
5927 }
5928 if (cm) {
5929 // Sync editor state
5930 if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
5931 if (marker.collapsed)
5932 { regChange(cm, from.line, to.line + 1); }
5933 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
5934 { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
5935 if (marker.atomic) { reCheckSelection(cm.doc); }
5936 signalLater(cm, "markerAdded", cm, marker);
5937 }
5938 return marker
5939 }
5940
5941 // SHARED TEXTMARKERS
5942
5943 // A shared marker spans multiple linked documents. It is
5944 // implemented as a meta-marker-object controlling multiple normal
5945 // markers.
5946 var SharedTextMarker = function(markers, primary) {
5947 var this$1 = this;
5948
5949 this.markers = markers;
5950 this.primary = primary;
5951 for (var i = 0; i < markers.length; ++i)
5952 { markers[i].parent = this$1; }
5953 };
5954
5955 SharedTextMarker.prototype.clear = function () {
5956 var this$1 = this;
5957
5958 if (this.explicitlyCleared) { return }
5959 this.explicitlyCleared = true;
5960 for (var i = 0; i < this.markers.length; ++i)
5961 { this$1.markers[i].clear(); }
5962 signalLater(this, "clear");
5963 };
5964
5965 SharedTextMarker.prototype.find = function (side, lineObj) {
5966 return this.primary.find(side, lineObj)
5967 };
5968 eventMixin(SharedTextMarker);
5969
5970 function markTextShared(doc, from, to, options, type) {
5971 options = copyObj(options);
5972 options.shared = false;
5973 var markers = [markText(doc, from, to, options, type)], primary = markers[0];
5974 var widget = options.widgetNode;
5975 linkedDocs(doc, function (doc) {
5976 if (widget) { options.widgetNode = widget.cloneNode(true); }
5977 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
5978 for (var i = 0; i < doc.linked.length; ++i)
5979 { if (doc.linked[i].isParent) { return } }
5980 primary = lst(markers);
5981 });
5982 return new SharedTextMarker(markers, primary)
5983 }
5984
5985 function findSharedMarkers(doc) {
5986 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
5987 }
5988
5989 function copySharedMarkers(doc, markers) {
5990 for (var i = 0; i < markers.length; i++) {
5991 var marker = markers[i], pos = marker.find();
5992 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
5993 if (cmp(mFrom, mTo)) {
5994 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
5995 marker.markers.push(subMark);
5996 subMark.parent = marker;
5997 }
5998 }
5999 }
6000
6001 function detachSharedMarkers(markers) {
6002 var loop = function ( i ) {
6003 var marker = markers[i], linked = [marker.primary.doc];
6004 linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
6005 for (var j = 0; j < marker.markers.length; j++) {
6006 var subMarker = marker.markers[j];
6007 if (indexOf(linked, subMarker.doc) == -1) {
6008 subMarker.parent = null;
6009 marker.markers.splice(j--, 1);
6010 }
6011 }
6012 };
6013
6014 for (var i = 0; i < markers.length; i++) loop( i );
6015 }
6016
6017 var nextDocId = 0;
6018 var Doc = function(text, mode, firstLine, lineSep, direction) {
6019 if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
6020 if (firstLine == null) { firstLine = 0; }
6021
6022 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
6023 this.first = firstLine;
6024 this.scrollTop = this.scrollLeft = 0;
6025 this.cantEdit = false;
6026 this.cleanGeneration = 1;
6027 this.modeFrontier = this.highlightFrontier = firstLine;
6028 var start = Pos(firstLine, 0);
6029 this.sel = simpleSelection(start);
6030 this.history = new History(null);
6031 this.id = ++nextDocId;
6032 this.modeOption = mode;
6033 this.lineSep = lineSep;
6034 this.direction = (direction == "rtl") ? "rtl" : "ltr";
6035 this.extend = false;
6036
6037 if (typeof text == "string") { text = this.splitLines(text); }
6038 updateDoc(this, {from: start, to: start, text: text});
6039 setSelection(this, simpleSelection(start), sel_dontScroll);
6040 };
6041
6042 Doc.prototype = createObj(BranchChunk.prototype, {
6043 constructor: Doc,
6044 // Iterate over the document. Supports two forms -- with only one
6045 // argument, it calls that for each line in the document. With
6046 // three, it iterates over the range given by the first two (with
6047 // the second being non-inclusive).
6048 iter: function(from, to, op) {
6049 if (op) { this.iterN(from - this.first, to - from, op); }
6050 else { this.iterN(this.first, this.first + this.size, from); }
6051 },
6052
6053 // Non-public interface for adding and removing lines.
6054 insert: function(at, lines) {
6055 var height = 0;
6056 for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
6057 this.insertInner(at - this.first, lines, height);
6058 },
6059 remove: function(at, n) { this.removeInner(at - this.first, n); },
6060
6061 // From here, the methods are part of the public interface. Most
6062 // are also available from CodeMirror (editor) instances.
6063
6064 getValue: function(lineSep) {
6065 var lines = getLines(this, this.first, this.first + this.size);
6066 if (lineSep === false) { return lines }
6067 return lines.join(lineSep || this.lineSeparator())
6068 },
6069 setValue: docMethodOp(function(code) {
6070 var top = Pos(this.first, 0), last = this.first + this.size - 1;
6071 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6072 text: this.splitLines(code), origin: "setValue", full: true}, true);
6073 if (this.cm) { scrollToCoords(this.cm, 0, 0); }
6074 setSelection(this, simpleSelection(top), sel_dontScroll);
6075 }),
6076 replaceRange: function(code, from, to, origin) {
6077 from = clipPos(this, from);
6078 to = to ? clipPos(this, to) : from;
6079 replaceRange(this, code, from, to, origin);
6080 },
6081 getRange: function(from, to, lineSep) {
6082 var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6083 if (lineSep === false) { return lines }
6084 return lines.join(lineSep || this.lineSeparator())
6085 },
6086
6087 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6088
6089 getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6090 getLineNumber: function(line) {return lineNo(line)},
6091
6092 getLineHandleVisualStart: function(line) {
6093 if (typeof line == "number") { line = getLine(this, line); }
6094 return visualLine(line)
6095 },
6096
6097 lineCount: function() {return this.size},
6098 firstLine: function() {return this.first},
6099 lastLine: function() {return this.first + this.size - 1},
6100
6101 clipPos: function(pos) {return clipPos(this, pos)},
6102
6103 getCursor: function(start) {
6104 var range$$1 = this.sel.primary(), pos;
6105 if (start == null || start == "head") { pos = range$$1.head; }
6106 else if (start == "anchor") { pos = range$$1.anchor; }
6107 else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
6108 else { pos = range$$1.from(); }
6109 return pos
6110 },
6111 listSelections: function() { return this.sel.ranges },
6112 somethingSelected: function() {return this.sel.somethingSelected()},
6113
6114 setCursor: docMethodOp(function(line, ch, options) {
6115 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6116 }),
6117 setSelection: docMethodOp(function(anchor, head, options) {
6118 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6119 }),
6120 extendSelection: docMethodOp(function(head, other, options) {
6121 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6122 }),
6123 extendSelections: docMethodOp(function(heads, options) {
6124 extendSelections(this, clipPosArray(this, heads), options);
6125 }),
6126 extendSelectionsBy: docMethodOp(function(f, options) {
6127 var heads = map(this.sel.ranges, f);
6128 extendSelections(this, clipPosArray(this, heads), options);
6129 }),
6130 setSelections: docMethodOp(function(ranges, primary, options) {
6131 var this$1 = this;
6132
6133 if (!ranges.length) { return }
6134 var out = [];
6135 for (var i = 0; i < ranges.length; i++)
6136 { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
6137 clipPos(this$1, ranges[i].head)); }
6138 if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
6139 setSelection(this, normalizeSelection(out, primary), options);
6140 }),
6141 addSelection: docMethodOp(function(anchor, head, options) {
6142 var ranges = this.sel.ranges.slice(0);
6143 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6144 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
6145 }),
6146
6147 getSelection: function(lineSep) {
6148 var this$1 = this;
6149
6150 var ranges = this.sel.ranges, lines;
6151 for (var i = 0; i < ranges.length; i++) {
6152 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
6153 lines = lines ? lines.concat(sel) : sel;
6154 }
6155 if (lineSep === false) { return lines }
6156 else { return lines.join(lineSep || this.lineSeparator()) }
6157 },
6158 getSelections: function(lineSep) {
6159 var this$1 = this;
6160
6161 var parts = [], ranges = this.sel.ranges;
6162 for (var i = 0; i < ranges.length; i++) {
6163 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
6164 if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
6165 parts[i] = sel;
6166 }
6167 return parts
6168 },
6169 replaceSelection: function(code, collapse, origin) {
6170 var dup = [];
6171 for (var i = 0; i < this.sel.ranges.length; i++)
6172 { dup[i] = code; }
6173 this.replaceSelections(dup, collapse, origin || "+input");
6174 },
6175 replaceSelections: docMethodOp(function(code, collapse, origin) {
6176 var this$1 = this;
6177
6178 var changes = [], sel = this.sel;
6179 for (var i = 0; i < sel.ranges.length; i++) {
6180 var range$$1 = sel.ranges[i];
6181 changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
6182 }
6183 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6184 for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
6185 { makeChange(this$1, changes[i$1]); }
6186 if (newSel) { setSelectionReplaceHistory(this, newSel); }
6187 else if (this.cm) { ensureCursorVisible(this.cm); }
6188 }),
6189 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6190 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6191 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6192 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6193
6194 setExtending: function(val) {this.extend = val;},
6195 getExtending: function() {return this.extend},
6196
6197 historySize: function() {
6198 var hist = this.history, done = 0, undone = 0;
6199 for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
6200 for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
6201 return {undo: done, redo: undone}
6202 },
6203 clearHistory: function() {this.history = new History(this.history.maxGeneration);},
6204
6205 markClean: function() {
6206 this.cleanGeneration = this.changeGeneration(true);
6207 },
6208 changeGeneration: function(forceSplit) {
6209 if (forceSplit)
6210 { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
6211 return this.history.generation
6212 },
6213 isClean: function (gen) {
6214 return this.history.generation == (gen || this.cleanGeneration)
6215 },
6216
6217 getHistory: function() {
6218 return {done: copyHistoryArray(this.history.done),
6219 undone: copyHistoryArray(this.history.undone)}
6220 },
6221 setHistory: function(histData) {
6222 var hist = this.history = new History(this.history.maxGeneration);
6223 hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6224 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6225 },
6226
6227 setGutterMarker: docMethodOp(function(line, gutterID, value) {
6228 return changeLine(this, line, "gutter", function (line) {
6229 var markers = line.gutterMarkers || (line.gutterMarkers = {});
6230 markers[gutterID] = value;
6231 if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
6232 return true
6233 })
6234 }),
6235
6236 clearGutter: docMethodOp(function(gutterID) {
6237 var this$1 = this;
6238
6239 this.iter(function (line) {
6240 if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
6241 changeLine(this$1, line, "gutter", function () {
6242 line.gutterMarkers[gutterID] = null;
6243 if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
6244 return true
6245 });
6246 }
6247 });
6248 }),
6249
6250 lineInfo: function(line) {
6251 var n;
6252 if (typeof line == "number") {
6253 if (!isLine(this, line)) { return null }
6254 n = line;
6255 line = getLine(this, line);
6256 if (!line) { return null }
6257 } else {
6258 n = lineNo(line);
6259 if (n == null) { return null }
6260 }
6261 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
6262 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
6263 widgets: line.widgets}
6264 },
6265
6266 addLineClass: docMethodOp(function(handle, where, cls) {
6267 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6268 var prop = where == "text" ? "textClass"
6269 : where == "background" ? "bgClass"
6270 : where == "gutter" ? "gutterClass" : "wrapClass";
6271 if (!line[prop]) { line[prop] = cls; }
6272 else if (classTest(cls).test(line[prop])) { return false }
6273 else { line[prop] += " " + cls; }
6274 return true
6275 })
6276 }),
6277 removeLineClass: docMethodOp(function(handle, where, cls) {
6278 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6279 var prop = where == "text" ? "textClass"
6280 : where == "background" ? "bgClass"
6281 : where == "gutter" ? "gutterClass" : "wrapClass";
6282 var cur = line[prop];
6283 if (!cur) { return false }
6284 else if (cls == null) { line[prop] = null; }
6285 else {
6286 var found = cur.match(classTest(cls));
6287 if (!found) { return false }
6288 var end = found.index + found[0].length;
6289 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
6290 }
6291 return true
6292 })
6293 }),
6294
6295 addLineWidget: docMethodOp(function(handle, node, options) {
6296 return addLineWidget(this, handle, node, options)
6297 }),
6298 removeLineWidget: function(widget) { widget.clear(); },
6299
6300 markText: function(from, to, options) {
6301 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
6302 },
6303 setBookmark: function(pos, options) {
6304 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6305 insertLeft: options && options.insertLeft,
6306 clearWhenEmpty: false, shared: options && options.shared,
6307 handleMouseEvents: options && options.handleMouseEvents};
6308 pos = clipPos(this, pos);
6309 return markText(this, pos, pos, realOpts, "bookmark")
6310 },
6311 findMarksAt: function(pos) {
6312 pos = clipPos(this, pos);
6313 var markers = [], spans = getLine(this, pos.line).markedSpans;
6314 if (spans) { for (var i = 0; i < spans.length; ++i) {
6315 var span = spans[i];
6316 if ((span.from == null || span.from <= pos.ch) &&
6317 (span.to == null || span.to >= pos.ch))
6318 { markers.push(span.marker.parent || span.marker); }
6319 } }
6320 return markers
6321 },
6322 findMarks: function(from, to, filter) {
6323 from = clipPos(this, from); to = clipPos(this, to);
6324 var found = [], lineNo$$1 = from.line;
6325 this.iter(from.line, to.line + 1, function (line) {
6326 var spans = line.markedSpans;
6327 if (spans) { for (var i = 0; i < spans.length; i++) {
6328 var span = spans[i];
6329 if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
6330 span.from == null && lineNo$$1 != from.line ||
6331 span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
6332 (!filter || filter(span.marker)))
6333 { found.push(span.marker.parent || span.marker); }
6334 } }
6335 ++lineNo$$1;
6336 });
6337 return found
6338 },
6339 getAllMarks: function() {
6340 var markers = [];
6341 this.iter(function (line) {
6342 var sps = line.markedSpans;
6343 if (sps) { for (var i = 0; i < sps.length; ++i)
6344 { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
6345 });
6346 return markers
6347 },
6348
6349 posFromIndex: function(off) {
6350 var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
6351 this.iter(function (line) {
6352 var sz = line.text.length + sepSize;
6353 if (sz > off) { ch = off; return true }
6354 off -= sz;
6355 ++lineNo$$1;
6356 });
6357 return clipPos(this, Pos(lineNo$$1, ch))
6358 },
6359 indexFromPos: function (coords) {
6360 coords = clipPos(this, coords);
6361 var index = coords.ch;
6362 if (coords.line < this.first || coords.ch < 0) { return 0 }
6363 var sepSize = this.lineSeparator().length;
6364 this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
6365 index += line.text.length + sepSize;
6366 });
6367 return index
6368 },
6369
6370 copy: function(copyHistory) {
6371 var doc = new Doc(getLines(this, this.first, this.first + this.size),
6372 this.modeOption, this.first, this.lineSep, this.direction);
6373 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6374 doc.sel = this.sel;
6375 doc.extend = false;
6376 if (copyHistory) {
6377 doc.history.undoDepth = this.history.undoDepth;
6378 doc.setHistory(this.getHistory());
6379 }
6380 return doc
6381 },
6382
6383 linkedDoc: function(options) {
6384 if (!options) { options = {}; }
6385 var from = this.first, to = this.first + this.size;
6386 if (options.from != null && options.from > from) { from = options.from; }
6387 if (options.to != null && options.to < to) { to = options.to; }
6388 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
6389 if (options.sharedHist) { copy.history = this.history
6390 ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6391 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6392 copySharedMarkers(copy, findSharedMarkers(this));
6393 return copy
6394 },
6395 unlinkDoc: function(other) {
6396 var this$1 = this;
6397
6398 if (other instanceof CodeMirror$1) { other = other.doc; }
6399 if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
6400 var link = this$1.linked[i];
6401 if (link.doc != other) { continue }
6402 this$1.linked.splice(i, 1);
6403 other.unlinkDoc(this$1);
6404 detachSharedMarkers(findSharedMarkers(this$1));
6405 break
6406 } }
6407 // If the histories were shared, split them again
6408 if (other.history == this.history) {
6409 var splitIds = [other.id];
6410 linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
6411 other.history = new History(null);
6412 other.history.done = copyHistoryArray(this.history.done, splitIds);
6413 other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6414 }
6415 },
6416 iterLinkedDocs: function(f) {linkedDocs(this, f);},
6417
6418 getMode: function() {return this.mode},
6419 getEditor: function() {return this.cm},
6420
6421 splitLines: function(str) {
6422 if (this.lineSep) { return str.split(this.lineSep) }
6423 return splitLinesAuto(str)
6424 },
6425 lineSeparator: function() { return this.lineSep || "\n" },
6426
6427 setDirection: docMethodOp(function (dir) {
6428 if (dir != "rtl") { dir = "ltr"; }
6429 if (dir == this.direction) { return }
6430 this.direction = dir;
6431 this.iter(function (line) { return line.order = null; });
6432 if (this.cm) { directionChanged(this.cm); }
6433 })
6434 });
6435
6436 // Public alias.
6437 Doc.prototype.eachLine = Doc.prototype.iter;
6438
6439 // Kludge to work around strange IE behavior where it'll sometimes
6440 // re-fire a series of drag-related events right after the drop (#1551)
6441 var lastDrop = 0;
6442
6443 function onDrop(e) {
6444 var cm = this;
6445 clearDragCursor(cm);
6446 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
6447 { return }
6448 e_preventDefault(e);
6449 if (ie) { lastDrop = +new Date; }
6450 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
6451 if (!pos || cm.isReadOnly()) { return }
6452 // Might be a file drop, in which case we simply extract the text
6453 // and insert it.
6454 if (files && files.length && window.FileReader && window.File) {
6455 var n = files.length, text = Array(n), read = 0;
6456 var loadFile = function (file, i) {
6457 if (cm.options.allowDropFileTypes &&
6458 indexOf(cm.options.allowDropFileTypes, file.type) == -1)
6459 { return }
6460
6461 var reader = new FileReader;
6462 reader.onload = operation(cm, function () {
6463 var content = reader.result;
6464 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
6465 text[i] = content;
6466 if (++read == n) {
6467 pos = clipPos(cm.doc, pos);
6468 var change = {from: pos, to: pos,
6469 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
6470 origin: "paste"};
6471 makeChange(cm.doc, change);
6472 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
6473 }
6474 });
6475 reader.readAsText(file);
6476 };
6477 for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
6478 } else { // Normal drop
6479 // Don't do a replace if the drop happened inside of the selected text.
6480 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
6481 cm.state.draggingText(e);
6482 // Ensure the editor is re-focused
6483 setTimeout(function () { return cm.display.input.focus(); }, 20);
6484 return
6485 }
6486 try {
6487 var text$1 = e.dataTransfer.getData("Text");
6488 if (text$1) {
6489 var selected;
6490 if (cm.state.draggingText && !cm.state.draggingText.copy)
6491 { selected = cm.listSelections(); }
6492 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
6493 if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
6494 { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
6495 cm.replaceSelection(text$1, "around", "paste");
6496 cm.display.input.focus();
6497 }
6498 }
6499 catch(e){}
6500 }
6501 }
6502
6503 function onDragStart(cm, e) {
6504 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
6505 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
6506
6507 e.dataTransfer.setData("Text", cm.getSelection());
6508 e.dataTransfer.effectAllowed = "copyMove";
6509
6510 // Use dummy image instead of default browsers image.
6511 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
6512 if (e.dataTransfer.setDragImage && !safari) {
6513 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
6514 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
6515 if (presto) {
6516 img.width = img.height = 1;
6517 cm.display.wrapper.appendChild(img);
6518 // Force a relayout, or Opera won't use our image for some obscure reason
6519 img._top = img.offsetTop;
6520 }
6521 e.dataTransfer.setDragImage(img, 0, 0);
6522 if (presto) { img.parentNode.removeChild(img); }
6523 }
6524 }
6525
6526 function onDragOver(cm, e) {
6527 var pos = posFromMouse(cm, e);
6528 if (!pos) { return }
6529 var frag = document.createDocumentFragment();
6530 drawSelectionCursor(cm, pos, frag);
6531 if (!cm.display.dragCursor) {
6532 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
6533 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
6534 }
6535 removeChildrenAndAdd(cm.display.dragCursor, frag);
6536 }
6537
6538 function clearDragCursor(cm) {
6539 if (cm.display.dragCursor) {
6540 cm.display.lineSpace.removeChild(cm.display.dragCursor);
6541 cm.display.dragCursor = null;
6542 }
6543 }
6544
6545 // These must be handled carefully, because naively registering a
6546 // handler for each editor will cause the editors to never be
6547 // garbage collected.
6548
6549 function forEachCodeMirror(f) {
6550 if (!document.getElementsByClassName) { return }
6551 var byClass = document.getElementsByClassName("CodeMirror");
6552 for (var i = 0; i < byClass.length; i++) {
6553 var cm = byClass[i].CodeMirror;
6554 if (cm) { f(cm); }
6555 }
6556 }
6557
6558 var globalsRegistered = false;
6559 function ensureGlobalHandlers() {
6560 if (globalsRegistered) { return }
6561 registerGlobalHandlers();
6562 globalsRegistered = true;
6563 }
6564 function registerGlobalHandlers() {
6565 // When the window resizes, we need to refresh active editors.
6566 var resizeTimer;
6567 on(window, "resize", function () {
6568 if (resizeTimer == null) { resizeTimer = setTimeout(function () {
6569 resizeTimer = null;
6570 forEachCodeMirror(onResize);
6571 }, 100); }
6572 });
6573 // When the window loses focus, we want to show the editor as blurred
6574 on(window, "blur", function () { return forEachCodeMirror(onBlur); });
6575 }
6576 // Called when the window resizes
6577 function onResize(cm) {
6578 var d = cm.display;
6579 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
6580 { return }
6581 // Might be a text scaling operation, clear size caches.
6582 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
6583 d.scrollbarsClipped = false;
6584 cm.setSize();
6585 }
6586
6587 var keyNames = {
6588 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
6589 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
6590 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
6591 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
6592 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
6593 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
6594 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
6595 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
6596 };
6597
6598 // Number keys
6599 for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
6600 // Alphabetic keys
6601 for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
6602 // Function keys
6603 for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
6604
6605 var keyMap = {};
6606
6607 keyMap.basic = {
6608 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
6609 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
6610 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
6611 "Tab": "defaultTab", "Shift-Tab": "indentAuto",
6612 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
6613 "Esc": "singleSelection"
6614 };
6615 // Note that the save and find-related commands aren't defined by
6616 // default. User code or addons can define them. Unknown commands
6617 // are simply ignored.
6618 keyMap.pcDefault = {
6619 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
6620 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
6621 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
6622 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
6623 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
6624 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
6625 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
6626 fallthrough: "basic"
6627 };
6628 // Very basic readline/emacs-style bindings, which are standard on Mac.
6629 keyMap.emacsy = {
6630 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
6631 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
6632 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
6633 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
6634 "Ctrl-O": "openLine"
6635 };
6636 keyMap.macDefault = {
6637 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
6638 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
6639 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
6640 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
6641 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
6642 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
6643 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
6644 fallthrough: ["basic", "emacsy"]
6645 };
6646 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
6647
6648 // KEYMAP DISPATCH
6649
6650 function normalizeKeyName(name) {
6651 var parts = name.split(/-(?!$)/);
6652 name = parts[parts.length - 1];
6653 var alt, ctrl, shift, cmd;
6654 for (var i = 0; i < parts.length - 1; i++) {
6655 var mod = parts[i];
6656 if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
6657 else if (/^a(lt)?$/i.test(mod)) { alt = true; }
6658 else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
6659 else if (/^s(hift)?$/i.test(mod)) { shift = true; }
6660 else { throw new Error("Unrecognized modifier name: " + mod) }
6661 }
6662 if (alt) { name = "Alt-" + name; }
6663 if (ctrl) { name = "Ctrl-" + name; }
6664 if (cmd) { name = "Cmd-" + name; }
6665 if (shift) { name = "Shift-" + name; }
6666 return name
6667 }
6668
6669 // This is a kludge to keep keymaps mostly working as raw objects
6670 // (backwards compatibility) while at the same time support features
6671 // like normalization and multi-stroke key bindings. It compiles a
6672 // new normalized keymap, and then updates the old object to reflect
6673 // this.
6674 function normalizeKeyMap(keymap) {
6675 var copy = {};
6676 for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
6677 var value = keymap[keyname];
6678 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
6679 if (value == "...") { delete keymap[keyname]; continue }
6680
6681 var keys = map(keyname.split(" "), normalizeKeyName);
6682 for (var i = 0; i < keys.length; i++) {
6683 var val = (void 0), name = (void 0);
6684 if (i == keys.length - 1) {
6685 name = keys.join(" ");
6686 val = value;
6687 } else {
6688 name = keys.slice(0, i + 1).join(" ");
6689 val = "...";
6690 }
6691 var prev = copy[name];
6692 if (!prev) { copy[name] = val; }
6693 else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
6694 }
6695 delete keymap[keyname];
6696 } }
6697 for (var prop in copy) { keymap[prop] = copy[prop]; }
6698 return keymap
6699 }
6700
6701 function lookupKey(key, map$$1, handle, context) {
6702 map$$1 = getKeyMap(map$$1);
6703 var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
6704 if (found === false) { return "nothing" }
6705 if (found === "...") { return "multi" }
6706 if (found != null && handle(found)) { return "handled" }
6707
6708 if (map$$1.fallthrough) {
6709 if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
6710 { return lookupKey(key, map$$1.fallthrough, handle, context) }
6711 for (var i = 0; i < map$$1.fallthrough.length; i++) {
6712 var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
6713 if (result) { return result }
6714 }
6715 }
6716 }
6717
6718 // Modifier key presses don't count as 'real' key presses for the
6719 // purpose of keymap fallthrough.
6720 function isModifierKey(value) {
6721 var name = typeof value == "string" ? value : keyNames[value.keyCode];
6722 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
6723 }
6724
6725 function addModifierNames(name, event, noShift) {
6726 var base = name;
6727 if (event.altKey && base != "Alt") { name = "Alt-" + name; }
6728 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
6729 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
6730 if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
6731 return name
6732 }
6733
6734 // Look up the name of a key as indicated by an event object.
6735 function keyName(event, noShift) {
6736 if (presto && event.keyCode == 34 && event["char"]) { return false }
6737 var name = keyNames[event.keyCode];
6738 if (name == null || event.altGraphKey) { return false }
6739 return addModifierNames(name, event, noShift)
6740 }
6741
6742 function getKeyMap(val) {
6743 return typeof val == "string" ? keyMap[val] : val
6744 }
6745
6746 // Helper for deleting text near the selection(s), used to implement
6747 // backspace, delete, and similar functionality.
6748 function deleteNearSelection(cm, compute) {
6749 var ranges = cm.doc.sel.ranges, kill = [];
6750 // Build up a set of ranges to kill first, merging overlapping
6751 // ranges.
6752 for (var i = 0; i < ranges.length; i++) {
6753 var toKill = compute(ranges[i]);
6754 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
6755 var replaced = kill.pop();
6756 if (cmp(replaced.from, toKill.from) < 0) {
6757 toKill.from = replaced.from;
6758 break
6759 }
6760 }
6761 kill.push(toKill);
6762 }
6763 // Next, remove those actual ranges.
6764 runInOp(cm, function () {
6765 for (var i = kill.length - 1; i >= 0; i--)
6766 { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
6767 ensureCursorVisible(cm);
6768 });
6769 }
6770
6771 function moveCharLogically(line, ch, dir) {
6772 var target = skipExtendingChars(line.text, ch + dir, dir);
6773 return target < 0 || target > line.text.length ? null : target
6774 }
6775
6776 function moveLogically(line, start, dir) {
6777 var ch = moveCharLogically(line, start.ch, dir);
6778 return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
6779 }
6780
6781 function endOfLine(visually, cm, lineObj, lineNo, dir) {
6782 if (visually) {
6783 var order = getOrder(lineObj, cm.doc.direction);
6784 if (order) {
6785 var part = dir < 0 ? lst(order) : order[0];
6786 var moveInStorageOrder = (dir < 0) == (part.level == 1);
6787 var sticky = moveInStorageOrder ? "after" : "before";
6788 var ch;
6789 // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
6790 // it could be that the last bidi part is not on the last visual line,
6791 // since visual lines contain content order-consecutive chunks.
6792 // Thus, in rtl, we are looking for the first (content-order) character
6793 // in the rtl chunk that is on the last line (that is, the same line
6794 // as the last (content-order) character).
6795 if (part.level > 0 || cm.doc.direction == "rtl") {
6796 var prep = prepareMeasureForLine(cm, lineObj);
6797 ch = dir < 0 ? lineObj.text.length - 1 : 0;
6798 var targetTop = measureCharPrepared(cm, prep, ch).top;
6799 ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
6800 if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
6801 } else { ch = dir < 0 ? part.to : part.from; }
6802 return new Pos(lineNo, ch, sticky)
6803 }
6804 }
6805 return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6806 }
6807
6808 function moveVisually(cm, line, start, dir) {
6809 var bidi = getOrder(line, cm.doc.direction);
6810 if (!bidi) { return moveLogically(line, start, dir) }
6811 if (start.ch >= line.text.length) {
6812 start.ch = line.text.length;
6813 start.sticky = "before";
6814 } else if (start.ch <= 0) {
6815 start.ch = 0;
6816 start.sticky = "after";
6817 }
6818 var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
6819 if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
6820 // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
6821 // nothing interesting happens.
6822 return moveLogically(line, start, dir)
6823 }
6824
6825 var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
6826 var prep;
6827 var getWrappedLineExtent = function (ch) {
6828 if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
6829 prep = prep || prepareMeasureForLine(cm, line);
6830 return wrappedLineExtentChar(cm, line, prep, ch)
6831 };
6832 var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
6833
6834 if (cm.doc.direction == "rtl" || part.level == 1) {
6835 var moveInStorageOrder = (part.level == 1) == (dir < 0);
6836 var ch = mv(start, moveInStorageOrder ? 1 : -1);
6837 if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
6838 // Case 2: We move within an rtl part or in an rtl editor on the same visual line
6839 var sticky = moveInStorageOrder ? "before" : "after";
6840 return new Pos(start.line, ch, sticky)
6841 }
6842 }
6843
6844 // Case 3: Could not move within this bidi part in this visual line, so leave
6845 // the current bidi part
6846
6847 var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
6848 var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
6849 ? new Pos(start.line, mv(ch, 1), "before")
6850 : new Pos(start.line, ch, "after"); };
6851
6852 for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
6853 var part = bidi[partPos];
6854 var moveInStorageOrder = (dir > 0) == (part.level != 1);
6855 var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
6856 if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
6857 ch = moveInStorageOrder ? part.from : mv(part.to, -1);
6858 if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
6859 }
6860 };
6861
6862 // Case 3a: Look for other bidi parts on the same visual line
6863 var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
6864 if (res) { return res }
6865
6866 // Case 3b: Look for other bidi parts on the next visual line
6867 var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
6868 if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
6869 res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
6870 if (res) { return res }
6871 }
6872
6873 // Case 4: Nowhere to move
6874 return null
6875 }
6876
6877 // Commands are parameter-less actions that can be performed on an
6878 // editor, mostly used for keybindings.
6879 var commands = {
6880 selectAll: selectAll,
6881 singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
6882 killLine: function (cm) { return deleteNearSelection(cm, function (range) {
6883 if (range.empty()) {
6884 var len = getLine(cm.doc, range.head.line).text.length;
6885 if (range.head.ch == len && range.head.line < cm.lastLine())
6886 { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
6887 else
6888 { return {from: range.head, to: Pos(range.head.line, len)} }
6889 } else {
6890 return {from: range.from(), to: range.to()}
6891 }
6892 }); },
6893 deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6894 from: Pos(range.from().line, 0),
6895 to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
6896 }); }); },
6897 delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6898 from: Pos(range.from().line, 0), to: range.from()
6899 }); }); },
6900 delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
6901 var top = cm.charCoords(range.head, "div").top + 5;
6902 var leftPos = cm.coordsChar({left: 0, top: top}, "div");
6903 return {from: leftPos, to: range.from()}
6904 }); },
6905 delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
6906 var top = cm.charCoords(range.head, "div").top + 5;
6907 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
6908 return {from: range.from(), to: rightPos }
6909 }); },
6910 undo: function (cm) { return cm.undo(); },
6911 redo: function (cm) { return cm.redo(); },
6912 undoSelection: function (cm) { return cm.undoSelection(); },
6913 redoSelection: function (cm) { return cm.redoSelection(); },
6914 goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
6915 goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
6916 goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
6917 {origin: "+move", bias: 1}
6918 ); },
6919 goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
6920 {origin: "+move", bias: 1}
6921 ); },
6922 goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
6923 {origin: "+move", bias: -1}
6924 ); },
6925 goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
6926 var top = cm.cursorCoords(range.head, "div").top + 5;
6927 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
6928 }, sel_move); },
6929 goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
6930 var top = cm.cursorCoords(range.head, "div").top + 5;
6931 return cm.coordsChar({left: 0, top: top}, "div")
6932 }, sel_move); },
6933 goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
6934 var top = cm.cursorCoords(range.head, "div").top + 5;
6935 var pos = cm.coordsChar({left: 0, top: top}, "div");
6936 if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
6937 return pos
6938 }, sel_move); },
6939 goLineUp: function (cm) { return cm.moveV(-1, "line"); },
6940 goLineDown: function (cm) { return cm.moveV(1, "line"); },
6941 goPageUp: function (cm) { return cm.moveV(-1, "page"); },
6942 goPageDown: function (cm) { return cm.moveV(1, "page"); },
6943 goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
6944 goCharRight: function (cm) { return cm.moveH(1, "char"); },
6945 goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
6946 goColumnRight: function (cm) { return cm.moveH(1, "column"); },
6947 goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
6948 goGroupRight: function (cm) { return cm.moveH(1, "group"); },
6949 goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
6950 goWordRight: function (cm) { return cm.moveH(1, "word"); },
6951 delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
6952 delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
6953 delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
6954 delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
6955 delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
6956 delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
6957 indentAuto: function (cm) { return cm.indentSelection("smart"); },
6958 indentMore: function (cm) { return cm.indentSelection("add"); },
6959 indentLess: function (cm) { return cm.indentSelection("subtract"); },
6960 insertTab: function (cm) { return cm.replaceSelection("\t"); },
6961 insertSoftTab: function (cm) {
6962 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
6963 for (var i = 0; i < ranges.length; i++) {
6964 var pos = ranges[i].from();
6965 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
6966 spaces.push(spaceStr(tabSize - col % tabSize));
6967 }
6968 cm.replaceSelections(spaces);
6969 },
6970 defaultTab: function (cm) {
6971 if (cm.somethingSelected()) { cm.indentSelection("add"); }
6972 else { cm.execCommand("insertTab"); }
6973 },
6974 // Swap the two chars left and right of each selection's head.
6975 // Move cursor behind the two swapped characters afterwards.
6976 //
6977 // Doesn't consider line feeds a character.
6978 // Doesn't scan more than one line above to find a character.
6979 // Doesn't do anything on an empty line.
6980 // Doesn't do anything with non-empty selections.
6981 transposeChars: function (cm) { return runInOp(cm, function () {
6982 var ranges = cm.listSelections(), newSel = [];
6983 for (var i = 0; i < ranges.length; i++) {
6984 if (!ranges[i].empty()) { continue }
6985 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
6986 if (line) {
6987 if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
6988 if (cur.ch > 0) {
6989 cur = new Pos(cur.line, cur.ch + 1);
6990 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
6991 Pos(cur.line, cur.ch - 2), cur, "+transpose");
6992 } else if (cur.line > cm.doc.first) {
6993 var prev = getLine(cm.doc, cur.line - 1).text;
6994 if (prev) {
6995 cur = new Pos(cur.line, 1);
6996 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
6997 prev.charAt(prev.length - 1),
6998 Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
6999 }
7000 }
7001 }
7002 newSel.push(new Range(cur, cur));
7003 }
7004 cm.setSelections(newSel);
7005 }); },
7006 newlineAndIndent: function (cm) { return runInOp(cm, function () {
7007 var sels = cm.listSelections();
7008 for (var i = sels.length - 1; i >= 0; i--)
7009 { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
7010 sels = cm.listSelections();
7011 for (var i$1 = 0; i$1 < sels.length; i$1++)
7012 { cm.indentLine(sels[i$1].from().line, null, true); }
7013 ensureCursorVisible(cm);
7014 }); },
7015 openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
7016 toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
7017 };
7018
7019
7020 function lineStart(cm, lineN) {
7021 var line = getLine(cm.doc, lineN);
7022 var visual = visualLine(line);
7023 if (visual != line) { lineN = lineNo(visual); }
7024 return endOfLine(true, cm, visual, lineN, 1)
7025 }
7026 function lineEnd(cm, lineN) {
7027 var line = getLine(cm.doc, lineN);
7028 var visual = visualLineEnd(line);
7029 if (visual != line) { lineN = lineNo(visual); }
7030 return endOfLine(true, cm, line, lineN, -1)
7031 }
7032 function lineStartSmart(cm, pos) {
7033 var start = lineStart(cm, pos.line);
7034 var line = getLine(cm.doc, start.line);
7035 var order = getOrder(line, cm.doc.direction);
7036 if (!order || order[0].level == 0) {
7037 var firstNonWS = Math.max(0, line.text.search(/\S/));
7038 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
7039 return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
7040 }
7041 return start
7042 }
7043
7044 // Run a handler that was bound to a key.
7045 function doHandleBinding(cm, bound, dropShift) {
7046 if (typeof bound == "string") {
7047 bound = commands[bound];
7048 if (!bound) { return false }
7049 }
7050 // Ensure previous input has been read, so that the handler sees a
7051 // consistent view of the document
7052 cm.display.input.ensurePolled();
7053 var prevShift = cm.display.shift, done = false;
7054 try {
7055 if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7056 if (dropShift) { cm.display.shift = false; }
7057 done = bound(cm) != Pass;
7058 } finally {
7059 cm.display.shift = prevShift;
7060 cm.state.suppressEdits = false;
7061 }
7062 return done
7063 }
7064
7065 function lookupKeyForEditor(cm, name, handle) {
7066 for (var i = 0; i < cm.state.keyMaps.length; i++) {
7067 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
7068 if (result) { return result }
7069 }
7070 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7071 || lookupKey(name, cm.options.keyMap, handle, cm)
7072 }
7073
7074 // Note that, despite the name, this function is also used to check
7075 // for bound mouse clicks.
7076
7077 var stopSeq = new Delayed;
7078
7079 function dispatchKey(cm, name, e, handle) {
7080 var seq = cm.state.keySeq;
7081 if (seq) {
7082 if (isModifierKey(name)) { return "handled" }
7083 if (/\'$/.test(name))
7084 { cm.state.keySeq = null; }
7085 else
7086 { stopSeq.set(50, function () {
7087 if (cm.state.keySeq == seq) {
7088 cm.state.keySeq = null;
7089 cm.display.input.reset();
7090 }
7091 }); }
7092 if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
7093 }
7094 return dispatchKeyInner(cm, name, e, handle)
7095 }
7096
7097 function dispatchKeyInner(cm, name, e, handle) {
7098 var result = lookupKeyForEditor(cm, name, handle);
7099
7100 if (result == "multi")
7101 { cm.state.keySeq = name; }
7102 if (result == "handled")
7103 { signalLater(cm, "keyHandled", cm, name, e); }
7104
7105 if (result == "handled" || result == "multi") {
7106 e_preventDefault(e);
7107 restartBlink(cm);
7108 }
7109
7110 return !!result
7111 }
7112
7113 // Handle a key from the keydown event.
7114 function handleKeyBinding(cm, e) {
7115 var name = keyName(e, true);
7116 if (!name) { return false }
7117
7118 if (e.shiftKey && !cm.state.keySeq) {
7119 // First try to resolve full name (including 'Shift-'). Failing
7120 // that, see if there is a cursor-motion command (starting with
7121 // 'go') bound to the keyname without 'Shift-'.
7122 return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
7123 || dispatchKey(cm, name, e, function (b) {
7124 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
7125 { return doHandleBinding(cm, b) }
7126 })
7127 } else {
7128 return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
7129 }
7130 }
7131
7132 // Handle a key from the keypress event
7133 function handleCharBinding(cm, e, ch) {
7134 return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
7135 }
7136
7137 var lastStoppedKey = null;
7138 function onKeyDown(e) {
7139 var cm = this;
7140 cm.curOp.focus = activeElt();
7141 if (signalDOMEvent(cm, e)) { return }
7142 // IE does strange things with escape.
7143 if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
7144 var code = e.keyCode;
7145 cm.display.shift = code == 16 || e.shiftKey;
7146 var handled = handleKeyBinding(cm, e);
7147 if (presto) {
7148 lastStoppedKey = handled ? code : null;
7149 // Opera has no cut event... we try to at least catch the key combo
7150 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
7151 { cm.replaceSelection("", null, "cut"); }
7152 }
7153
7154 // Turn mouse into crosshair when Alt is held on Mac.
7155 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
7156 { showCrossHair(cm); }
7157 }
7158
7159 function showCrossHair(cm) {
7160 var lineDiv = cm.display.lineDiv;
7161 addClass(lineDiv, "CodeMirror-crosshair");
7162
7163 function up(e) {
7164 if (e.keyCode == 18 || !e.altKey) {
7165 rmClass(lineDiv, "CodeMirror-crosshair");
7166 off(document, "keyup", up);
7167 off(document, "mouseover", up);
7168 }
7169 }
7170 on(document, "keyup", up);
7171 on(document, "mouseover", up);
7172 }
7173
7174 function onKeyUp(e) {
7175 if (e.keyCode == 16) { this.doc.sel.shift = false; }
7176 signalDOMEvent(this, e);
7177 }
7178
7179 function onKeyPress(e) {
7180 var cm = this;
7181 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
7182 var keyCode = e.keyCode, charCode = e.charCode;
7183 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
7184 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
7185 var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
7186 // Some browsers fire keypress events for backspace
7187 if (ch == "\x08") { return }
7188 if (handleCharBinding(cm, e, ch)) { return }
7189 cm.display.input.onKeyPress(e);
7190 }
7191
7192 var DOUBLECLICK_DELAY = 400;
7193
7194 var PastClick = function(time, pos, button) {
7195 this.time = time;
7196 this.pos = pos;
7197 this.button = button;
7198 };
7199
7200 PastClick.prototype.compare = function (time, pos, button) {
7201 return this.time + DOUBLECLICK_DELAY > time &&
7202 cmp(pos, this.pos) == 0 && button == this.button
7203 };
7204
7205 var lastClick;
7206 var lastDoubleClick;
7207 function clickRepeat(pos, button) {
7208 var now = +new Date;
7209 if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
7210 lastClick = lastDoubleClick = null;
7211 return "triple"
7212 } else if (lastClick && lastClick.compare(now, pos, button)) {
7213 lastDoubleClick = new PastClick(now, pos, button);
7214 lastClick = null;
7215 return "double"
7216 } else {
7217 lastClick = new PastClick(now, pos, button);
7218 lastDoubleClick = null;
7219 return "single"
7220 }
7221 }
7222
7223 // A mouse down can be a single click, double click, triple click,
7224 // start of selection drag, start of text drag, new cursor
7225 // (ctrl-click), rectangle drag (alt-drag), or xwin
7226 // middle-click-paste. Or it might be a click on something we should
7227 // not interfere with, such as a scrollbar or widget.
7228 function onMouseDown(e) {
7229 var cm = this, display = cm.display;
7230 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
7231 display.input.ensurePolled();
7232 display.shift = e.shiftKey;
7233
7234 if (eventInWidget(display, e)) {
7235 if (!webkit) {
7236 // Briefly turn off draggability, to allow widgets to do
7237 // normal dragging things.
7238 display.scroller.draggable = false;
7239 setTimeout(function () { return display.scroller.draggable = true; }, 100);
7240 }
7241 return
7242 }
7243 if (clickInGutter(cm, e)) { return }
7244 var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
7245 window.focus();
7246
7247 // #3261: make sure, that we're not starting a second selection
7248 if (button == 1 && cm.state.selectingText)
7249 { cm.state.selectingText(e); }
7250
7251 if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
7252
7253 if (button == 1) {
7254 if (pos) { leftButtonDown(cm, pos, repeat, e); }
7255 else if (e_target(e) == display.scroller) { e_preventDefault(e); }
7256 } else if (button == 2) {
7257 if (pos) { extendSelection(cm.doc, pos); }
7258 setTimeout(function () { return display.input.focus(); }, 20);
7259 } else if (button == 3) {
7260 if (captureRightClick) { onContextMenu(cm, e); }
7261 else { delayBlurEvent(cm); }
7262 }
7263 }
7264
7265 function handleMappedButton(cm, button, pos, repeat, event) {
7266 var name = "Click";
7267 if (repeat == "double") { name = "Double" + name; }
7268 else if (repeat == "triple") { name = "Triple" + name; }
7269 name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
7270
7271 return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
7272 if (typeof bound == "string") { bound = commands[bound]; }
7273 if (!bound) { return false }
7274 var done = false;
7275 try {
7276 if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7277 done = bound(cm, pos) != Pass;
7278 } finally {
7279 cm.state.suppressEdits = false;
7280 }
7281 return done
7282 })
7283 }
7284
7285 function configureMouse(cm, repeat, event) {
7286 var option = cm.getOption("configureMouse");
7287 var value = option ? option(cm, repeat, event) : {};
7288 if (value.unit == null) {
7289 var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
7290 value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
7291 }
7292 if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
7293 if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
7294 if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
7295 return value
7296 }
7297
7298 function leftButtonDown(cm, pos, repeat, event) {
7299 if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
7300 else { cm.curOp.focus = activeElt(); }
7301
7302 var behavior = configureMouse(cm, repeat, event);
7303
7304 var sel = cm.doc.sel, contained;
7305 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
7306 repeat == "single" && (contained = sel.contains(pos)) > -1 &&
7307 (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
7308 (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
7309 { leftButtonStartDrag(cm, event, pos, behavior); }
7310 else
7311 { leftButtonSelect(cm, event, pos, behavior); }
7312 }
7313
7314 // Start a text drag. When it ends, see if any dragging actually
7315 // happen, and treat as a click if it didn't.
7316 function leftButtonStartDrag(cm, event, pos, behavior) {
7317 var display = cm.display, moved = false;
7318 var dragEnd = operation(cm, function (e) {
7319 if (webkit) { display.scroller.draggable = false; }
7320 cm.state.draggingText = false;
7321 off(document, "mouseup", dragEnd);
7322 off(document, "mousemove", mouseMove);
7323 off(display.scroller, "dragstart", dragStart);
7324 off(display.scroller, "drop", dragEnd);
7325 if (!moved) {
7326 e_preventDefault(e);
7327 if (!behavior.addNew)
7328 { extendSelection(cm.doc, pos, null, null, behavior.extend); }
7329 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
7330 if (webkit || ie && ie_version == 9)
7331 { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
7332 else
7333 { display.input.focus(); }
7334 }
7335 });
7336 var mouseMove = function(e2) {
7337 moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
7338 };
7339 var dragStart = function () { return moved = true; };
7340 // Let the drag handler handle this.
7341 if (webkit) { display.scroller.draggable = true; }
7342 cm.state.draggingText = dragEnd;
7343 dragEnd.copy = !behavior.moveOnDrag;
7344 // IE's approach to draggable
7345 if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
7346 on(document, "mouseup", dragEnd);
7347 on(document, "mousemove", mouseMove);
7348 on(display.scroller, "dragstart", dragStart);
7349 on(display.scroller, "drop", dragEnd);
7350
7351 delayBlurEvent(cm);
7352 setTimeout(function () { return display.input.focus(); }, 20);
7353 }
7354
7355 function rangeForUnit(cm, pos, unit) {
7356 if (unit == "char") { return new Range(pos, pos) }
7357 if (unit == "word") { return cm.findWordAt(pos) }
7358 if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
7359 var result = unit(cm, pos);
7360 return new Range(result.from, result.to)
7361 }
7362
7363 // Normal selection, as opposed to text dragging.
7364 function leftButtonSelect(cm, event, start, behavior) {
7365 var display = cm.display, doc = cm.doc;
7366 e_preventDefault(event);
7367
7368 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
7369 if (behavior.addNew && !behavior.extend) {
7370 ourIndex = doc.sel.contains(start);
7371 if (ourIndex > -1)
7372 { ourRange = ranges[ourIndex]; }
7373 else
7374 { ourRange = new Range(start, start); }
7375 } else {
7376 ourRange = doc.sel.primary();
7377 ourIndex = doc.sel.primIndex;
7378 }
7379
7380 if (behavior.unit == "rectangle") {
7381 if (!behavior.addNew) { ourRange = new Range(start, start); }
7382 start = posFromMouse(cm, event, true, true);
7383 ourIndex = -1;
7384 } else {
7385 var range$$1 = rangeForUnit(cm, start, behavior.unit);
7386 if (behavior.extend)
7387 { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
7388 else
7389 { ourRange = range$$1; }
7390 }
7391
7392 if (!behavior.addNew) {
7393 ourIndex = 0;
7394 setSelection(doc, new Selection([ourRange], 0), sel_mouse);
7395 startSel = doc.sel;
7396 } else if (ourIndex == -1) {
7397 ourIndex = ranges.length;
7398 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
7399 {scroll: false, origin: "*mouse"});
7400 } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
7401 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
7402 {scroll: false, origin: "*mouse"});
7403 startSel = doc.sel;
7404 } else {
7405 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
7406 }
7407
7408 var lastPos = start;
7409 function extendTo(pos) {
7410 if (cmp(lastPos, pos) == 0) { return }
7411 lastPos = pos;
7412
7413 if (behavior.unit == "rectangle") {
7414 var ranges = [], tabSize = cm.options.tabSize;
7415 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
7416 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
7417 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
7418 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
7419 line <= end; line++) {
7420 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
7421 if (left == right)
7422 { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
7423 else if (text.length > leftPos)
7424 { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
7425 }
7426 if (!ranges.length) { ranges.push(new Range(start, start)); }
7427 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
7428 {origin: "*mouse", scroll: false});
7429 cm.scrollIntoView(pos);
7430 } else {
7431 var oldRange = ourRange;
7432 var range$$1 = rangeForUnit(cm, pos, behavior.unit);
7433 var anchor = oldRange.anchor, head;
7434 if (cmp(range$$1.anchor, anchor) > 0) {
7435 head = range$$1.head;
7436 anchor = minPos(oldRange.from(), range$$1.anchor);
7437 } else {
7438 head = range$$1.anchor;
7439 anchor = maxPos(oldRange.to(), range$$1.head);
7440 }
7441 var ranges$1 = startSel.ranges.slice(0);
7442 ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
7443 setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
7444 }
7445 }
7446
7447 var editorSize = display.wrapper.getBoundingClientRect();
7448 // Used to ensure timeout re-tries don't fire when another extend
7449 // happened in the meantime (clearTimeout isn't reliable -- at
7450 // least on Chrome, the timeouts still happen even when cleared,
7451 // if the clear happens after their scheduled firing time).
7452 var counter = 0;
7453
7454 function extend(e) {
7455 var curCount = ++counter;
7456 var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
7457 if (!cur) { return }
7458 if (cmp(cur, lastPos) != 0) {
7459 cm.curOp.focus = activeElt();
7460 extendTo(cur);
7461 var visible = visibleLines(display, doc);
7462 if (cur.line >= visible.to || cur.line < visible.from)
7463 { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
7464 } else {
7465 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
7466 if (outside) { setTimeout(operation(cm, function () {
7467 if (counter != curCount) { return }
7468 display.scroller.scrollTop += outside;
7469 extend(e);
7470 }), 50); }
7471 }
7472 }
7473
7474 function done(e) {
7475 cm.state.selectingText = false;
7476 counter = Infinity;
7477 e_preventDefault(e);
7478 display.input.focus();
7479 off(document, "mousemove", move);
7480 off(document, "mouseup", up);
7481 doc.history.lastSelOrigin = null;
7482 }
7483
7484 var move = operation(cm, function (e) {
7485 if (!e_button(e)) { done(e); }
7486 else { extend(e); }
7487 });
7488 var up = operation(cm, done);
7489 cm.state.selectingText = up;
7490 on(document, "mousemove", move);
7491 on(document, "mouseup", up);
7492 }
7493
7494 // Used when mouse-selecting to adjust the anchor to the proper side
7495 // of a bidi jump depending on the visual position of the head.
7496 function bidiSimplify(cm, range$$1) {
7497 var anchor = range$$1.anchor;
7498 var head = range$$1.head;
7499 var anchorLine = getLine(cm.doc, anchor.line);
7500 if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
7501 var order = getOrder(anchorLine);
7502 if (!order) { return range$$1 }
7503 var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
7504 if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
7505 var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
7506 if (boundary == 0 || boundary == order.length) { return range$$1 }
7507
7508 // Compute the relative visual position of the head compared to the
7509 // anchor (<0 is to the left, >0 to the right)
7510 var leftSide;
7511 if (head.line != anchor.line) {
7512 leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
7513 } else {
7514 var headIndex = getBidiPartAt(order, head.ch, head.sticky);
7515 var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
7516 if (headIndex == boundary - 1 || headIndex == boundary)
7517 { leftSide = dir < 0; }
7518 else
7519 { leftSide = dir > 0; }
7520 }
7521
7522 var usePart = order[boundary + (leftSide ? -1 : 0)];
7523 var from = leftSide == (usePart.level == 1);
7524 var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
7525 return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
7526 }
7527
7528
7529 // Determines whether an event happened in the gutter, and fires the
7530 // handlers for the corresponding event.
7531 function gutterEvent(cm, e, type, prevent) {
7532 var mX, mY;
7533 if (e.touches) {
7534 mX = e.touches[0].clientX;
7535 mY = e.touches[0].clientY;
7536 } else {
7537 try { mX = e.clientX; mY = e.clientY; }
7538 catch(e) { return false }
7539 }
7540 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
7541 if (prevent) { e_preventDefault(e); }
7542
7543 var display = cm.display;
7544 var lineBox = display.lineDiv.getBoundingClientRect();
7545
7546 if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
7547 mY -= lineBox.top - display.viewOffset;
7548
7549 for (var i = 0; i < cm.options.gutters.length; ++i) {
7550 var g = display.gutters.childNodes[i];
7551 if (g && g.getBoundingClientRect().right >= mX) {
7552 var line = lineAtHeight(cm.doc, mY);
7553 var gutter = cm.options.gutters[i];
7554 signal(cm, type, cm, line, gutter, e);
7555 return e_defaultPrevented(e)
7556 }
7557 }
7558 }
7559
7560 function clickInGutter(cm, e) {
7561 return gutterEvent(cm, e, "gutterClick", true)
7562 }
7563
7564 // CONTEXT MENU HANDLING
7565
7566 // To make the context menu work, we need to briefly unhide the
7567 // textarea (making it as unobtrusive as possible) to let the
7568 // right-click take effect on it.
7569 function onContextMenu(cm, e) {
7570 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
7571 if (signalDOMEvent(cm, e, "contextmenu")) { return }
7572 cm.display.input.onContextMenu(e);
7573 }
7574
7575 function contextMenuInGutter(cm, e) {
7576 if (!hasHandler(cm, "gutterContextMenu")) { return false }
7577 return gutterEvent(cm, e, "gutterContextMenu", false)
7578 }
7579
7580 function themeChanged(cm) {
7581 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
7582 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
7583 clearCaches(cm);
7584 }
7585
7586 var Init = {toString: function(){return "CodeMirror.Init"}};
7587
7588 var defaults = {};
7589 var optionHandlers = {};
7590
7591 function defineOptions(CodeMirror) {
7592 var optionHandlers = CodeMirror.optionHandlers;
7593
7594 function option(name, deflt, handle, notOnInit) {
7595 CodeMirror.defaults[name] = deflt;
7596 if (handle) { optionHandlers[name] =
7597 notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
7598 }
7599
7600 CodeMirror.defineOption = option;
7601
7602 // Passed to option handlers when there is no old value.
7603 CodeMirror.Init = Init;
7604
7605 // These two are, on init, called from the constructor because they
7606 // have to be initialized before the editor can start at all.
7607 option("value", "", function (cm, val) { return cm.setValue(val); }, true);
7608 option("mode", null, function (cm, val) {
7609 cm.doc.modeOption = val;
7610 loadMode(cm);
7611 }, true);
7612
7613 option("indentUnit", 2, loadMode, true);
7614 option("indentWithTabs", false);
7615 option("smartIndent", true);
7616 option("tabSize", 4, function (cm) {
7617 resetModeState(cm);
7618 clearCaches(cm);
7619 regChange(cm);
7620 }, true);
7621 option("lineSeparator", null, function (cm, val) {
7622 cm.doc.lineSep = val;
7623 if (!val) { return }
7624 var newBreaks = [], lineNo = cm.doc.first;
7625 cm.doc.iter(function (line) {
7626 for (var pos = 0;;) {
7627 var found = line.text.indexOf(val, pos);
7628 if (found == -1) { break }
7629 pos = found + val.length;
7630 newBreaks.push(Pos(lineNo, found));
7631 }
7632 lineNo++;
7633 });
7634 for (var i = newBreaks.length - 1; i >= 0; i--)
7635 { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
7636 });
7637 option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
7638 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
7639 if (old != Init) { cm.refresh(); }
7640 });
7641 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
7642 option("electricChars", true);
7643 option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
7644 throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
7645 }, true);
7646 option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
7647 option("rtlMoveVisually", !windows);
7648 option("wholeLineUpdateBefore", true);
7649
7650 option("theme", "default", function (cm) {
7651 themeChanged(cm);
7652 guttersChanged(cm);
7653 }, true);
7654 option("keyMap", "default", function (cm, val, old) {
7655 var next = getKeyMap(val);
7656 var prev = old != Init && getKeyMap(old);
7657 if (prev && prev.detach) { prev.detach(cm, next); }
7658 if (next.attach) { next.attach(cm, prev || null); }
7659 });
7660 option("extraKeys", null);
7661 option("configureMouse", null);
7662
7663 option("lineWrapping", false, wrappingChanged, true);
7664 option("gutters", [], function (cm) {
7665 setGuttersForLineNumbers(cm.options);
7666 guttersChanged(cm);
7667 }, true);
7668 option("fixedGutter", true, function (cm, val) {
7669 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
7670 cm.refresh();
7671 }, true);
7672 option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
7673 option("scrollbarStyle", "native", function (cm) {
7674 initScrollbars(cm);
7675 updateScrollbars(cm);
7676 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
7677 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
7678 }, true);
7679 option("lineNumbers", false, function (cm) {
7680 setGuttersForLineNumbers(cm.options);
7681 guttersChanged(cm);
7682 }, true);
7683 option("firstLineNumber", 1, guttersChanged, true);
7684 option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
7685 option("showCursorWhenSelecting", false, updateSelection, true);
7686
7687 option("resetSelectionOnContextMenu", true);
7688 option("lineWiseCopyCut", true);
7689 option("pasteLinesPerSelection", true);
7690
7691 option("readOnly", false, function (cm, val) {
7692 if (val == "nocursor") {
7693 onBlur(cm);
7694 cm.display.input.blur();
7695 }
7696 cm.display.input.readOnlyChanged(val);
7697 });
7698 option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
7699 option("dragDrop", true, dragDropChanged);
7700 option("allowDropFileTypes", null);
7701
7702 option("cursorBlinkRate", 530);
7703 option("cursorScrollMargin", 0);
7704 option("cursorHeight", 1, updateSelection, true);
7705 option("singleCursorHeightPerLine", true, updateSelection, true);
7706 option("workTime", 100);
7707 option("workDelay", 100);
7708 option("flattenSpans", true, resetModeState, true);
7709 option("addModeClass", false, resetModeState, true);
7710 option("pollInterval", 100);
7711 option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
7712 option("historyEventDelay", 1250);
7713 option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
7714 option("maxHighlightLength", 10000, resetModeState, true);
7715 option("moveInputWithCursor", true, function (cm, val) {
7716 if (!val) { cm.display.input.resetPosition(); }
7717 });
7718
7719 option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
7720 option("autofocus", null);
7721 option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
7722 }
7723
7724 function guttersChanged(cm) {
7725 updateGutters(cm);
7726 regChange(cm);
7727 alignHorizontally(cm);
7728 }
7729
7730 function dragDropChanged(cm, value, old) {
7731 var wasOn = old && old != Init;
7732 if (!value != !wasOn) {
7733 var funcs = cm.display.dragFunctions;
7734 var toggle = value ? on : off;
7735 toggle(cm.display.scroller, "dragstart", funcs.start);
7736 toggle(cm.display.scroller, "dragenter", funcs.enter);
7737 toggle(cm.display.scroller, "dragover", funcs.over);
7738 toggle(cm.display.scroller, "dragleave", funcs.leave);
7739 toggle(cm.display.scroller, "drop", funcs.drop);
7740 }
7741 }
7742
7743 function wrappingChanged(cm) {
7744 if (cm.options.lineWrapping) {
7745 addClass(cm.display.wrapper, "CodeMirror-wrap");
7746 cm.display.sizer.style.minWidth = "";
7747 cm.display.sizerWidth = null;
7748 } else {
7749 rmClass(cm.display.wrapper, "CodeMirror-wrap");
7750 findMaxLine(cm);
7751 }
7752 estimateLineHeights(cm);
7753 regChange(cm);
7754 clearCaches(cm);
7755 setTimeout(function () { return updateScrollbars(cm); }, 100);
7756 }
7757
7758 // A CodeMirror instance represents an editor. This is the object
7759 // that user code is usually dealing with.
7760
7761 function CodeMirror$1(place, options) {
7762 var this$1 = this;
7763
7764 if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
7765
7766 this.options = options = options ? copyObj(options) : {};
7767 // Determine effective options based on given values and defaults.
7768 copyObj(defaults, options, false);
7769 setGuttersForLineNumbers(options);
7770
7771 var doc = options.value;
7772 if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
7773 this.doc = doc;
7774
7775 var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
7776 var display = this.display = new Display(place, doc, input);
7777 display.wrapper.CodeMirror = this;
7778 updateGutters(this);
7779 themeChanged(this);
7780 if (options.lineWrapping)
7781 { this.display.wrapper.className += " CodeMirror-wrap"; }
7782 initScrollbars(this);
7783
7784 this.state = {
7785 keyMaps: [], // stores maps added by addKeyMap
7786 overlays: [], // highlighting overlays, as added by addOverlay
7787 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
7788 overwrite: false,
7789 delayingBlurEvent: false,
7790 focused: false,
7791 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
7792 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
7793 selectingText: false,
7794 draggingText: false,
7795 highlight: new Delayed(), // stores highlight worker timeout
7796 keySeq: null, // Unfinished key sequence
7797 specialChars: null
7798 };
7799
7800 if (options.autofocus && !mobile) { display.input.focus(); }
7801
7802 // Override magic textarea content restore that IE sometimes does
7803 // on our hidden textarea on reload
7804 if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
7805
7806 registerEventHandlers(this);
7807 ensureGlobalHandlers();
7808
7809 startOperation(this);
7810 this.curOp.forceUpdate = true;
7811 attachDoc(this, doc);
7812
7813 if ((options.autofocus && !mobile) || this.hasFocus())
7814 { setTimeout(bind(onFocus, this), 20); }
7815 else
7816 { onBlur(this); }
7817
7818 for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
7819 { optionHandlers[opt](this$1, options[opt], Init); } }
7820 maybeUpdateLineNumberWidth(this);
7821 if (options.finishInit) { options.finishInit(this); }
7822 for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
7823 endOperation(this);
7824 // Suppress optimizelegibility in Webkit, since it breaks text
7825 // measuring on line wrapping boundaries.
7826 if (webkit && options.lineWrapping &&
7827 getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
7828 { display.lineDiv.style.textRendering = "auto"; }
7829 }
7830
7831 // The default configuration options.
7832 CodeMirror$1.defaults = defaults;
7833 // Functions to run when options are changed.
7834 CodeMirror$1.optionHandlers = optionHandlers;
7835
7836 // Attach the necessary event handlers when initializing the editor
7837 function registerEventHandlers(cm) {
7838 var d = cm.display;
7839 on(d.scroller, "mousedown", operation(cm, onMouseDown));
7840 // Older IE's will not fire a second mousedown for a double click
7841 if (ie && ie_version < 11)
7842 { on(d.scroller, "dblclick", operation(cm, function (e) {
7843 if (signalDOMEvent(cm, e)) { return }
7844 var pos = posFromMouse(cm, e);
7845 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
7846 e_preventDefault(e);
7847 var word = cm.findWordAt(pos);
7848 extendSelection(cm.doc, word.anchor, word.head);
7849 })); }
7850 else
7851 { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
7852 // Some browsers fire contextmenu *after* opening the menu, at
7853 // which point we can't mess with it anymore. Context menu is
7854 // handled in onMouseDown for these browsers.
7855 if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
7856
7857 // Used to suppress mouse event handling when a touch happens
7858 var touchFinished, prevTouch = {end: 0};
7859 function finishTouch() {
7860 if (d.activeTouch) {
7861 touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
7862 prevTouch = d.activeTouch;
7863 prevTouch.end = +new Date;
7864 }
7865 }
7866 function isMouseLikeTouchEvent(e) {
7867 if (e.touches.length != 1) { return false }
7868 var touch = e.touches[0];
7869 return touch.radiusX <= 1 && touch.radiusY <= 1
7870 }
7871 function farAway(touch, other) {
7872 if (other.left == null) { return true }
7873 var dx = other.left - touch.left, dy = other.top - touch.top;
7874 return dx * dx + dy * dy > 20 * 20
7875 }
7876 on(d.scroller, "touchstart", function (e) {
7877 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
7878 d.input.ensurePolled();
7879 clearTimeout(touchFinished);
7880 var now = +new Date;
7881 d.activeTouch = {start: now, moved: false,
7882 prev: now - prevTouch.end <= 300 ? prevTouch : null};
7883 if (e.touches.length == 1) {
7884 d.activeTouch.left = e.touches[0].pageX;
7885 d.activeTouch.top = e.touches[0].pageY;
7886 }
7887 }
7888 });
7889 on(d.scroller, "touchmove", function () {
7890 if (d.activeTouch) { d.activeTouch.moved = true; }
7891 });
7892 on(d.scroller, "touchend", function (e) {
7893 var touch = d.activeTouch;
7894 if (touch && !eventInWidget(d, e) && touch.left != null &&
7895 !touch.moved && new Date - touch.start < 300) {
7896 var pos = cm.coordsChar(d.activeTouch, "page"), range;
7897 if (!touch.prev || farAway(touch, touch.prev)) // Single tap
7898 { range = new Range(pos, pos); }
7899 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
7900 { range = cm.findWordAt(pos); }
7901 else // Triple tap
7902 { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
7903 cm.setSelection(range.anchor, range.head);
7904 cm.focus();
7905 e_preventDefault(e);
7906 }
7907 finishTouch();
7908 });
7909 on(d.scroller, "touchcancel", finishTouch);
7910
7911 // Sync scrolling between fake scrollbars and real scrollable
7912 // area, ensure viewport is updated when scrolling.
7913 on(d.scroller, "scroll", function () {
7914 if (d.scroller.clientHeight) {
7915 updateScrollTop(cm, d.scroller.scrollTop);
7916 setScrollLeft(cm, d.scroller.scrollLeft, true);
7917 signal(cm, "scroll", cm);
7918 }
7919 });
7920
7921 // Listen to wheel events in order to try and update the viewport on time.
7922 on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
7923 on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
7924
7925 // Prevent wrapper from ever scrolling
7926 on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
7927
7928 d.dragFunctions = {
7929 enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
7930 over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
7931 start: function (e) { return onDragStart(cm, e); },
7932 drop: operation(cm, onDrop),
7933 leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
7934 };
7935
7936 var inp = d.input.getField();
7937 on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
7938 on(inp, "keydown", operation(cm, onKeyDown));
7939 on(inp, "keypress", operation(cm, onKeyPress));
7940 on(inp, "focus", function (e) { return onFocus(cm, e); });
7941 on(inp, "blur", function (e) { return onBlur(cm, e); });
7942 }
7943
7944 var initHooks = [];
7945 CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
7946
7947 // Indent the given line. The how parameter can be "smart",
7948 // "add"/null, "subtract", or "prev". When aggressive is false
7949 // (typically set to true for forced single-line indents), empty
7950 // lines are not indented, and places where the mode returns Pass
7951 // are left alone.
7952 function indentLine(cm, n, how, aggressive) {
7953 var doc = cm.doc, state;
7954 if (how == null) { how = "add"; }
7955 if (how == "smart") {
7956 // Fall back to "prev" when the mode doesn't have an indentation
7957 // method.
7958 if (!doc.mode.indent) { how = "prev"; }
7959 else { state = getContextBefore(cm, n).state; }
7960 }
7961
7962 var tabSize = cm.options.tabSize;
7963 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
7964 if (line.stateAfter) { line.stateAfter = null; }
7965 var curSpaceString = line.text.match(/^\s*/)[0], indentation;
7966 if (!aggressive && !/\S/.test(line.text)) {
7967 indentation = 0;
7968 how = "not";
7969 } else if (how == "smart") {
7970 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
7971 if (indentation == Pass || indentation > 150) {
7972 if (!aggressive) { return }
7973 how = "prev";
7974 }
7975 }
7976 if (how == "prev") {
7977 if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
7978 else { indentation = 0; }
7979 } else if (how == "add") {
7980 indentation = curSpace + cm.options.indentUnit;
7981 } else if (how == "subtract") {
7982 indentation = curSpace - cm.options.indentUnit;
7983 } else if (typeof how == "number") {
7984 indentation = curSpace + how;
7985 }
7986 indentation = Math.max(0, indentation);
7987
7988 var indentString = "", pos = 0;
7989 if (cm.options.indentWithTabs)
7990 { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
7991 if (pos < indentation) { indentString += spaceStr(indentation - pos); }
7992
7993 if (indentString != curSpaceString) {
7994 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
7995 line.stateAfter = null;
7996 return true
7997 } else {
7998 // Ensure that, if the cursor was in the whitespace at the start
7999 // of the line, it is moved to the end of that space.
8000 for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
8001 var range = doc.sel.ranges[i$1];
8002 if (range.head.line == n && range.head.ch < curSpaceString.length) {
8003 var pos$1 = Pos(n, curSpaceString.length);
8004 replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
8005 break
8006 }
8007 }
8008 }
8009 }
8010
8011 // This will be set to a {lineWise: bool, text: [string]} object, so
8012 // that, when pasting, we know what kind of selections the copied
8013 // text was made out of.
8014 var lastCopied = null;
8015
8016 function setLastCopied(newLastCopied) {
8017 lastCopied = newLastCopied;
8018 }
8019
8020 function applyTextInput(cm, inserted, deleted, sel, origin) {
8021 var doc = cm.doc;
8022 cm.display.shift = false;
8023 if (!sel) { sel = doc.sel; }
8024
8025 var paste = cm.state.pasteIncoming || origin == "paste";
8026 var textLines = splitLinesAuto(inserted), multiPaste = null;
8027 // When pasing N lines into N selections, insert one line per selection
8028 if (paste && sel.ranges.length > 1) {
8029 if (lastCopied && lastCopied.text.join("\n") == inserted) {
8030 if (sel.ranges.length % lastCopied.text.length == 0) {
8031 multiPaste = [];
8032 for (var i = 0; i < lastCopied.text.length; i++)
8033 { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
8034 }
8035 } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
8036 multiPaste = map(textLines, function (l) { return [l]; });
8037 }
8038 }
8039
8040 var updateInput;
8041 // Normal behavior is to insert the new text into every selection
8042 for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
8043 var range$$1 = sel.ranges[i$1];
8044 var from = range$$1.from(), to = range$$1.to();
8045 if (range$$1.empty()) {
8046 if (deleted && deleted > 0) // Handle deletion
8047 { from = Pos(from.line, from.ch - deleted); }
8048 else if (cm.state.overwrite && !paste) // Handle overwrite
8049 { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
8050 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
8051 { from = to = Pos(from.line, 0); }
8052 }
8053 updateInput = cm.curOp.updateInput;
8054 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
8055 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
8056 makeChange(cm.doc, changeEvent);
8057 signalLater(cm, "inputRead", cm, changeEvent);
8058 }
8059 if (inserted && !paste)
8060 { triggerElectric(cm, inserted); }
8061
8062 ensureCursorVisible(cm);
8063 cm.curOp.updateInput = updateInput;
8064 cm.curOp.typing = true;
8065 cm.state.pasteIncoming = cm.state.cutIncoming = false;
8066 }
8067
8068 function handlePaste(e, cm) {
8069 var pasted = e.clipboardData && e.clipboardData.getData("Text");
8070 if (pasted) {
8071 e.preventDefault();
8072 if (!cm.isReadOnly() && !cm.options.disableInput)
8073 { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
8074 return true
8075 }
8076 }
8077
8078 function triggerElectric(cm, inserted) {
8079 // When an 'electric' character is inserted, immediately trigger a reindent
8080 if (!cm.options.electricChars || !cm.options.smartIndent) { return }
8081 var sel = cm.doc.sel;
8082
8083 for (var i = sel.ranges.length - 1; i >= 0; i--) {
8084 var range$$1 = sel.ranges[i];
8085 if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
8086 var mode = cm.getModeAt(range$$1.head);
8087 var indented = false;
8088 if (mode.electricChars) {
8089 for (var j = 0; j < mode.electricChars.length; j++)
8090 { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
8091 indented = indentLine(cm, range$$1.head.line, "smart");
8092 break
8093 } }
8094 } else if (mode.electricInput) {
8095 if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
8096 { indented = indentLine(cm, range$$1.head.line, "smart"); }
8097 }
8098 if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
8099 }
8100 }
8101
8102 function copyableRanges(cm) {
8103 var text = [], ranges = [];
8104 for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
8105 var line = cm.doc.sel.ranges[i].head.line;
8106 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
8107 ranges.push(lineRange);
8108 text.push(cm.getRange(lineRange.anchor, lineRange.head));
8109 }
8110 return {text: text, ranges: ranges}
8111 }
8112
8113 function disableBrowserMagic(field, spellcheck) {
8114 field.setAttribute("autocorrect", "off");
8115 field.setAttribute("autocapitalize", "off");
8116 field.setAttribute("spellcheck", !!spellcheck);
8117 }
8118
8119 function hiddenTextarea() {
8120 var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
8121 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
8122 // The textarea is kept positioned near the cursor to prevent the
8123 // fact that it'll be scrolled into view on input from scrolling
8124 // our fake cursor out of view. On webkit, when wrap=off, paste is
8125 // very slow. So make the area wide instead.
8126 if (webkit) { te.style.width = "1000px"; }
8127 else { te.setAttribute("wrap", "off"); }
8128 // If border: 0; -- iOS fails to open keyboard (issue #1287)
8129 if (ios) { te.style.border = "1px solid black"; }
8130 disableBrowserMagic(te);
8131 return div
8132 }
8133
8134 // The publicly visible API. Note that methodOp(f) means
8135 // 'wrap f in an operation, performed on its `this` parameter'.
8136
8137 // This is not the complete set of editor methods. Most of the
8138 // methods defined on the Doc type are also injected into
8139 // CodeMirror.prototype, for backwards compatibility and
8140 // convenience.
8141
8142 var addEditorMethods = function(CodeMirror) {
8143 var optionHandlers = CodeMirror.optionHandlers;
8144
8145 var helpers = CodeMirror.helpers = {};
8146
8147 CodeMirror.prototype = {
8148 constructor: CodeMirror,
8149 focus: function(){window.focus(); this.display.input.focus();},
8150
8151 setOption: function(option, value) {
8152 var options = this.options, old = options[option];
8153 if (options[option] == value && option != "mode") { return }
8154 options[option] = value;
8155 if (optionHandlers.hasOwnProperty(option))
8156 { operation(this, optionHandlers[option])(this, value, old); }
8157 signal(this, "optionChange", this, option);
8158 },
8159
8160 getOption: function(option) {return this.options[option]},
8161 getDoc: function() {return this.doc},
8162
8163 addKeyMap: function(map$$1, bottom) {
8164 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
8165 },
8166 removeKeyMap: function(map$$1) {
8167 var maps = this.state.keyMaps;
8168 for (var i = 0; i < maps.length; ++i)
8169 { if (maps[i] == map$$1 || maps[i].name == map$$1) {
8170 maps.splice(i, 1);
8171 return true
8172 } }
8173 },
8174
8175 addOverlay: methodOp(function(spec, options) {
8176 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
8177 if (mode.startState) { throw new Error("Overlays may not be stateful.") }
8178 insertSorted(this.state.overlays,
8179 {mode: mode, modeSpec: spec, opaque: options && options.opaque,
8180 priority: (options && options.priority) || 0},
8181 function (overlay) { return overlay.priority; });
8182 this.state.modeGen++;
8183 regChange(this);
8184 }),
8185 removeOverlay: methodOp(function(spec) {
8186 var this$1 = this;
8187
8188 var overlays = this.state.overlays;
8189 for (var i = 0; i < overlays.length; ++i) {
8190 var cur = overlays[i].modeSpec;
8191 if (cur == spec || typeof spec == "string" && cur.name == spec) {
8192 overlays.splice(i, 1);
8193 this$1.state.modeGen++;
8194 regChange(this$1);
8195 return
8196 }
8197 }
8198 }),
8199
8200 indentLine: methodOp(function(n, dir, aggressive) {
8201 if (typeof dir != "string" && typeof dir != "number") {
8202 if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
8203 else { dir = dir ? "add" : "subtract"; }
8204 }
8205 if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
8206 }),
8207 indentSelection: methodOp(function(how) {
8208 var this$1 = this;
8209
8210 var ranges = this.doc.sel.ranges, end = -1;
8211 for (var i = 0; i < ranges.length; i++) {
8212 var range$$1 = ranges[i];
8213 if (!range$$1.empty()) {
8214 var from = range$$1.from(), to = range$$1.to();
8215 var start = Math.max(end, from.line);
8216 end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
8217 for (var j = start; j < end; ++j)
8218 { indentLine(this$1, j, how); }
8219 var newRanges = this$1.doc.sel.ranges;
8220 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
8221 { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
8222 } else if (range$$1.head.line > end) {
8223 indentLine(this$1, range$$1.head.line, how, true);
8224 end = range$$1.head.line;
8225 if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
8226 }
8227 }
8228 }),
8229
8230 // Fetch the parser token for a given character. Useful for hacks
8231 // that want to inspect the mode state (say, for completion).
8232 getTokenAt: function(pos, precise) {
8233 return takeToken(this, pos, precise)
8234 },
8235
8236 getLineTokens: function(line, precise) {
8237 return takeToken(this, Pos(line), precise, true)
8238 },
8239
8240 getTokenTypeAt: function(pos) {
8241 pos = clipPos(this.doc, pos);
8242 var styles = getLineStyles(this, getLine(this.doc, pos.line));
8243 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
8244 var type;
8245 if (ch == 0) { type = styles[2]; }
8246 else { for (;;) {
8247 var mid = (before + after) >> 1;
8248 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
8249 else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
8250 else { type = styles[mid * 2 + 2]; break }
8251 } }
8252 var cut = type ? type.indexOf("overlay ") : -1;
8253 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
8254 },
8255
8256 getModeAt: function(pos) {
8257 var mode = this.doc.mode;
8258 if (!mode.innerMode) { return mode }
8259 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
8260 },
8261
8262 getHelper: function(pos, type) {
8263 return this.getHelpers(pos, type)[0]
8264 },
8265
8266 getHelpers: function(pos, type) {
8267 var this$1 = this;
8268
8269 var found = [];
8270 if (!helpers.hasOwnProperty(type)) { return found }
8271 var help = helpers[type], mode = this.getModeAt(pos);
8272 if (typeof mode[type] == "string") {
8273 if (help[mode[type]]) { found.push(help[mode[type]]); }
8274 } else if (mode[type]) {
8275 for (var i = 0; i < mode[type].length; i++) {
8276 var val = help[mode[type][i]];
8277 if (val) { found.push(val); }
8278 }
8279 } else if (mode.helperType && help[mode.helperType]) {
8280 found.push(help[mode.helperType]);
8281 } else if (help[mode.name]) {
8282 found.push(help[mode.name]);
8283 }
8284 for (var i$1 = 0; i$1 < help._global.length; i$1++) {
8285 var cur = help._global[i$1];
8286 if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
8287 { found.push(cur.val); }
8288 }
8289 return found
8290 },
8291
8292 getStateAfter: function(line, precise) {
8293 var doc = this.doc;
8294 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
8295 return getContextBefore(this, line + 1, precise).state
8296 },
8297
8298 cursorCoords: function(start, mode) {
8299 var pos, range$$1 = this.doc.sel.primary();
8300 if (start == null) { pos = range$$1.head; }
8301 else if (typeof start == "object") { pos = clipPos(this.doc, start); }
8302 else { pos = start ? range$$1.from() : range$$1.to(); }
8303 return cursorCoords(this, pos, mode || "page")
8304 },
8305
8306 charCoords: function(pos, mode) {
8307 return charCoords(this, clipPos(this.doc, pos), mode || "page")
8308 },
8309
8310 coordsChar: function(coords, mode) {
8311 coords = fromCoordSystem(this, coords, mode || "page");
8312 return coordsChar(this, coords.left, coords.top)
8313 },
8314
8315 lineAtHeight: function(height, mode) {
8316 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
8317 return lineAtHeight(this.doc, height + this.display.viewOffset)
8318 },
8319 heightAtLine: function(line, mode, includeWidgets) {
8320 var end = false, lineObj;
8321 if (typeof line == "number") {
8322 var last = this.doc.first + this.doc.size - 1;
8323 if (line < this.doc.first) { line = this.doc.first; }
8324 else if (line > last) { line = last; end = true; }
8325 lineObj = getLine(this.doc, line);
8326 } else {
8327 lineObj = line;
8328 }
8329 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
8330 (end ? this.doc.height - heightAtLine(lineObj) : 0)
8331 },
8332
8333 defaultTextHeight: function() { return textHeight(this.display) },
8334 defaultCharWidth: function() { return charWidth(this.display) },
8335
8336 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8337
8338 addWidget: function(pos, node, scroll, vert, horiz) {
8339 var display = this.display;
8340 pos = cursorCoords(this, clipPos(this.doc, pos));
8341 var top = pos.bottom, left = pos.left;
8342 node.style.position = "absolute";
8343 node.setAttribute("cm-ignore-events", "true");
8344 this.display.input.setUneditable(node);
8345 display.sizer.appendChild(node);
8346 if (vert == "over") {
8347 top = pos.top;
8348 } else if (vert == "above" || vert == "near") {
8349 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
8350 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
8351 // Default to positioning above (if specified and possible); otherwise default to positioning below
8352 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
8353 { top = pos.top - node.offsetHeight; }
8354 else if (pos.bottom + node.offsetHeight <= vspace)
8355 { top = pos.bottom; }
8356 if (left + node.offsetWidth > hspace)
8357 { left = hspace - node.offsetWidth; }
8358 }
8359 node.style.top = top + "px";
8360 node.style.left = node.style.right = "";
8361 if (horiz == "right") {
8362 left = display.sizer.clientWidth - node.offsetWidth;
8363 node.style.right = "0px";
8364 } else {
8365 if (horiz == "left") { left = 0; }
8366 else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
8367 node.style.left = left + "px";
8368 }
8369 if (scroll)
8370 { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
8371 },
8372
8373 triggerOnKeyDown: methodOp(onKeyDown),
8374 triggerOnKeyPress: methodOp(onKeyPress),
8375 triggerOnKeyUp: onKeyUp,
8376 triggerOnMouseDown: methodOp(onMouseDown),
8377
8378 execCommand: function(cmd) {
8379 if (commands.hasOwnProperty(cmd))
8380 { return commands[cmd].call(null, this) }
8381 },
8382
8383 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8384
8385 findPosH: function(from, amount, unit, visually) {
8386 var this$1 = this;
8387
8388 var dir = 1;
8389 if (amount < 0) { dir = -1; amount = -amount; }
8390 var cur = clipPos(this.doc, from);
8391 for (var i = 0; i < amount; ++i) {
8392 cur = findPosH(this$1.doc, cur, dir, unit, visually);
8393 if (cur.hitSide) { break }
8394 }
8395 return cur
8396 },
8397
8398 moveH: methodOp(function(dir, unit) {
8399 var this$1 = this;
8400
8401 this.extendSelectionsBy(function (range$$1) {
8402 if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
8403 { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
8404 else
8405 { return dir < 0 ? range$$1.from() : range$$1.to() }
8406 }, sel_move);
8407 }),
8408
8409 deleteH: methodOp(function(dir, unit) {
8410 var sel = this.doc.sel, doc = this.doc;
8411 if (sel.somethingSelected())
8412 { doc.replaceSelection("", null, "+delete"); }
8413 else
8414 { deleteNearSelection(this, function (range$$1) {
8415 var other = findPosH(doc, range$$1.head, dir, unit, false);
8416 return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
8417 }); }
8418 }),
8419
8420 findPosV: function(from, amount, unit, goalColumn) {
8421 var this$1 = this;
8422
8423 var dir = 1, x = goalColumn;
8424 if (amount < 0) { dir = -1; amount = -amount; }
8425 var cur = clipPos(this.doc, from);
8426 for (var i = 0; i < amount; ++i) {
8427 var coords = cursorCoords(this$1, cur, "div");
8428 if (x == null) { x = coords.left; }
8429 else { coords.left = x; }
8430 cur = findPosV(this$1, coords, dir, unit);
8431 if (cur.hitSide) { break }
8432 }
8433 return cur
8434 },
8435
8436 moveV: methodOp(function(dir, unit) {
8437 var this$1 = this;
8438
8439 var doc = this.doc, goals = [];
8440 var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
8441 doc.extendSelectionsBy(function (range$$1) {
8442 if (collapse)
8443 { return dir < 0 ? range$$1.from() : range$$1.to() }
8444 var headPos = cursorCoords(this$1, range$$1.head, "div");
8445 if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
8446 goals.push(headPos.left);
8447 var pos = findPosV(this$1, headPos, dir, unit);
8448 if (unit == "page" && range$$1 == doc.sel.primary())
8449 { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
8450 return pos
8451 }, sel_move);
8452 if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
8453 { doc.sel.ranges[i].goalColumn = goals[i]; } }
8454 }),
8455
8456 // Find the word at the given position (as returned by coordsChar).
8457 findWordAt: function(pos) {
8458 var doc = this.doc, line = getLine(doc, pos.line).text;
8459 var start = pos.ch, end = pos.ch;
8460 if (line) {
8461 var helper = this.getHelper(pos, "wordChars");
8462 if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
8463 var startChar = line.charAt(start);
8464 var check = isWordChar(startChar, helper)
8465 ? function (ch) { return isWordChar(ch, helper); }
8466 : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
8467 : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
8468 while (start > 0 && check(line.charAt(start - 1))) { --start; }
8469 while (end < line.length && check(line.charAt(end))) { ++end; }
8470 }
8471 return new Range(Pos(pos.line, start), Pos(pos.line, end))
8472 },
8473
8474 toggleOverwrite: function(value) {
8475 if (value != null && value == this.state.overwrite) { return }
8476 if (this.state.overwrite = !this.state.overwrite)
8477 { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8478 else
8479 { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8480
8481 signal(this, "overwriteToggle", this, this.state.overwrite);
8482 },
8483 hasFocus: function() { return this.display.input.getField() == activeElt() },
8484 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
8485
8486 scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
8487 getScrollInfo: function() {
8488 var scroller = this.display.scroller;
8489 return {left: scroller.scrollLeft, top: scroller.scrollTop,
8490 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
8491 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
8492 clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
8493 },
8494
8495 scrollIntoView: methodOp(function(range$$1, margin) {
8496 if (range$$1 == null) {
8497 range$$1 = {from: this.doc.sel.primary().head, to: null};
8498 if (margin == null) { margin = this.options.cursorScrollMargin; }
8499 } else if (typeof range$$1 == "number") {
8500 range$$1 = {from: Pos(range$$1, 0), to: null};
8501 } else if (range$$1.from == null) {
8502 range$$1 = {from: range$$1, to: null};
8503 }
8504 if (!range$$1.to) { range$$1.to = range$$1.from; }
8505 range$$1.margin = margin || 0;
8506
8507 if (range$$1.from.line != null) {
8508 scrollToRange(this, range$$1);
8509 } else {
8510 scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
8511 }
8512 }),
8513
8514 setSize: methodOp(function(width, height) {
8515 var this$1 = this;
8516
8517 var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
8518 if (width != null) { this.display.wrapper.style.width = interpret(width); }
8519 if (height != null) { this.display.wrapper.style.height = interpret(height); }
8520 if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
8521 var lineNo$$1 = this.display.viewFrom;
8522 this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
8523 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
8524 { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
8525 ++lineNo$$1;
8526 });
8527 this.curOp.forceUpdate = true;
8528 signal(this, "refresh", this);
8529 }),
8530
8531 operation: function(f){return runInOp(this, f)},
8532 startOperation: function(){return startOperation(this)},
8533 endOperation: function(){return endOperation(this)},
8534
8535 refresh: methodOp(function() {
8536 var oldHeight = this.display.cachedTextHeight;
8537 regChange(this);
8538 this.curOp.forceUpdate = true;
8539 clearCaches(this);
8540 scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
8541 updateGutterSpace(this);
8542 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
8543 { estimateLineHeights(this); }
8544 signal(this, "refresh", this);
8545 }),
8546
8547 swapDoc: methodOp(function(doc) {
8548 var old = this.doc;
8549 old.cm = null;
8550 attachDoc(this, doc);
8551 clearCaches(this);
8552 this.display.input.reset();
8553 scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
8554 this.curOp.forceScroll = true;
8555 signalLater(this, "swapDoc", this, old);
8556 return old
8557 }),
8558
8559 getInputField: function(){return this.display.input.getField()},
8560 getWrapperElement: function(){return this.display.wrapper},
8561 getScrollerElement: function(){return this.display.scroller},
8562 getGutterElement: function(){return this.display.gutters}
8563 };
8564 eventMixin(CodeMirror);
8565
8566 CodeMirror.registerHelper = function(type, name, value) {
8567 if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
8568 helpers[type][name] = value;
8569 };
8570 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
8571 CodeMirror.registerHelper(type, name, value);
8572 helpers[type]._global.push({pred: predicate, val: value});
8573 };
8574 };
8575
8576 // Used for horizontal relative motion. Dir is -1 or 1 (left or
8577 // right), unit can be "char", "column" (like char, but doesn't
8578 // cross line boundaries), "word" (across next word), or "group" (to
8579 // the start of next group of word or non-word-non-whitespace
8580 // chars). The visually param controls whether, in right-to-left
8581 // text, direction 1 means to move towards the next index in the
8582 // string, or towards the character to the right of the current
8583 // position. The resulting position will have a hitSide=true
8584 // property if it reached the end of the document.
8585 function findPosH(doc, pos, dir, unit, visually) {
8586 var oldPos = pos;
8587 var origDir = dir;
8588 var lineObj = getLine(doc, pos.line);
8589 function findNextLine() {
8590 var l = pos.line + dir;
8591 if (l < doc.first || l >= doc.first + doc.size) { return false }
8592 pos = new Pos(l, pos.ch, pos.sticky);
8593 return lineObj = getLine(doc, l)
8594 }
8595 function moveOnce(boundToLine) {
8596 var next;
8597 if (visually) {
8598 next = moveVisually(doc.cm, lineObj, pos, dir);
8599 } else {
8600 next = moveLogically(lineObj, pos, dir);
8601 }
8602 if (next == null) {
8603 if (!boundToLine && findNextLine())
8604 { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
8605 else
8606 { return false }
8607 } else {
8608 pos = next;
8609 }
8610 return true
8611 }
8612
8613 if (unit == "char") {
8614 moveOnce();
8615 } else if (unit == "column") {
8616 moveOnce(true);
8617 } else if (unit == "word" || unit == "group") {
8618 var sawType = null, group = unit == "group";
8619 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
8620 for (var first = true;; first = false) {
8621 if (dir < 0 && !moveOnce(!first)) { break }
8622 var cur = lineObj.text.charAt(pos.ch) || "\n";
8623 var type = isWordChar(cur, helper) ? "w"
8624 : group && cur == "\n" ? "n"
8625 : !group || /\s/.test(cur) ? null
8626 : "p";
8627 if (group && !first && !type) { type = "s"; }
8628 if (sawType && sawType != type) {
8629 if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
8630 break
8631 }
8632
8633 if (type) { sawType = type; }
8634 if (dir > 0 && !moveOnce(!first)) { break }
8635 }
8636 }
8637 var result = skipAtomic(doc, pos, oldPos, origDir, true);
8638 if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8639 return result
8640 }
8641
8642 // For relative vertical movement. Dir may be -1 or 1. Unit can be
8643 // "page" or "line". The resulting position will have a hitSide=true
8644 // property if it reached the end of the document.
8645 function findPosV(cm, pos, dir, unit) {
8646 var doc = cm.doc, x = pos.left, y;
8647 if (unit == "page") {
8648 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
8649 var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
8650 y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
8651
8652 } else if (unit == "line") {
8653 y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8654 }
8655 var target;
8656 for (;;) {
8657 target = coordsChar(cm, x, y);
8658 if (!target.outside) { break }
8659 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
8660 y += dir * 5;
8661 }
8662 return target
8663 }
8664
8665 // CONTENTEDITABLE INPUT STYLE
8666
8667 var ContentEditableInput = function(cm) {
8668 this.cm = cm;
8669 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
8670 this.polling = new Delayed();
8671 this.composing = null;
8672 this.gracePeriod = false;
8673 this.readDOMTimeout = null;
8674 };
8675
8676 ContentEditableInput.prototype.init = function (display) {
8677 var this$1 = this;
8678
8679 var input = this, cm = input.cm;
8680 var div = input.div = display.lineDiv;
8681 disableBrowserMagic(div, cm.options.spellcheck);
8682
8683 on(div, "paste", function (e) {
8684 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
8685 // IE doesn't fire input events, so we schedule a read for the pasted content in this way
8686 if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
8687 });
8688
8689 on(div, "compositionstart", function (e) {
8690 this$1.composing = {data: e.data, done: false};
8691 });
8692 on(div, "compositionupdate", function (e) {
8693 if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
8694 });
8695 on(div, "compositionend", function (e) {
8696 if (this$1.composing) {
8697 if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
8698 this$1.composing.done = true;
8699 }
8700 });
8701
8702 on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8703
8704 on(div, "input", function () {
8705 if (!this$1.composing) { this$1.readFromDOMSoon(); }
8706 });
8707
8708 function onCopyCut(e) {
8709 if (signalDOMEvent(cm, e)) { return }
8710 if (cm.somethingSelected()) {
8711 setLastCopied({lineWise: false, text: cm.getSelections()});
8712 if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
8713 } else if (!cm.options.lineWiseCopyCut) {
8714 return
8715 } else {
8716 var ranges = copyableRanges(cm);
8717 setLastCopied({lineWise: true, text: ranges.text});
8718 if (e.type == "cut") {
8719 cm.operation(function () {
8720 cm.setSelections(ranges.ranges, 0, sel_dontScroll);
8721 cm.replaceSelection("", null, "cut");
8722 });
8723 }
8724 }
8725 if (e.clipboardData) {
8726 e.clipboardData.clearData();
8727 var content = lastCopied.text.join("\n");
8728 // iOS exposes the clipboard API, but seems to discard content inserted into it
8729 e.clipboardData.setData("Text", content);
8730 if (e.clipboardData.getData("Text") == content) {
8731 e.preventDefault();
8732 return
8733 }
8734 }
8735 // Old-fashioned briefly-focus-a-textarea hack
8736 var kludge = hiddenTextarea(), te = kludge.firstChild;
8737 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
8738 te.value = lastCopied.text.join("\n");
8739 var hadFocus = document.activeElement;
8740 selectInput(te);
8741 setTimeout(function () {
8742 cm.display.lineSpace.removeChild(kludge);
8743 hadFocus.focus();
8744 if (hadFocus == div) { input.showPrimarySelection(); }
8745 }, 50);
8746 }
8747 on(div, "copy", onCopyCut);
8748 on(div, "cut", onCopyCut);
8749 };
8750
8751 ContentEditableInput.prototype.prepareSelection = function () {
8752 var result = prepareSelection(this.cm, false);
8753 result.focus = this.cm.state.focused;
8754 return result
8755 };
8756
8757 ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
8758 if (!info || !this.cm.display.view.length) { return }
8759 if (info.focus || takeFocus) { this.showPrimarySelection(); }
8760 this.showMultipleSelections(info);
8761 };
8762
8763 ContentEditableInput.prototype.showPrimarySelection = function () {
8764 var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
8765 var from = prim.from(), to = prim.to();
8766
8767 if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8768 sel.removeAllRanges();
8769 return
8770 }
8771
8772 var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8773 var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
8774 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
8775 cmp(minPos(curAnchor, curFocus), from) == 0 &&
8776 cmp(maxPos(curAnchor, curFocus), to) == 0)
8777 { return }
8778
8779 var view = cm.display.view;
8780 var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
8781 {node: view[0].measure.map[2], offset: 0};
8782 var end = to.line < cm.display.viewTo && posToDOM(cm, to);
8783 if (!end) {
8784 var measure = view[view.length - 1].measure;
8785 var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
8786 end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
8787 }
8788
8789 if (!start || !end) {
8790 sel.removeAllRanges();
8791 return
8792 }
8793
8794 var old = sel.rangeCount && sel.getRangeAt(0), rng;
8795 try { rng = range(start.node, start.offset, end.offset, end.node); }
8796 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
8797 if (rng) {
8798 if (!gecko && cm.state.focused) {
8799 sel.collapse(start.node, start.offset);
8800 if (!rng.collapsed) {
8801 sel.removeAllRanges();
8802 sel.addRange(rng);
8803 }
8804 } else {
8805 sel.removeAllRanges();
8806 sel.addRange(rng);
8807 }
8808 if (old && sel.anchorNode == null) { sel.addRange(old); }
8809 else if (gecko) { this.startGracePeriod(); }
8810 }
8811 this.rememberSelection();
8812 };
8813
8814 ContentEditableInput.prototype.startGracePeriod = function () {
8815 var this$1 = this;
8816
8817 clearTimeout(this.gracePeriod);
8818 this.gracePeriod = setTimeout(function () {
8819 this$1.gracePeriod = false;
8820 if (this$1.selectionChanged())
8821 { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
8822 }, 20);
8823 };
8824
8825 ContentEditableInput.prototype.showMultipleSelections = function (info) {
8826 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
8827 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
8828 };
8829
8830 ContentEditableInput.prototype.rememberSelection = function () {
8831 var sel = window.getSelection();
8832 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
8833 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
8834 };
8835
8836 ContentEditableInput.prototype.selectionInEditor = function () {
8837 var sel = window.getSelection();
8838 if (!sel.rangeCount) { return false }
8839 var node = sel.getRangeAt(0).commonAncestorContainer;
8840 return contains(this.div, node)
8841 };
8842
8843 ContentEditableInput.prototype.focus = function () {
8844 if (this.cm.options.readOnly != "nocursor") {
8845 if (!this.selectionInEditor())
8846 { this.showSelection(this.prepareSelection(), true); }
8847 this.div.focus();
8848 }
8849 };
8850 ContentEditableInput.prototype.blur = function () { this.div.blur(); };
8851 ContentEditableInput.prototype.getField = function () { return this.div };
8852
8853 ContentEditableInput.prototype.supportsTouch = function () { return true };
8854
8855 ContentEditableInput.prototype.receivedFocus = function () {
8856 var input = this;
8857 if (this.selectionInEditor())
8858 { this.pollSelection(); }
8859 else
8860 { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
8861
8862 function poll() {
8863 if (input.cm.state.focused) {
8864 input.pollSelection();
8865 input.polling.set(input.cm.options.pollInterval, poll);
8866 }
8867 }
8868 this.polling.set(this.cm.options.pollInterval, poll);
8869 };
8870
8871 ContentEditableInput.prototype.selectionChanged = function () {
8872 var sel = window.getSelection();
8873 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
8874 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
8875 };
8876
8877 ContentEditableInput.prototype.pollSelection = function () {
8878 if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
8879 var sel = window.getSelection(), cm = this.cm;
8880 // On Android Chrome (version 56, at least), backspacing into an
8881 // uneditable block element will put the cursor in that element,
8882 // and then, because it's not editable, hide the virtual keyboard.
8883 // Because Android doesn't allow us to actually detect backspace
8884 // presses in a sane way, this code checks for when that happens
8885 // and simulates a backspace press in this case.
8886 if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
8887 this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
8888 this.blur();
8889 this.focus();
8890 return
8891 }
8892 if (this.composing) { return }
8893 this.rememberSelection();
8894 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8895 var head = domToPos(cm, sel.focusNode, sel.focusOffset);
8896 if (anchor && head) { runInOp(cm, function () {
8897 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
8898 if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
8899 }); }
8900 };
8901
8902 ContentEditableInput.prototype.pollContent = function () {
8903 if (this.readDOMTimeout != null) {
8904 clearTimeout(this.readDOMTimeout);
8905 this.readDOMTimeout = null;
8906 }
8907
8908 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
8909 var from = sel.from(), to = sel.to();
8910 if (from.ch == 0 && from.line > cm.firstLine())
8911 { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
8912 if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
8913 { to = Pos(to.line + 1, 0); }
8914 if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
8915
8916 var fromIndex, fromLine, fromNode;
8917 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
8918 fromLine = lineNo(display.view[0].line);
8919 fromNode = display.view[0].node;
8920 } else {
8921 fromLine = lineNo(display.view[fromIndex].line);
8922 fromNode = display.view[fromIndex - 1].node.nextSibling;
8923 }
8924 var toIndex = findViewIndex(cm, to.line);
8925 var toLine, toNode;
8926 if (toIndex == display.view.length - 1) {
8927 toLine = display.viewTo - 1;
8928 toNode = display.lineDiv.lastChild;
8929 } else {
8930 toLine = lineNo(display.view[toIndex + 1].line) - 1;
8931 toNode = display.view[toIndex + 1].node.previousSibling;
8932 }
8933
8934 if (!fromNode) { return false }
8935 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
8936 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
8937 while (newText.length > 1 && oldText.length > 1) {
8938 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
8939 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
8940 else { break }
8941 }
8942
8943 var cutFront = 0, cutEnd = 0;
8944 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
8945 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
8946 { ++cutFront; }
8947 var newBot = lst(newText), oldBot = lst(oldText);
8948 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
8949 oldBot.length - (oldText.length == 1 ? cutFront : 0));
8950 while (cutEnd < maxCutEnd &&
8951 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
8952 { ++cutEnd; }
8953 // Try to move start of change to start of selection if ambiguous
8954 if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
8955 while (cutFront && cutFront > from.ch &&
8956 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
8957 cutFront--;
8958 cutEnd++;
8959 }
8960 }
8961
8962 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
8963 newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
8964
8965 var chFrom = Pos(fromLine, cutFront);
8966 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
8967 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
8968 replaceRange(cm.doc, newText, chFrom, chTo, "+input");
8969 return true
8970 }
8971 };
8972
8973 ContentEditableInput.prototype.ensurePolled = function () {
8974 this.forceCompositionEnd();
8975 };
8976 ContentEditableInput.prototype.reset = function () {
8977 this.forceCompositionEnd();
8978 };
8979 ContentEditableInput.prototype.forceCompositionEnd = function () {
8980 if (!this.composing) { return }
8981 clearTimeout(this.readDOMTimeout);
8982 this.composing = null;
8983 this.updateFromDOM();
8984 this.div.blur();
8985 this.div.focus();
8986 };
8987 ContentEditableInput.prototype.readFromDOMSoon = function () {
8988 var this$1 = this;
8989
8990 if (this.readDOMTimeout != null) { return }
8991 this.readDOMTimeout = setTimeout(function () {
8992 this$1.readDOMTimeout = null;
8993 if (this$1.composing) {
8994 if (this$1.composing.done) { this$1.composing = null; }
8995 else { return }
8996 }
8997 this$1.updateFromDOM();
8998 }, 80);
8999 };
9000
9001 ContentEditableInput.prototype.updateFromDOM = function () {
9002 var this$1 = this;
9003
9004 if (this.cm.isReadOnly() || !this.pollContent())
9005 { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
9006 };
9007
9008 ContentEditableInput.prototype.setUneditable = function (node) {
9009 node.contentEditable = "false";
9010 };
9011
9012 ContentEditableInput.prototype.onKeyPress = function (e) {
9013 if (e.charCode == 0) { return }
9014 e.preventDefault();
9015 if (!this.cm.isReadOnly())
9016 { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
9017 };
9018
9019 ContentEditableInput.prototype.readOnlyChanged = function (val) {
9020 this.div.contentEditable = String(val != "nocursor");
9021 };
9022
9023 ContentEditableInput.prototype.onContextMenu = function () {};
9024 ContentEditableInput.prototype.resetPosition = function () {};
9025
9026 ContentEditableInput.prototype.needsContentAttribute = true;
9027
9028 function posToDOM(cm, pos) {
9029 var view = findViewForLine(cm, pos.line);
9030 if (!view || view.hidden) { return null }
9031 var line = getLine(cm.doc, pos.line);
9032 var info = mapFromLineView(view, line, pos.line);
9033
9034 var order = getOrder(line, cm.doc.direction), side = "left";
9035 if (order) {
9036 var partPos = getBidiPartAt(order, pos.ch);
9037 side = partPos % 2 ? "right" : "left";
9038 }
9039 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9040 result.offset = result.collapse == "right" ? result.end : result.start;
9041 return result
9042 }
9043
9044 function isInGutter(node) {
9045 for (var scan = node; scan; scan = scan.parentNode)
9046 { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
9047 return false
9048 }
9049
9050 function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9051
9052 function domTextBetween(cm, from, to, fromLine, toLine) {
9053 var text = "", closing = false, lineSep = cm.doc.lineSeparator();
9054 function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
9055 function close() {
9056 if (closing) {
9057 text += lineSep;
9058 closing = false;
9059 }
9060 }
9061 function addText(str) {
9062 if (str) {
9063 close();
9064 text += str;
9065 }
9066 }
9067 function walk(node) {
9068 if (node.nodeType == 1) {
9069 var cmText = node.getAttribute("cm-text");
9070 if (cmText != null) {
9071 addText(cmText || node.textContent.replace(/\u200b/g, ""));
9072 return
9073 }
9074 var markerID = node.getAttribute("cm-marker"), range$$1;
9075 if (markerID) {
9076 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
9077 if (found.length && (range$$1 = found[0].find(0)))
9078 { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
9079 return
9080 }
9081 if (node.getAttribute("contenteditable") == "false") { return }
9082 var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
9083 if (isBlock) { close(); }
9084 for (var i = 0; i < node.childNodes.length; i++)
9085 { walk(node.childNodes[i]); }
9086 if (isBlock) { closing = true; }
9087 } else if (node.nodeType == 3) {
9088 addText(node.nodeValue);
9089 }
9090 }
9091 for (;;) {
9092 walk(from);
9093 if (from == to) { break }
9094 from = from.nextSibling;
9095 }
9096 return text
9097 }
9098
9099 function domToPos(cm, node, offset) {
9100 var lineNode;
9101 if (node == cm.display.lineDiv) {
9102 lineNode = cm.display.lineDiv.childNodes[offset];
9103 if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
9104 node = null; offset = 0;
9105 } else {
9106 for (lineNode = node;; lineNode = lineNode.parentNode) {
9107 if (!lineNode || lineNode == cm.display.lineDiv) { return null }
9108 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
9109 }
9110 }
9111 for (var i = 0; i < cm.display.view.length; i++) {
9112 var lineView = cm.display.view[i];
9113 if (lineView.node == lineNode)
9114 { return locateNodeInLineView(lineView, node, offset) }
9115 }
9116 }
9117
9118 function locateNodeInLineView(lineView, node, offset) {
9119 var wrapper = lineView.text.firstChild, bad = false;
9120 if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
9121 if (node == wrapper) {
9122 bad = true;
9123 node = wrapper.childNodes[offset];
9124 offset = 0;
9125 if (!node) {
9126 var line = lineView.rest ? lst(lineView.rest) : lineView.line;
9127 return badPos(Pos(lineNo(line), line.text.length), bad)
9128 }
9129 }
9130
9131 var textNode = node.nodeType == 3 ? node : null, topNode = node;
9132 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
9133 textNode = node.firstChild;
9134 if (offset) { offset = textNode.nodeValue.length; }
9135 }
9136 while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
9137 var measure = lineView.measure, maps = measure.maps;
9138
9139 function find(textNode, topNode, offset) {
9140 for (var i = -1; i < (maps ? maps.length : 0); i++) {
9141 var map$$1 = i < 0 ? measure.map : maps[i];
9142 for (var j = 0; j < map$$1.length; j += 3) {
9143 var curNode = map$$1[j + 2];
9144 if (curNode == textNode || curNode == topNode) {
9145 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
9146 var ch = map$$1[j] + offset;
9147 if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
9148 return Pos(line, ch)
9149 }
9150 }
9151 }
9152 }
9153 var found = find(textNode, topNode, offset);
9154 if (found) { return badPos(found, bad) }
9155
9156 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
9157 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
9158 found = find(after, after.firstChild, 0);
9159 if (found)
9160 { return badPos(Pos(found.line, found.ch - dist), bad) }
9161 else
9162 { dist += after.textContent.length; }
9163 }
9164 for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
9165 found = find(before, before.firstChild, -1);
9166 if (found)
9167 { return badPos(Pos(found.line, found.ch + dist$1), bad) }
9168 else
9169 { dist$1 += before.textContent.length; }
9170 }
9171 }
9172
9173 // TEXTAREA INPUT STYLE
9174
9175 var TextareaInput = function(cm) {
9176 this.cm = cm;
9177 // See input.poll and input.reset
9178 this.prevInput = "";
9179
9180 // Flag that indicates whether we expect input to appear real soon
9181 // now (after some event like 'keypress' or 'input') and are
9182 // polling intensively.
9183 this.pollingFast = false;
9184 // Self-resetting timeout for the poller
9185 this.polling = new Delayed();
9186 // Used to work around IE issue with selection being forgotten when focus moves away from textarea
9187 this.hasSelection = false;
9188 this.composing = null;
9189 };
9190
9191 TextareaInput.prototype.init = function (display) {
9192 var this$1 = this;
9193
9194 var input = this, cm = this.cm;
9195
9196 // Wraps and hides input textarea
9197 var div = this.wrapper = hiddenTextarea();
9198 // The semihidden textarea that is focused when the editor is
9199 // focused, and receives input.
9200 var te = this.textarea = div.firstChild;
9201 display.wrapper.insertBefore(div, display.wrapper.firstChild);
9202
9203 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
9204 if (ios) { te.style.width = "0px"; }
9205
9206 on(te, "input", function () {
9207 if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9208 input.poll();
9209 });
9210
9211 on(te, "paste", function (e) {
9212 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9213
9214 cm.state.pasteIncoming = true;
9215 input.fastPoll();
9216 });
9217
9218 function prepareCopyCut(e) {
9219 if (signalDOMEvent(cm, e)) { return }
9220 if (cm.somethingSelected()) {
9221 setLastCopied({lineWise: false, text: cm.getSelections()});
9222 } else if (!cm.options.lineWiseCopyCut) {
9223 return
9224 } else {
9225 var ranges = copyableRanges(cm);
9226 setLastCopied({lineWise: true, text: ranges.text});
9227 if (e.type == "cut") {
9228 cm.setSelections(ranges.ranges, null, sel_dontScroll);
9229 } else {
9230 input.prevInput = "";
9231 te.value = ranges.text.join("\n");
9232 selectInput(te);
9233 }
9234 }
9235 if (e.type == "cut") { cm.state.cutIncoming = true; }
9236 }
9237 on(te, "cut", prepareCopyCut);
9238 on(te, "copy", prepareCopyCut);
9239
9240 on(display.scroller, "paste", function (e) {
9241 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
9242 cm.state.pasteIncoming = true;
9243 input.focus();
9244 });
9245
9246 // Prevent normal selection in the editor (we handle our own)
9247 on(display.lineSpace, "selectstart", function (e) {
9248 if (!eventInWidget(display, e)) { e_preventDefault(e); }
9249 });
9250
9251 on(te, "compositionstart", function () {
9252 var start = cm.getCursor("from");
9253 if (input.composing) { input.composing.range.clear(); }
9254 input.composing = {
9255 start: start,
9256 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
9257 };
9258 });
9259 on(te, "compositionend", function () {
9260 if (input.composing) {
9261 input.poll();
9262 input.composing.range.clear();
9263 input.composing = null;
9264 }
9265 });
9266 };
9267
9268 TextareaInput.prototype.prepareSelection = function () {
9269 // Redraw the selection and/or cursor
9270 var cm = this.cm, display = cm.display, doc = cm.doc;
9271 var result = prepareSelection(cm);
9272
9273 // Move the hidden textarea near the cursor to prevent scrolling artifacts
9274 if (cm.options.moveInputWithCursor) {
9275 var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
9276 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
9277 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
9278 headPos.top + lineOff.top - wrapOff.top));
9279 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
9280 headPos.left + lineOff.left - wrapOff.left));
9281 }
9282
9283 return result
9284 };
9285
9286 TextareaInput.prototype.showSelection = function (drawn) {
9287 var cm = this.cm, display = cm.display;
9288 removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
9289 removeChildrenAndAdd(display.selectionDiv, drawn.selection);
9290 if (drawn.teTop != null) {
9291 this.wrapper.style.top = drawn.teTop + "px";
9292 this.wrapper.style.left = drawn.teLeft + "px";
9293 }
9294 };
9295
9296 // Reset the input to correspond to the selection (or to be empty,
9297 // when not typing and nothing is selected)
9298 TextareaInput.prototype.reset = function (typing) {
9299 if (this.contextMenuPending || this.composing) { return }
9300 var cm = this.cm;
9301 if (cm.somethingSelected()) {
9302 this.prevInput = "";
9303 var content = cm.getSelection();
9304 this.textarea.value = content;
9305 if (cm.state.focused) { selectInput(this.textarea); }
9306 if (ie && ie_version >= 9) { this.hasSelection = content; }
9307 } else if (!typing) {
9308 this.prevInput = this.textarea.value = "";
9309 if (ie && ie_version >= 9) { this.hasSelection = null; }
9310 }
9311 };
9312
9313 TextareaInput.prototype.getField = function () { return this.textarea };
9314
9315 TextareaInput.prototype.supportsTouch = function () { return false };
9316
9317 TextareaInput.prototype.focus = function () {
9318 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
9319 try { this.textarea.focus(); }
9320 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
9321 }
9322 };
9323
9324 TextareaInput.prototype.blur = function () { this.textarea.blur(); };
9325
9326 TextareaInput.prototype.resetPosition = function () {
9327 this.wrapper.style.top = this.wrapper.style.left = 0;
9328 };
9329
9330 TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
9331
9332 // Poll for input changes, using the normal rate of polling. This
9333 // runs as long as the editor is focused.
9334 TextareaInput.prototype.slowPoll = function () {
9335 var this$1 = this;
9336
9337 if (this.pollingFast) { return }
9338 this.polling.set(this.cm.options.pollInterval, function () {
9339 this$1.poll();
9340 if (this$1.cm.state.focused) { this$1.slowPoll(); }
9341 });
9342 };
9343
9344 // When an event has just come in that is likely to add or change
9345 // something in the input textarea, we poll faster, to ensure that
9346 // the change appears on the screen quickly.
9347 TextareaInput.prototype.fastPoll = function () {
9348 var missed = false, input = this;
9349 input.pollingFast = true;
9350 function p() {
9351 var changed = input.poll();
9352 if (!changed && !missed) {missed = true; input.polling.set(60, p);}
9353 else {input.pollingFast = false; input.slowPoll();}
9354 }
9355 input.polling.set(20, p);
9356 };
9357
9358 // Read input from the textarea, and update the document to match.
9359 // When something is selected, it is present in the textarea, and
9360 // selected (unless it is huge, in which case a placeholder is
9361 // used). When nothing is selected, the cursor sits after previously
9362 // seen text (can be empty), which is stored in prevInput (we must
9363 // not reset the textarea when typing, because that breaks IME).
9364 TextareaInput.prototype.poll = function () {
9365 var this$1 = this;
9366
9367 var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
9368 // Since this is called a *lot*, try to bail out as cheaply as
9369 // possible when it is clear that nothing happened. hasSelection
9370 // will be the case when there is a lot of text in the textarea,
9371 // in which case reading its value would be expensive.
9372 if (this.contextMenuPending || !cm.state.focused ||
9373 (hasSelection(input) && !prevInput && !this.composing) ||
9374 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
9375 { return false }
9376
9377 var text = input.value;
9378 // If nothing changed, bail.
9379 if (text == prevInput && !cm.somethingSelected()) { return false }
9380 // Work around nonsensical selection resetting in IE9/10, and
9381 // inexplicable appearance of private area unicode characters on
9382 // some key combos in Mac (#2689).
9383 if (ie && ie_version >= 9 && this.hasSelection === text ||
9384 mac && /[\uf700-\uf7ff]/.test(text)) {
9385 cm.display.input.reset();
9386 return false
9387 }
9388
9389 if (cm.doc.sel == cm.display.selForContextMenu) {
9390 var first = text.charCodeAt(0);
9391 if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
9392 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
9393 }
9394 // Find the part of the input that is actually new
9395 var same = 0, l = Math.min(prevInput.length, text.length);
9396 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
9397
9398 runInOp(cm, function () {
9399 applyTextInput(cm, text.slice(same), prevInput.length - same,
9400 null, this$1.composing ? "*compose" : null);
9401
9402 // Don't leave long text in the textarea, since it makes further polling slow
9403 if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
9404 else { this$1.prevInput = text; }
9405
9406 if (this$1.composing) {
9407 this$1.composing.range.clear();
9408 this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
9409 {className: "CodeMirror-composing"});
9410 }
9411 });
9412 return true
9413 };
9414
9415 TextareaInput.prototype.ensurePolled = function () {
9416 if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9417 };
9418
9419 TextareaInput.prototype.onKeyPress = function () {
9420 if (ie && ie_version >= 9) { this.hasSelection = null; }
9421 this.fastPoll();
9422 };
9423
9424 TextareaInput.prototype.onContextMenu = function (e) {
9425 var input = this, cm = input.cm, display = cm.display, te = input.textarea;
9426 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
9427 if (!pos || presto) { return } // Opera is difficult.
9428
9429 // Reset the current text selection only if the click is done outside of the selection
9430 // and 'resetSelectionOnContextMenu' option is true.
9431 var reset = cm.options.resetSelectionOnContextMenu;
9432 if (reset && cm.doc.sel.contains(pos) == -1)
9433 { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
9434
9435 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
9436 input.wrapper.style.cssText = "position: absolute";
9437 var wrapperBox = input.wrapper.getBoundingClientRect();
9438 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);";
9439 var oldScrollY;
9440 if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
9441 display.input.focus();
9442 if (webkit) { window.scrollTo(null, oldScrollY); }
9443 display.input.reset();
9444 // Adds "Select all" to context menu in FF
9445 if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
9446 input.contextMenuPending = true;
9447 display.selForContextMenu = cm.doc.sel;
9448 clearTimeout(display.detectingSelectAll);
9449
9450 // Select-all will be greyed out if there's nothing to select, so
9451 // this adds a zero-width space so that we can later check whether
9452 // it got selected.
9453 function prepareSelectAllHack() {
9454 if (te.selectionStart != null) {
9455 var selected = cm.somethingSelected();
9456 var extval = "\u200b" + (selected ? te.value : "");
9457 te.value = "\u21da"; // Used to catch context-menu undo
9458 te.value = extval;
9459 input.prevInput = selected ? "" : "\u200b";
9460 te.selectionStart = 1; te.selectionEnd = extval.length;
9461 // Re-set this, in case some other handler touched the
9462 // selection in the meantime.
9463 display.selForContextMenu = cm.doc.sel;
9464 }
9465 }
9466 function rehide() {
9467 input.contextMenuPending = false;
9468 input.wrapper.style.cssText = oldWrapperCSS;
9469 te.style.cssText = oldCSS;
9470 if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
9471
9472 // Try to detect the user choosing select-all
9473 if (te.selectionStart != null) {
9474 if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
9475 var i = 0, poll = function () {
9476 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
9477 te.selectionEnd > 0 && input.prevInput == "\u200b") {
9478 operation(cm, selectAll)(cm);
9479 } else if (i++ < 10) {
9480 display.detectingSelectAll = setTimeout(poll, 500);
9481 } else {
9482 display.selForContextMenu = null;
9483 display.input.reset();
9484 }
9485 };
9486 display.detectingSelectAll = setTimeout(poll, 200);
9487 }
9488 }
9489
9490 if (ie && ie_version >= 9) { prepareSelectAllHack(); }
9491 if (captureRightClick) {
9492 e_stop(e);
9493 var mouseup = function () {
9494 off(window, "mouseup", mouseup);
9495 setTimeout(rehide, 20);
9496 };
9497 on(window, "mouseup", mouseup);
9498 } else {
9499 setTimeout(rehide, 50);
9500 }
9501 };
9502
9503 TextareaInput.prototype.readOnlyChanged = function (val) {
9504 if (!val) { this.reset(); }
9505 this.textarea.disabled = val == "nocursor";
9506 };
9507
9508 TextareaInput.prototype.setUneditable = function () {};
9509
9510 TextareaInput.prototype.needsContentAttribute = false;
9511
9512 function fromTextArea(textarea, options) {
9513 options = options ? copyObj(options) : {};
9514 options.value = textarea.value;
9515 if (!options.tabindex && textarea.tabIndex)
9516 { options.tabindex = textarea.tabIndex; }
9517 if (!options.placeholder && textarea.placeholder)
9518 { options.placeholder = textarea.placeholder; }
9519 // Set autofocus to true if this textarea is focused, or if it has
9520 // autofocus and no other element is focused.
9521 if (options.autofocus == null) {
9522 var hasFocus = activeElt();
9523 options.autofocus = hasFocus == textarea ||
9524 textarea.getAttribute("autofocus") != null && hasFocus == document.body;
9525 }
9526
9527 function save() {textarea.value = cm.getValue();}
9528
9529 var realSubmit;
9530 if (textarea.form) {
9531 on(textarea.form, "submit", save);
9532 // Deplorable hack to make the submit method do the right thing.
9533 if (!options.leaveSubmitMethodAlone) {
9534 var form = textarea.form;
9535 realSubmit = form.submit;
9536 try {
9537 var wrappedSubmit = form.submit = function () {
9538 save();
9539 form.submit = realSubmit;
9540 form.submit();
9541 form.submit = wrappedSubmit;
9542 };
9543 } catch(e) {}
9544 }
9545 }
9546
9547 options.finishInit = function (cm) {
9548 cm.save = save;
9549 cm.getTextArea = function () { return textarea; };
9550 cm.toTextArea = function () {
9551 cm.toTextArea = isNaN; // Prevent this from being ran twice
9552 save();
9553 textarea.parentNode.removeChild(cm.getWrapperElement());
9554 textarea.style.display = "";
9555 if (textarea.form) {
9556 off(textarea.form, "submit", save);
9557 if (typeof textarea.form.submit == "function")
9558 { textarea.form.submit = realSubmit; }
9559 }
9560 };
9561 };
9562
9563 textarea.style.display = "none";
9564 var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
9565 options);
9566 return cm
9567 }
9568
9569 function addLegacyProps(CodeMirror) {
9570 CodeMirror.off = off;
9571 CodeMirror.on = on;
9572 CodeMirror.wheelEventPixels = wheelEventPixels;
9573 CodeMirror.Doc = Doc;
9574 CodeMirror.splitLines = splitLinesAuto;
9575 CodeMirror.countColumn = countColumn;
9576 CodeMirror.findColumn = findColumn;
9577 CodeMirror.isWordChar = isWordCharBasic;
9578 CodeMirror.Pass = Pass;
9579 CodeMirror.signal = signal;
9580 CodeMirror.Line = Line;
9581 CodeMirror.changeEnd = changeEnd;
9582 CodeMirror.scrollbarModel = scrollbarModel;
9583 CodeMirror.Pos = Pos;
9584 CodeMirror.cmpPos = cmp;
9585 CodeMirror.modes = modes;
9586 CodeMirror.mimeModes = mimeModes;
9587 CodeMirror.resolveMode = resolveMode;
9588 CodeMirror.getMode = getMode;
9589 CodeMirror.modeExtensions = modeExtensions;
9590 CodeMirror.extendMode = extendMode;
9591 CodeMirror.copyState = copyState;
9592 CodeMirror.startState = startState;
9593 CodeMirror.innerMode = innerMode;
9594 CodeMirror.commands = commands;
9595 CodeMirror.keyMap = keyMap;
9596 CodeMirror.keyName = keyName;
9597 CodeMirror.isModifierKey = isModifierKey;
9598 CodeMirror.lookupKey = lookupKey;
9599 CodeMirror.normalizeKeyMap = normalizeKeyMap;
9600 CodeMirror.StringStream = StringStream;
9601 CodeMirror.SharedTextMarker = SharedTextMarker;
9602 CodeMirror.TextMarker = TextMarker;
9603 CodeMirror.LineWidget = LineWidget;
9604 CodeMirror.e_preventDefault = e_preventDefault;
9605 CodeMirror.e_stopPropagation = e_stopPropagation;
9606 CodeMirror.e_stop = e_stop;
9607 CodeMirror.addClass = addClass;
9608 CodeMirror.contains = contains;
9609 CodeMirror.rmClass = rmClass;
9610 CodeMirror.keyNames = keyNames;
9611 }
9612
9613 // EDITOR CONSTRUCTOR
9614
9615 defineOptions(CodeMirror$1);
9616
9617 addEditorMethods(CodeMirror$1);
9618
9619 // Set up methods on CodeMirror's prototype to redirect to the editor's document.
9620 var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
9621 for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
9622 { CodeMirror$1.prototype[prop] = (function(method) {
9623 return function() {return method.apply(this.doc, arguments)}
9624 })(Doc.prototype[prop]); } }
9625
9626 eventMixin(Doc);
9627
9628 // INPUT HANDLING
9629
9630 CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9631
9632 // MODE DEFINITION AND QUERYING
9633
9634 // Extra arguments are stored as the mode's dependencies, which is
9635 // used by (legacy) mechanisms like loadmode.js to automatically
9636 // load a mode. (Preferred mechanism is the require/define calls.)
9637 CodeMirror$1.defineMode = function(name/*, mode, …*/) {
9638 if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
9639 defineMode.apply(this, arguments);
9640 };
9641
9642 CodeMirror$1.defineMIME = defineMIME;
9643
9644 // Minimal default mode.
9645 CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9646 CodeMirror$1.defineMIME("text/plain", "null");
9647
9648 // EXTENSIONS
9649
9650 CodeMirror$1.defineExtension = function (name, func) {
9651 CodeMirror$1.prototype[name] = func;
9652 };
9653 CodeMirror$1.defineDocExtension = function (name, func) {
9654 Doc.prototype[name] = func;
9655 };
9656
9657 CodeMirror$1.fromTextArea = fromTextArea;
9658
9659 addLegacyProps(CodeMirror$1);
9660
9661 CodeMirror$1.version = "5.32.0";
9662
9663 return CodeMirror$1;
9664
9665 })));
9666