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
← All changes | assets/codemirror/codemirror.js +8394 -8526 4.124.5 View file →
@@ -1,8 +1,8 @@
1 1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 -// Distributed under an MIT license: https://codemirror.net/LICENSE
2 +// Distributed under an MIT license: http://codemirror.net/LICENSE
3 3
4 -// This is CodeMirror (https://codemirror.net), a code editor
4 +// This is CodeMirror (http://codemirror.net), a code editor
5 5 // implemented in JavaScript on top of the browser's DOM.
6 6 //
7 7 // You can find some technical background for some of the code below
8 8 // at http://marijnhaverbeke.nl/blog/#cm-internals .
@@ -7,9791 +7,9659 @@
7 7 // You can find some technical background for some of the code below
8 8 // at http://marijnhaverbeke.nl/blog/#cm-internals .
9 9
10 10 (function (global, factory) {
11 - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
12 - typeof define === 'function' && define.amd ? define(factory) :
13 - (global = global || self, global.CodeMirror = factory());
11 + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
12 + typeof define === 'function' && define.amd ? define(factory) :
13 + (global.CodeMirror = factory());
14 14 }(this, (function () { 'use strict';
15 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;
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 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);
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 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);
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 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);
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 49
50 - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
50 +function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
51 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 - };
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 60
61 - function removeChildren(e) {
62 - for (var count = e.childNodes.length; count > 0; --count)
63 - { e.removeChild(e.firstChild); }
64 - return e
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;
65 123 }
124 + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
125 + { activeElement = activeElement.shadowRoot.activeElement; }
126 + return activeElement
127 +}
66 128
67 - function removeChildrenAndAdd(parent, e) {
68 - return removeChildren(parent).appendChild(e)
69 - }
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 +}
70 139
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
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; }
78 165 }
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
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;
84 173 }
174 +}
85 175
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 - }; }
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 +};
102 181
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)
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 }
112 213 }
214 +}
113 215
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 - }
216 +var spaceStrs = [""];
217 +function spaceStr(n) {
218 + while (spaceStrs.length <= n)
219 + { spaceStrs.push(lst(spaceStrs) + " "); }
220 + return spaceStrs[n]
221 +}
128 222
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 - }
223 +function lst(arr) { return arr[arr.length-1] }
139 224
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) {} }; }
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 +}
145 230
146 - function bind(f) {
147 - var args = Array.prototype.slice.call(arguments, 1);
148 - return function(){return f.apply(null, args)}
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();
149 246 }
247 + if (props) { copyObj(props, inst); }
248 + return inst
249 +}
150 250
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 - }
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 +}
158 261
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 - }
262 +function isEmpty(obj) {
263 + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
264 + return true
265 +}
175 266
176 - var Delayed = function() {
177 - this.id = null;
178 - this.f = null;
179 - this.time = 0;
180 - this.handler = bind(this.onTimeout, this);
181 - };
182 - Delayed.prototype.onTimeout = function (self) {
183 - self.id = 0;
184 - if (self.time <= +new Date) {
185 - self.f();
186 - } else {
187 - setTimeout(self.handler, self.time - +new Date);
188 - }
189 - };
190 - Delayed.prototype.set = function (ms, f) {
191 - this.f = f;
192 - var time = +new Date + ms;
193 - if (!this.id || time < this.time) {
194 - clearTimeout(this.id);
195 - this.id = setTimeout(this.handler, ms);
196 - this.time = time;
197 - }
198 - };
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) }
199 274
200 - function indexOf(array, elt) {
201 - for (var i = 0; i < array.length; ++i)
202 - { if (array[i] == elt) { return i } }
203 - return -1
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; }
204 294 }
295 +}
205 296
206 - // Number of pixels added to scroller and sizer to hide scrollbar
207 - var scrollerGap = 50;
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.
208 300
209 - // Returned or thrown by various protocols to signal 'I'm not
210 - // handling this'.
211 - var Pass = {toString: function(){return "CodeMirror.Pass"}};
301 +function Display(place, doc, input) {
302 + var d = this;
303 + this.input = input;
212 304
213 - // Reused option objects for setSelection & friends
214 - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
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");
215 342
216 - // The inverse of countColumn -- find the offset that corresponds to
217 - // a particular column.
218 - function findColumn(string, goal, tabSize) {
219 - for (var pos = 0, col = 0;;) {
220 - var nextTab = string.indexOf("\t", pos);
221 - if (nextTab == -1) { nextTab = string.length; }
222 - var skipped = nextTab - pos;
223 - if (nextTab == string.length || col + skipped >= goal)
224 - { return pos + Math.min(skipped, goal - col) }
225 - col += nextTab - pos;
226 - col += tabSize - (col % tabSize);
227 - pos = nextTab + 1;
228 - if (col >= goal) { return pos }
229 - }
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); }
230 350 }
231 351
232 - var spaceStrs = [""];
233 - function spaceStr(n) {
234 - while (spaceStrs.length <= n)
235 - { spaceStrs.push(lst(spaceStrs) + " "); }
236 - return spaceStrs[n]
237 - }
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;
238 365
239 - function lst(arr) { return arr[arr.length-1] }
366 + d.nativeBarWidth = d.barHeight = d.barWidth = 0;
367 + d.scrollbarsClipped = false;
240 368
241 - function map(array, f) {
242 - var out = [];
243 - for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
244 - return out
245 - }
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;
246 376
247 - function insertSorted(array, value, score) {
248 - var pos = 0, priority = score(value);
249 - while (pos < array.length && score(array[pos]) <= priority) { pos++; }
250 - array.splice(pos, 0, value);
251 - }
377 + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
252 378
253 - function nothing() {}
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;
254 384
255 - function createObj(base, props) {
256 - var inst;
257 - if (Object.create) {
258 - inst = Object.create(base);
259 - } else {
260 - nothing.prototype = base;
261 - inst = new nothing();
262 - }
263 - if (props) { copyObj(props, inst); }
264 - return inst
265 - }
385 + // Used for measuring wheel scrolling granularity
386 + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
266 387
267 - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
268 - function isWordCharBasic(ch) {
269 - return /\w/.test(ch) || ch > "\x80" &&
270 - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
271 - }
272 - function isWordChar(ch, helper) {
273 - if (!helper) { return isWordCharBasic(ch) }
274 - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
275 - return helper.test(ch)
276 - }
388 + // True when shift is held down.
389 + d.shift = false;
277 390
278 - function isEmpty(obj) {
279 - for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
280 - return true
281 - }
391 + // Used to track whether anything happened since the context menu
392 + // was opened.
393 + d.selForContextMenu = null;
282 394
283 - // Extending unicode characters. A series of a non-extending char +
284 - // any number of extending chars is treated as a single unit as far
285 - // as editing and measuring is concerned. This is not fully correct,
286 - // since some scripts/fonts/browsers also treat other configurations
287 - // of code points as a group.
288 - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
289 - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
395 + d.activeTouch = null;
290 396
291 - // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
292 - function skipExtendingChars(str, pos, dir) {
293 - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
294 - return pos
295 - }
397 + input.init(d);
398 +}
296 399
297 - // Returns the value from the range [`from`; `to`] that satisfies
298 - // `pred` and is closest to `from`. Assumes that at least `to`
299 - // satisfies `pred`. Supports `from` being greater than `to`.
300 - function findFirst(pred, from, to) {
301 - // At any point we are certain `to` satisfies `pred`, don't know
302 - // whether `from` does.
303 - var dir = from > to ? -1 : 1;
304 - for (;;) {
305 - if (from == to) { return from }
306 - var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
307 - if (mid == from) { return pred(mid) ? from : to }
308 - if (pred(mid)) { to = mid; }
309 - else { from = mid + dir; }
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;
310 410 }
311 411 }
412 + return chunk.lines[n]
413 +}
312 414
313 - // BIDI HELPERS
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 +}
314 434
315 - function iterateBidiSections(order, from, to, f) {
316 - if (!order) { return f(from, to, "ltr", 0) }
317 - var found = false;
318 - for (var i = 0; i < order.length; ++i) {
319 - var part = order[i];
320 - if (part.from < to && part.to > from || from == to && part.to == from) {
321 - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
322 - found = true;
323 - }
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();
324 451 }
325 - if (!found) { f(from, to, "ltr"); }
326 452 }
453 + return no + cur.first
454 +}
327 455
328 - var bidiOther = null;
329 - function getBidiPartAt(order, ch, sticky) {
330 - var found;
331 - bidiOther = null;
332 - for (var i = 0; i < order.length; ++i) {
333 - var cur = order[i];
334 - if (cur.from < ch && cur.to > ch) { return i }
335 - if (cur.to == ch) {
336 - if (cur.from != cur.to && sticky == "before") { found = i; }
337 - else { bidiOther = i; }
338 - }
339 - if (cur.from == ch) {
340 - if (cur.from != cur.to && sticky != "before") { found = i; }
341 - else { bidiOther = i; }
342 - }
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();
343 466 }
344 - return found != null ? found : bidiOther
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;
345 474 }
475 + return n + i
476 +}
346 477
347 - // Bidirectional ordering algorithm
348 - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
349 - // that this (partially) implements.
478 +function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
350 479
351 - // One-char codes used for character types:
352 - // L (L): Left-to-Right
353 - // R (R): Right-to-Left
354 - // r (AL): Right-to-Left Arabic
355 - // 1 (EN): European Number
356 - // + (ES): European Number Separator
357 - // % (ET): European Number Terminator
358 - // n (AN): Arabic Number
359 - // , (CS): Common Number Separator
360 - // m (NSM): Non-Spacing Mark
361 - // b (BN): Boundary Neutral
362 - // s (B): Paragraph Separator
363 - // t (S): Segment Separator
364 - // w (WS): Whitespace
365 - // N (ON): Other Neutrals
480 +function lineNumberFor(options, i) {
481 + return String(options.lineNumberFormatter(i + options.firstLineNumber))
482 +}
366 483
367 - // Returns null if characters are ordered as they appear
368 - // (left-to-right), or an array of sections ({from, to, level}
369 - // objects) in the order in which they occur visually.
370 - var bidiOrdering = (function() {
371 - // Character types for codepoints 0 to 0xff
372 - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
373 - // Character types for codepoints 0x600 to 0x6f9
374 - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
375 - function charType(code) {
376 - if (code <= 0xf7) { return lowTypes.charAt(code) }
377 - else if (0x590 <= code && code <= 0x5f4) { return "R" }
378 - else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
379 - else if (0x6ee <= code && code <= 0x8ac) { return "r" }
380 - else if (0x2000 <= code && code <= 0x200b) { return "w" }
381 - else if (code == 0x200c) { return "b" }
382 - else { return "L" }
383 - }
484 +// A Pos instance represents a position within the text.
485 +function Pos(line, ch, sticky) {
486 + if ( sticky === void 0 ) sticky = null;
384 487
385 - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
386 - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
488 + if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
489 + this.line = line;
490 + this.ch = ch;
491 + this.sticky = sticky;
492 +}
387 493
388 - function BidiSpan(level, from, to) {
389 - this.level = level;
390 - this.from = from; this.to = to;
391 - }
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 }
392 497
393 - return function(str, direction) {
394 - var outerType = direction == "ltr" ? "L" : "R";
498 +function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
395 499
396 - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
397 - var len = str.length, types = [];
398 - for (var i = 0; i < len; ++i)
399 - { types.push(charType(str.charCodeAt(i))); }
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 }
400 503
401 - // W1. Examine each non-spacing mark (NSM) in the level run, and
402 - // change the type of the NSM to the type of the previous
403 - // character. If the NSM is at the start of the level run, it will
404 - // get the type of sor.
405 - for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
406 - var type = types[i$1];
407 - if (type == "m") { types[i$1] = prev; }
408 - else { prev = type; }
409 - }
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 +}
410 524
411 - // W2. Search backwards from each instance of a European number
412 - // until the first strong type (R, L, AL, or sor) is found. If an
413 - // AL is found, change the type of the European number to Arabic
414 - // number.
415 - // W3. Change all ALs to R.
416 - for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
417 - var type$1 = types[i$2];
418 - if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
419 - else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
420 - }
525 +// Optimize some code when these features are not used.
526 +var sawReadOnlySpans = false;
527 +var sawCollapsedSpans = false;
421 528
422 - // W4. A single European separator between two European numbers
423 - // changes to a European number. A single common separator between
424 - // two numbers of the same type changes to that type.
425 - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
426 - var type$2 = types[i$3];
427 - if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
428 - else if (type$2 == "," && prev$1 == types[i$3+1] &&
429 - (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
430 - prev$1 = type$2;
431 - }
529 +function seeReadOnlySpans() {
530 + sawReadOnlySpans = true;
531 +}
432 532
433 - // W5. A sequence of European terminators adjacent to European
434 - // numbers changes to all European numbers.
435 - // W6. Otherwise, separators and terminators change to Other
436 - // Neutral.
437 - for (var i$4 = 0; i$4 < len; ++i$4) {
438 - var type$3 = types[i$4];
439 - if (type$3 == ",") { types[i$4] = "N"; }
440 - else if (type$3 == "%") {
441 - var end = (void 0);
442 - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
443 - var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
444 - for (var j = i$4; j < end; ++j) { types[j] = replace; }
445 - i$4 = end - 1;
446 - }
447 - }
533 +function seeCollapsedSpans() {
534 + sawCollapsedSpans = true;
535 +}
448 536
449 - // W7. Search backwards from each instance of a European number
450 - // until the first strong type (R, L, or sor) is found. If an L is
451 - // found, then change the type of the European number to L.
452 - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
453 - var type$4 = types[i$5];
454 - if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
455 - else if (isStrong.test(type$4)) { cur$1 = type$4; }
456 - }
537 +// TEXTMARKER SPANS
457 538
458 - // N1. A sequence of neutrals takes the direction of the
459 - // surrounding strong text if the text on both sides has the same
460 - // direction. European and Arabic numbers act as if they were R in
461 - // terms of their influence on neutrals. Start-of-level-run (sor)
462 - // and end-of-level-run (eor) are used at level run boundaries.
463 - // N2. Any remaining neutrals take the embedding direction.
464 - for (var i$6 = 0; i$6 < len; ++i$6) {
465 - if (isNeutral.test(types[i$6])) {
466 - var end$1 = (void 0);
467 - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
468 - var before = (i$6 ? types[i$6-1] : outerType) == "L";
469 - var after = (end$1 < len ? types[end$1] : outerType) == "L";
470 - var replace$1 = before == after ? (before ? "L" : "R") : outerType;
471 - for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
472 - i$6 = end$1 - 1;
473 - }
474 - }
539 +function MarkedSpan(marker, from, to) {
540 + this.marker = marker;
541 + this.from = from; this.to = to;
542 +}
475 543
476 - // Here we depart from the documented algorithm, in order to avoid
477 - // building up an actual levels array. Since there are only three
478 - // levels (0, 1, 2) in an implementation that doesn't take
479 - // explicit embedding into account, we can build up the order on
480 - // the fly, without following the level-based algorithm.
481 - var order = [], m;
482 - for (var i$7 = 0; i$7 < len;) {
483 - if (countsAsLeft.test(types[i$7])) {
484 - var start = i$7;
485 - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
486 - order.push(new BidiSpan(0, start, i$7));
487 - } else {
488 - var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
489 - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
490 - for (var j$2 = pos; j$2 < i$7;) {
491 - if (countsAsNum.test(types[j$2])) {
492 - if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
493 - var nstart = j$2;
494 - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
495 - order.splice(at, 0, new BidiSpan(2, nstart, j$2));
496 - at += isRTL;
497 - pos = j$2;
498 - } else { ++j$2; }
499 - }
500 - if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
501 - }
502 - }
503 - if (direction == "ltr") {
504 - if (order[0].level == 1 && (m = str.match(/^\s+/))) {
505 - order[0].from = m[0].length;
506 - order.unshift(new BidiSpan(0, 0, m[0].length));
507 - }
508 - if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
509 - lst(order).to -= m[0].length;
510 - order.push(new BidiSpan(0, len - m[0].length, len));
511 - }
512 - }
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 +}
513 564
514 - return direction == "rtl" ? order.reverse() : order
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));
515 576 }
516 - })();
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 +}
517 592
518 - // Get the bidi ordering for the given line (and cache it). Returns
519 - // false for lines that are fully left-to-right, and an array of
520 - // BidiSpan objects otherwise.
521 - function getOrder(line, direction) {
522 - var order = line.order;
523 - if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
524 - return order
525 - }
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 }
526 604
527 - // EVENT HANDLING
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);
528 609
529 - // Lightweight event framework. on/off also work on DOM nodes,
530 - // registering native DOM handlers.
531 -
532 - var noHandlers = [];
533 -
534 - var on = function(emitter, type, f) {
535 - if (emitter.addEventListener) {
536 - emitter.addEventListener(type, f, false);
537 - } else if (emitter.attachEvent) {
538 - emitter.attachEvent("on" + type, f);
539 - } else {
540 - var map = emitter._handlers || (emitter._handlers = {});
541 - map[type] = (map[type] || noHandlers).concat(f);
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 + }
542 621 }
543 - };
544 -
545 - function getHandlers(emitter, type) {
546 - return emitter._handlers && emitter._handlers[type] || noHandlers
547 622 }
548 -
549 - function off(emitter, type, f) {
550 - if (emitter.removeEventListener) {
551 - emitter.removeEventListener(type, f, false);
552 - } else if (emitter.detachEvent) {
553 - emitter.detachEvent("on" + type, f);
554 - } else {
555 - var map = emitter._handlers, arr = map && map[type];
556 - if (arr) {
557 - var index = indexOf(arr, f);
558 - if (index > -1)
559 - { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
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); }
560 637 }
561 638 }
562 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); }
563 643
564 - function signal(emitter, type /*, values...*/) {
565 - var handlers = getHandlers(emitter, type);
566 - if (!handlers.length) { return }
567 - var args = Array.prototype.slice.call(arguments, 2);
568 - for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
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);
569 655 }
656 + return newMarkers
657 +}
570 658
571 - // The DOM events that CodeMirror handles can be overridden by
572 - // registering a (non-DOM) handler on the editor for the event name,
573 - // and preventDefault-ing the event in that handler.
574 - function signalDOMEvent(cm, e, override) {
575 - if (typeof e == "string")
576 - { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
577 - signal(cm, override || e.type, cm, e);
578 - return e_defaultPrevented(e) || e.codemirrorIgnore
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); }
579 666 }
667 + if (!spans.length) { return null }
668 + return spans
669 +}
580 670
581 - function signalCursorActivity(cm) {
582 - var arr = cm._handlers && cm._handlers.cursorActivity;
583 - if (!arr) { return }
584 - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
585 - for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
586 - { set.push(arr[i]); } }
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 + }
587 696 }
697 + return parts
698 +}
588 699
589 - function hasHandler(emitter, type) {
590 - return getHandlers(emitter, type).length > 0
591 - }
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 +}
592 714
593 - // Add on and off methods to a constructor's prototype, to make
594 - // registering events on such objects more convenient.
595 - function eventMixin(ctor) {
596 - ctor.prototype.on = function(type, f) {on(this, type, f);};
597 - ctor.prototype.off = function(type, f) {off(this, type, f);};
598 - }
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 }
599 719
600 - // Due to the fact that we still support jurassic IE versions, some
601 - // compatibility wrappers are needed.
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 +}
602 733
603 - function e_preventDefault(e) {
604 - if (e.preventDefault) { e.preventDefault(); }
605 - else { e.returnValue = false; }
606 - }
607 - function e_stopPropagation(e) {
608 - if (e.stopPropagation) { e.stopPropagation(); }
609 - else { e.cancelBubble = true; }
610 - }
611 - function e_defaultPrevented(e) {
612 - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
613 - }
614 - function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
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) }
615 748
616 - function e_target(e) {return e.target || e.srcElement}
617 - function e_button(e) {
618 - var b = e.which;
619 - if (b == null) {
620 - if (e.button & 1) { b = 1; }
621 - else if (e.button & 2) { b = 3; }
622 - else if (e.button & 4) { b = 2; }
623 - }
624 - if (mac && e.ctrlKey && b == 1) { b = 3; }
625 - return b
626 - }
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 +}
627 767
628 - // Detect drag-and-drop
629 - var dragAndDrop = function() {
630 - // There is *some* kind of drag-and-drop support in IE6-8, but I
631 - // couldn't get it to work yet.
632 - if (ie && ie_version < 9) { return false }
633 - var div = elt('div');
634 - return "draggable" in div || "dragDrop" in div
635 - }();
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 +}
636 778
637 - var zwspSupported;
638 - function zeroWidthElement(measure) {
639 - if (zwspSupported == null) {
640 - var test = elt("span", "\u200b");
641 - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
642 - if (measure.firstChild.offsetHeight != 0)
643 - { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
644 - }
645 - var node = zwspSupported ? elt("span", "\u200b") :
646 - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
647 - node.setAttribute("cm-text", "");
648 - return node
649 - }
779 +function visualLineEnd(line) {
780 + var merged;
781 + while (merged = collapsedSpanAtEnd(line))
782 + { line = merged.find(1, true).line; }
783 + return line
784 +}
650 785
651 - // Feature-detect IE's crummy client rect reporting for bidi text
652 - var badBidiRects;
653 - function hasBadBidiRects(measure) {
654 - if (badBidiRects != null) { return badBidiRects }
655 - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
656 - var r0 = range(txt, 0, 1).getBoundingClientRect();
657 - var r1 = range(txt, 1, 2).getBoundingClientRect();
658 - removeChildren(measure);
659 - if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
660 - return badBidiRects = (r1.right - r0.right < 3)
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);
661 793 }
794 + return lines
795 +}
662 796
663 - // See if "".split is the broken IE version, if so, provide an
664 - // alternative way to split lines.
665 - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
666 - var pos = 0, result = [], l = string.length;
667 - while (pos <= l) {
668 - var nl = string.indexOf("\n", pos);
669 - if (nl == -1) { nl = string.length; }
670 - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
671 - var rt = line.indexOf("\r");
672 - if (rt != -1) {
673 - result.push(line.slice(0, rt));
674 - pos += rt + 1;
675 - } else {
676 - result.push(line);
677 - pos = nl + 1;
678 - }
679 - }
680 - return result
681 - } : function (string) { return string.split(/\r\n?|\n/); };
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 +}
682 804
683 - var hasSelection = window.getSelection ? function (te) {
684 - try { return te.selectionStart != te.selectionEnd }
685 - catch(e) { return false }
686 - } : function (te) {
687 - var range;
688 - try {range = te.ownerDocument.selection.createRange();}
689 - catch(e) {}
690 - if (!range || range.parentElement() != te) { return false }
691 - return range.compareEndPoints("StartToEnd", range) != 0
692 - };
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 +}
693 815
694 - var hasCopyEvent = (function () {
695 - var e = elt("div");
696 - if ("oncopy" in e) { return true }
697 - e.setAttribute("oncopy", "return;");
698 - return typeof e.oncopy == "function"
699 - })();
700 -
701 - var badZoomedRects = null;
702 - function hasBadZoomedRects(measure) {
703 - if (badZoomedRects != null) { return badZoomedRects }
704 - var node = removeChildrenAndAdd(measure, elt("span", "x"));
705 - var normal = node.getBoundingClientRect();
706 - var fromRange = range(node, 0, 1).getBoundingClientRect();
707 - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
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))
708 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 +}
709 845
710 - // Known modes, by name and by MIME
711 - var modes = {}, mimeModes = {};
846 +// Find the height above the given line.
847 +function heightAtLine(lineObj) {
848 + lineObj = visualLine(lineObj);
712 849
713 - // Extra arguments are stored as the mode's dependencies, which is
714 - // used by (legacy) mechanisms like loadmode.js to automatically
715 - // load a mode. (Preferred mechanism is the require/define calls.)
716 - function defineMode(name, mode) {
717 - if (arguments.length > 2)
718 - { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
719 - modes[name] = mode;
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; }
720 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 +}
721 865
722 - function defineMIME(mime, spec) {
723 - mimeModes[mime] = spec;
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;
724 876 }
725 -
726 - // Given a MIME type, a {name, ...options} config object, or a name
727 - // string, return a mode config object.
728 - function resolveMode(spec) {
729 - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
730 - spec = mimeModes[spec];
731 - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
732 - var found = mimeModes[spec.name];
733 - if (typeof found == "string") { found = {name: found}; }
734 - spec = createObj(found, spec);
735 - spec.name = found.name;
736 - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
737 - return resolveMode("application/xml")
738 - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
739 - return resolveMode("application/json")
740 - }
741 - if (typeof spec == "string") { return {name: spec} }
742 - else { return spec || {name: "null"} }
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;
743 883 }
884 + return len
885 +}
744 886
745 - // Given a mode spec (anything that resolveMode accepts), find and
746 - // initialize an actual mode object.
747 - function getMode(options, spec) {
748 - spec = resolveMode(spec);
749 - var mfactory = modes[spec.name];
750 - if (!mfactory) { return getMode(options, "text/plain") }
751 - var modeObj = mfactory(options, spec);
752 - if (modeExtensions.hasOwnProperty(spec.name)) {
753 - var exts = modeExtensions[spec.name];
754 - for (var prop in exts) {
755 - if (!exts.hasOwnProperty(prop)) { continue }
756 - if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
757 - modeObj[prop] = exts[prop];
758 - }
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;
759 898 }
760 - modeObj.name = spec.name;
761 - if (spec.helperType) { modeObj.helperType = spec.helperType; }
762 - if (spec.modeProps) { for (var prop$1 in spec.modeProps)
763 - { modeObj[prop$1] = spec.modeProps[prop$1]; } }
899 + });
900 +}
764 901
765 - return modeObj
766 - }
902 +// BIDI HELPERS
767 903
768 - // This can be used to attach properties to mode objects from
769 - // outside the actual mode definition.
770 - var modeExtensions = {};
771 - function extendMode(mode, properties) {
772 - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
773 - copyObj(properties, exts);
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 + }
774 913 }
914 + if (!found) { f(from, to, "ltr"); }
915 +}
775 916
776 - function copyState(mode, state) {
777 - if (state === true) { return state }
778 - if (mode.copyState) { return mode.copyState(state) }
779 - var nstate = {};
780 - for (var n in state) {
781 - var val = state[n];
782 - if (val instanceof Array) { val = val.concat([]); }
783 - nstate[n] = val;
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; }
784 927 }
785 - return nstate
928 + if (cur.from == ch) {
929 + if (cur.from != cur.to && sticky != "before") { found = i; }
930 + else { bidiOther = i; }
931 + }
786 932 }
933 + return found != null ? found : bidiOther
934 +}
787 935
788 - // Given a mode and a state (for that mode), find the inner mode and
789 - // state at the position that the state refers to.
790 - function innerMode(mode, state) {
791 - var info;
792 - while (mode.innerMode) {
793 - info = mode.innerMode(state);
794 - if (!info || info.mode == mode) { break }
795 - state = info.state;
796 - mode = info.mode;
797 - }
798 - return info || {mode: mode, state: state}
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" }
799 972 }
800 973
801 - function startState(mode, a1, a2) {
802 - return mode.startState ? mode.startState(a1, a2) : true
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;
803 980 }
804 981
805 - // STRING STREAM
982 + return function(str, direction) {
983 + var outerType = direction == "ltr" ? "L" : "R";
806 984
807 - // Fed to the mode parsers, provides helper functions to make
808 - // parsers more succinct.
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))); }
809 989
810 - var StringStream = function(string, tabSize, lineOracle) {
811 - this.pos = this.start = 0;
812 - this.string = string;
813 - this.tabSize = tabSize || 8;
814 - this.lastColumnPos = this.lastColumnValue = 0;
815 - this.lineStart = 0;
816 - this.lineOracle = lineOracle;
817 - };
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 + }
818 999
819 - StringStream.prototype.eol = function () {return this.pos >= this.string.length};
820 - StringStream.prototype.sol = function () {return this.pos == this.lineStart};
821 - StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
822 - StringStream.prototype.next = function () {
823 - if (this.pos < this.string.length)
824 - { return this.string.charAt(this.pos++) }
825 - };
826 - StringStream.prototype.eat = function (match) {
827 - var ch = this.string.charAt(this.pos);
828 - var ok;
829 - if (typeof match == "string") { ok = ch == match; }
830 - else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
831 - if (ok) {++this.pos; return ch}
832 - };
833 - StringStream.prototype.eatWhile = function (match) {
834 - var start = this.pos;
835 - while (this.eat(match)){}
836 - return this.pos > start
837 - };
838 - StringStream.prototype.eatSpace = function () {
839 - var start = this.pos;
840 - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
841 - return this.pos > start
842 - };
843 - StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
844 - StringStream.prototype.skipTo = function (ch) {
845 - var found = this.string.indexOf(ch, this.pos);
846 - if (found > -1) {this.pos = found; return true}
847 - };
848 - StringStream.prototype.backUp = function (n) {this.pos -= n;};
849 - StringStream.prototype.column = function () {
850 - if (this.lastColumnPos < this.start) {
851 - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
852 - this.lastColumnPos = this.start;
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"; } }
853 1009 }
854 - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
855 - };
856 - StringStream.prototype.indentation = function () {
857 - return countColumn(this.string, null, this.tabSize) -
858 - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
859 - };
860 - StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
861 - if (typeof pattern == "string") {
862 - var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
863 - var substr = this.string.substr(this.pos, pattern.length);
864 - if (cased(substr) == cased(pattern)) {
865 - if (consume !== false) { this.pos += pattern.length; }
866 - return true
867 - }
868 - } else {
869 - var match = this.string.slice(this.pos).match(pattern);
870 - if (match && match.index > 0) { return null }
871 - if (match && consume !== false) { this.pos += match[0].length; }
872 - return match
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;
873 1020 }
874 - };
875 - StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
876 - StringStream.prototype.hideFirstChars = function (n, inner) {
877 - this.lineStart += n;
878 - try { return inner() }
879 - finally { this.lineStart -= n; }
880 - };
881 - StringStream.prototype.lookAhead = function (n) {
882 - var oracle = this.lineOracle;
883 - return oracle && oracle.lookAhead(n)
884 - };
885 - StringStream.prototype.baseToken = function () {
886 - var oracle = this.lineOracle;
887 - return oracle && oracle.baseToken(this.pos)
888 - };
889 1021
890 - // Find the line object corresponding to the given line number.
891 - function getLine(doc, n) {
892 - n -= doc.first;
893 - if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
894 - var chunk = doc;
895 - while (!chunk.lines) {
896 - for (var i = 0;; ++i) {
897 - var child = chunk.children[i], sz = child.chunkSize();
898 - if (n < sz) { chunk = child; break }
899 - n -= sz;
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;
900 1035 }
901 1036 }
902 - return chunk.lines[n]
903 - }
904 1037
905 - // Get the part of a document between two positions, as an array of
906 - // strings.
907 - function getBetween(doc, start, end) {
908 - var out = [], n = start.line;
909 - doc.iter(start.line, end.line + 1, function (line) {
910 - var text = line.text;
911 - if (n == end.line) { text = text.slice(0, end.ch); }
912 - if (n == start.line) { text = text.slice(start.ch); }
913 - out.push(text);
914 - ++n;
915 - });
916 - return out
917 - }
918 - // Get the lines between from and to, as array of strings.
919 - function getLines(doc, from, to) {
920 - var out = [];
921 - doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
922 - return out
923 - }
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 + }
924 1046
925 - // Update the height of a line, propagating the height change
926 - // upwards to parent nodes.
927 - function updateLineHeight(line, height) {
928 - var diff = height - line.height;
929 - if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
930 - }
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 + }
931 1064
932 - // Given a line object, find its line number by walking up through
933 - // its parent links.
934 - function lineNo(line) {
935 - if (line.parent == null) { return null }
936 - var cur = line.parent, no = indexOf(cur.lines, line);
937 - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
938 - for (var i = 0;; ++i) {
939 - if (chunk.children[i] == cur) { break }
940 - no += chunk.children[i].chunkSize();
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)); }
941 1089 }
942 1090 }
943 - return no + cur.first
944 - }
945 -
946 - // Find the line at the given vertical position, using the height
947 - // information in the document tree.
948 - function lineAtHeight(chunk, h) {
949 - var n = chunk.first;
950 - outer: do {
951 - for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
952 - var child = chunk.children[i$1], ch = child.height;
953 - if (h < ch) { chunk = child; continue outer }
954 - h -= ch;
955 - n += child.chunkSize();
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));
956 1095 }
957 - return n
958 - } while (!chunk.lines)
959 - var i = 0;
960 - for (; i < chunk.lines.length; ++i) {
961 - var line = chunk.lines[i], lh = line.height;
962 - if (h < lh) { break }
963 - h -= lh;
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 + }
964 1100 }
965 - return n + i
1101 +
1102 + return direction == "rtl" ? order.reverse() : order
966 1103 }
1104 +})();
967 1105
968 - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
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 +}
969 1114
970 - function lineNumberFor(options, i) {
971 - return String(options.lineNumberFormatter(i + options.firstLineNumber))
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);
972 1130 }
1131 +};
973 1132
974 - // A Pos instance represents a position within the text.
975 - function Pos(line, ch, sticky) {
976 - if ( sticky === void 0 ) sticky = null;
1133 +function getHandlers(emitter, type) {
1134 + return emitter._handlers && emitter._handlers[type] || noHandlers
1135 +}
977 1136
978 - if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
979 - this.line = line;
980 - this.ch = ch;
981 - this.sticky = sticky;
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 + }
982 1149 }
1150 +}
983 1151
984 - // Compare two positions, return 0 if they are the same, a negative
985 - // number when a is less, and a positive number otherwise.
986 - function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
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 +}
987 1158
988 - function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
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 +}
989 1168
990 - function copyPos(x) {return Pos(x.line, x.ch)}
991 - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
992 - function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
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 +}
993 1176
994 - // Most of the external API clips given positions to make sure they
995 - // actually exist within the document.
996 - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
997 - function clipPos(doc, pos) {
998 - if (pos.line < doc.first) { return Pos(doc.first, 0) }
999 - var last = doc.first + doc.size - 1;
1000 - if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
1001 - return clipToLen(pos, getLine(doc, pos.line).text.length)
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; }
1002 1211 }
1003 - function clipToLen(pos, linelen) {
1004 - var ch = pos.ch;
1005 - if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
1006 - else if (ch < 0) { return Pos(pos.line, 0) }
1007 - else { return pos }
1008 - }
1009 - function clipPosArray(doc, array) {
1010 - var out = [];
1011 - for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
1012 - return out
1013 - }
1212 + if (mac && e.ctrlKey && b == 1) { b = 3; }
1213 + return b
1214 +}
1014 1215
1015 - var SavedContext = function(state, lookAhead) {
1016 - this.state = state;
1017 - this.lookAhead = lookAhead;
1018 - };
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 +}();
1019 1224
1020 - var Context = function(doc, state, line, lookAhead) {
1021 - this.state = state;
1022 - this.doc = doc;
1023 - this.line = line;
1024 - this.maxLookAhead = lookAhead || 0;
1025 - this.baseTokens = null;
1026 - this.baseTokenPos = 1;
1027 - };
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 +}
1028 1238
1029 - Context.prototype.lookAhead = function (n) {
1030 - var line = this.doc.getLine(this.line + n);
1031 - if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
1032 - return line
1033 - };
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 +}
1034 1250
1035 - Context.prototype.baseToken = function (n) {
1036 - if (!this.baseTokens) { return null }
1037 - while (this.baseTokens[this.baseTokenPos] <= n)
1038 - { this.baseTokenPos += 2; }
1039 - var type = this.baseTokens[this.baseTokenPos + 1];
1040 - return {type: type && type.replace(/( |^)overlay .*/, ""),
1041 - size: this.baseTokens[this.baseTokenPos] - n}
1042 - };
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/); };
1043 1270
1044 - Context.prototype.nextLine = function () {
1045 - this.line++;
1046 - if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1047 - };
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 +};
1048 1281
1049 - Context.fromSaved = function (doc, saved, line) {
1050 - if (saved instanceof SavedContext)
1051 - { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
1052 - else
1053 - { return new Context(doc, copyState(doc.mode, saved), line) }
1054 - };
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 +})();
1055 1288
1056 - Context.prototype.save = function (copy) {
1057 - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
1058 - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
1059 - };
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 +}
1060 1297
1298 +// Known modes, by name and by MIME
1299 +var modes = {};
1300 +var mimeModes = {};
1061 1301
1062 - // Compute a style array (an array starting with a mode generation
1063 - // -- for invalidation -- followed by pairs of end positions and
1064 - // style strings), which is used to highlight the tokens on the
1065 - // line.
1066 - function highlightLine(cm, line, context, forceToEnd) {
1067 - // A styles array always starts with a number identifying the
1068 - // mode/overlays that it is based on (for easy invalidation).
1069 - var st = [cm.state.modeGen], lineClasses = {};
1070 - // Compute the base array of styles
1071 - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
1072 - lineClasses, forceToEnd);
1073 - var state = context.state;
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 +}
1074 1310
1075 - // Run overlays, adjust style array.
1076 - var loop = function ( o ) {
1077 - context.baseTokens = st;
1078 - var overlay = cm.state.overlays[o], i = 1, at = 0;
1079 - context.state = true;
1080 - runMode(cm, line.text, overlay.mode, context, function (end, style) {
1081 - var start = i;
1082 - // Ensure there's a token end at the current position, and that i points at it
1083 - while (at < end) {
1084 - var i_end = st[i];
1085 - if (i_end > end)
1086 - { st.splice(i, 1, end, st[i+1], i_end); }
1087 - i += 2;
1088 - at = Math.min(end, i_end);
1089 - }
1090 - if (!style) { return }
1091 - if (overlay.opaque) {
1092 - st.splice(start, i - start, end, "overlay " + style);
1093 - i = start + 2;
1094 - } else {
1095 - for (; start < i; start += 2) {
1096 - var cur = st[start+1];
1097 - st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
1098 - }
1099 - }
1100 - }, lineClasses);
1101 - context.state = state;
1102 - context.baseTokens = null;
1103 - context.baseTokenPos = 1;
1104 - };
1311 +function defineMIME(mime, spec) {
1312 + mimeModes[mime] = spec;
1313 +}
1105 1314
1106 - for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1107 -
1108 - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
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")
1109 1329 }
1330 + if (typeof spec == "string") { return {name: spec} }
1331 + else { return spec || {name: "null"} }
1332 +}
1110 1333
1111 - function getLineStyles(cm, line, updateFrontier) {
1112 - if (!line.styles || line.styles[0] != cm.state.modeGen) {
1113 - var context = getContextBefore(cm, lineNo(line));
1114 - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
1115 - var result = highlightLine(cm, line, context);
1116 - if (resetState) { context.state = resetState; }
1117 - line.stateAfter = context.save(!resetState);
1118 - line.styles = result.styles;
1119 - if (result.classes) { line.styleClasses = result.classes; }
1120 - else if (line.styleClasses) { line.styleClasses = null; }
1121 - if (updateFrontier === cm.doc.highlightFrontier)
1122 - { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
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];
1123 1347 }
1124 - return line.styles
1125 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]; } }
1126 1353
1127 - function getContextBefore(cm, n, precise) {
1128 - var doc = cm.doc, display = cm.display;
1129 - if (!doc.mode.startState) { return new Context(doc, true, n) }
1130 - var start = findStartLine(cm, n, precise);
1131 - var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
1132 - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
1354 + return modeObj
1355 +}
1133 1356
1134 - doc.iter(start, n, function (line) {
1135 - processLine(cm, line.text, context);
1136 - var pos = context.line;
1137 - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
1138 - context.nextLine();
1139 - });
1140 - if (precise) { doc.modeFrontier = context.line; }
1141 - return context
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;
1142 1373 }
1374 + return nstate
1375 +}
1143 1376
1144 - // Lightweight form of highlight -- proceed over this line and
1145 - // update state, but don't save a style array. Used for lines that
1146 - // aren't currently visible.
1147 - function processLine(cm, text, context, startAt) {
1148 - var mode = cm.doc.mode;
1149 - var stream = new StringStream(text, cm.options.tabSize, context);
1150 - stream.start = stream.pos = startAt || 0;
1151 - if (text == "") { callBlankLine(mode, context.state); }
1152 - while (!stream.eol()) {
1153 - readToken(mode, stream, context.state);
1154 - stream.start = stream.pos;
1155 - }
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;
1156 1386 }
1387 + return info || {mode: mode, state: state}
1388 +}
1157 1389
1158 - function callBlankLine(mode, state) {
1159 - if (mode.blankLine) { return mode.blankLine(state) }
1160 - if (!mode.innerMode) { return }
1161 - var inner = innerMode(mode, state);
1162 - if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
1163 - }
1390 +function startState(mode, a1, a2) {
1391 + return mode.startState ? mode.startState(a1, a2) : true
1392 +}
1164 1393
1165 - function readToken(mode, stream, state, inner) {
1166 - for (var i = 0; i < 10; i++) {
1167 - if (inner) { inner[0] = innerMode(mode, state).mode; }
1168 - var style = mode.token(stream, state);
1169 - if (stream.pos > stream.start) { return style }
1170 - }
1171 - throw new Error("Mode " + mode.name + " failed to advance stream.")
1172 - }
1394 +// STRING STREAM
1173 1395
1174 - var Token = function(stream, type, state) {
1175 - this.start = stream.start; this.end = stream.pos;
1176 - this.string = stream.current();
1177 - this.type = type || null;
1178 - this.state = state;
1179 - };
1396 +// Fed to the mode parsers, provides helper functions to make
1397 +// parsers more succinct.
1180 1398
1181 - // Utility for getTokenAt and getLineTokens
1182 - function takeToken(cm, pos, precise, asArray) {
1183 - var doc = cm.doc, mode = doc.mode, style;
1184 - pos = clipPos(doc, pos);
1185 - var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
1186 - var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
1187 - if (asArray) { tokens = []; }
1188 - while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
1189 - stream.start = stream.pos;
1190 - style = readToken(mode, stream, context.state);
1191 - if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
1192 - }
1193 - return asArray ? tokens : new Token(stream, style, context.state)
1194 - }
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 +};
1195 1407
1196 - function extractLineClasses(type, output) {
1197 - if (type) { for (;;) {
1198 - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
1199 - if (!lineClass) { break }
1200 - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
1201 - var prop = lineClass[1] ? "bgClass" : "textClass";
1202 - if (output[prop] == null)
1203 - { output[prop] = lineClass[2]; }
1204 - else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
1205 - { output[prop] += " " + lineClass[2]; }
1206 - } }
1207 - return type
1208 - }
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;
1209 1429
1210 - // Run the given mode's parser over a line, calling f for each token.
1211 - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
1212 - var flattenSpans = mode.flattenSpans;
1213 - if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
1214 - var curStart = 0, curStyle = null;
1215 - var stream = new StringStream(text, cm.options.tabSize, context), style;
1216 - var inner = cm.options.addModeClass && [null];
1217 - if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
1218 - while (!stream.eol()) {
1219 - if (stream.pos > cm.options.maxHighlightLength) {
1220 - flattenSpans = false;
1221 - if (forceToEnd) { processLine(cm, text, context, stream.pos); }
1222 - stream.pos = text.length;
1223 - style = null;
1224 - } else {
1225 - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
1226 - }
1227 - if (inner) {
1228 - var mName = inner[0].name;
1229 - if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
1230 - }
1231 - if (!flattenSpans || curStyle != style) {
1232 - while (curStart < stream.start) {
1233 - curStart = Math.min(stream.start, curStart + 5000);
1234 - f(curStart, curStyle);
1235 - }
1236 - curStyle = style;
1237 - }
1238 - stream.start = stream.pos;
1239 - }
1240 - while (curStart < stream.pos) {
1241 - // Webkit seems to refuse to render text nodes longer than 57444
1242 - // characters, and returns inaccurate measurements in nodes
1243 - // starting around 5000 chars.
1244 - var pos = Math.min(stream.pos, curStart + 5000);
1245 - f(pos, curStyle);
1246 - curStart = pos;
1247 - }
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;
1248 1444 }
1249 -
1250 - // Finds the line to start with when starting a parse. Tries to
1251 - // find a line with a stateAfter, so that it can start with a
1252 - // valid state. If that fails, it returns the line with the
1253 - // smallest indentation, which tends to need the least context to
1254 - // parse correctly.
1255 - function findStartLine(cm, n, precise) {
1256 - var minindent, minline, doc = cm.doc;
1257 - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1258 - for (var search = n; search > lim; --search) {
1259 - if (search <= doc.first) { return doc.first }
1260 - var line = getLine(doc, search - 1), after = line.stateAfter;
1261 - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
1262 - { return search }
1263 - var indented = countColumn(line.text, null, cm.options.tabSize);
1264 - if (minline == null || minindent > indented) {
1265 - minline = search - 1;
1266 - minindent = indented;
1267 - }
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
1268 1458 }
1269 - return minline
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
1270 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 +};
1271 1480
1272 - function retreatFrontier(doc, n) {
1273 - doc.modeFrontier = Math.min(doc.modeFrontier, n);
1274 - if (doc.highlightFrontier < n - 10) { return }
1275 - var start = doc.first;
1276 - for (var line = n - 1; line > start; line--) {
1277 - var saved = getLine(doc, line).stateAfter;
1278 - // change is on 3
1279 - // state on line 1 looked ahead 2 -- so saw 3
1280 - // test 1 + 2 < 3 should cover this
1281 - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
1282 - start = line + 1;
1283 - break
1284 - }
1285 - }
1286 - doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1287 - }
1481 +var SavedContext = function(state, lookAhead) {
1482 + this.state = state;
1483 + this.lookAhead = lookAhead;
1484 +};
1288 1485
1289 - // Optimize some code when these features are not used.
1290 - var sawReadOnlySpans = false, sawCollapsedSpans = false;
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 +};
1291 1494
1292 - function seeReadOnlySpans() {
1293 - sawReadOnlySpans = true;
1294 - }
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 +};
1295 1500
1296 - function seeCollapsedSpans() {
1297 - sawCollapsedSpans = true;
1298 - }
1501 +Context.prototype.baseToken = function (n) {
1502 + var this$1 = this;
1299 1503
1300 - // TEXTMARKER SPANS
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 +};
1301 1511
1302 - function MarkedSpan(marker, from, to) {
1303 - this.marker = marker;
1304 - this.from = from; this.to = to;
1305 - }
1512 +Context.prototype.nextLine = function () {
1513 + this.line++;
1514 + if (this.maxLookAhead > 0) { this.maxLookAhead--; }
1515 +};
1306 1516
1307 - // Search an array of spans for a span matching the given marker.
1308 - function getMarkedSpanFor(spans, marker) {
1309 - if (spans) { for (var i = 0; i < spans.length; ++i) {
1310 - var span = spans[i];
1311 - if (span.marker == marker) { return span }
1312 - } }
1313 - }
1314 - // Remove a span from an array, returning undefined if no spans are
1315 - // left (we don't store arrays for lines without spans).
1316 - function removeMarkedSpan(spans, span) {
1317 - var r;
1318 - for (var i = 0; i < spans.length; ++i)
1319 - { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
1320 - return r
1321 - }
1322 - // Add a span to a line.
1323 - function addMarkedSpan(line, span) {
1324 - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
1325 - span.marker.attachLine(line);
1326 - }
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 +};
1327 1523
1328 - // Used for the algorithm that adjusts markers for a change in the
1329 - // document. These functions cut an array of spans at a given
1330 - // character position, returning an array of remaining chunks (or
1331 - // undefined if nothing remains).
1332 - function markedSpansBefore(old, startCh, isInsert) {
1333 - var nw;
1334 - if (old) { for (var i = 0; i < old.length; ++i) {
1335 - var span = old[i], marker = span.marker;
1336 - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
1337 - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
1338 - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
1339 - ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
1340 - }
1341 - } }
1342 - return nw
1343 - }
1344 - function markedSpansAfter(old, endCh, isInsert) {
1345 - var nw;
1346 - if (old) { for (var i = 0; i < old.length; ++i) {
1347 - var span = old[i], marker = span.marker;
1348 - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
1349 - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
1350 - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
1351 - ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
1352 - span.to == null ? null : span.to - endCh));
1353 - }
1354 - } }
1355 - return nw
1356 - }
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 +};
1357 1528
1358 - // Given a change object, compute the new set of marker spans that
1359 - // cover the line in which the change took place. Removes spans
1360 - // entirely within the change, reconnects spans belonging to the
1361 - // same marker that appear on both sides of the change, and cuts off
1362 - // spans partially within the change. Returns an array of span
1363 - // arrays with one element for each line in (after) the change.
1364 - function stretchSpansOverChange(doc, change) {
1365 - if (change.full) { return null }
1366 - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
1367 - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
1368 - if (!oldFirst && !oldLast) { return null }
1369 1529
1370 - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
1371 - // Get the spans that 'stick out' on both sides
1372 - var first = markedSpansBefore(oldFirst, startCh, isInsert);
1373 - var last = markedSpansAfter(oldLast, endCh, isInsert);
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;
1374 1542
1375 - // Next, merge those two ends
1376 - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
1377 - if (first) {
1378 - // Fix up .to properties of first
1379 - for (var i = 0; i < first.length; ++i) {
1380 - var span = first[i];
1381 - if (span.to == null) {
1382 - var found = getMarkedSpanFor(last, span.marker);
1383 - if (!found) { span.to = startCh; }
1384 - else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
1385 - }
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);
1386 1557 }
1387 - }
1388 - if (last) {
1389 - // Fix up .from in last (or move them into first in case of sameLine)
1390 - for (var i$1 = 0; i$1 < last.length; ++i$1) {
1391 - var span$1 = last[i$1];
1392 - if (span$1.to != null) { span$1.to += offset; }
1393 - if (span$1.from == null) {
1394 - var found$1 = getMarkedSpanFor(first, span$1.marker);
1395 - if (!found$1) {
1396 - span$1.from = offset;
1397 - if (sameLine) { (first || (first = [])).push(span$1); }
1398 - }
1399 - } else {
1400 - span$1.from += offset;
1401 - if (sameLine) { (first || (first = [])).push(span$1); }
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;
1402 1566 }
1403 1567 }
1404 - }
1405 - // Make sure we didn't create any zero-length spans
1406 - if (first) { first = clearEmptySpans(first); }
1407 - if (last && last != first) { last = clearEmptySpans(last); }
1568 + }, lineClasses);
1569 + context.state = state;
1570 + context.baseTokens = null;
1571 + context.baseTokenPos = 1;
1572 + };
1408 1573
1409 - var newMarkers = [first];
1410 - if (!sameLine) {
1411 - // Fill gap with whole-line-spans
1412 - var gap = change.text.length - 2, gapMarkers;
1413 - if (gap > 0 && first)
1414 - { for (var i$2 = 0; i$2 < first.length; ++i$2)
1415 - { if (first[i$2].to == null)
1416 - { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
1417 - for (var i$3 = 0; i$3 < gap; ++i$3)
1418 - { newMarkers.push(gapMarkers); }
1419 - newMarkers.push(last);
1420 - }
1421 - return newMarkers
1422 - }
1574 + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
1423 1575
1424 - // Remove spans that are empty and don't have a clearWhenEmpty
1425 - // option of false.
1426 - function clearEmptySpans(spans) {
1427 - for (var i = 0; i < spans.length; ++i) {
1428 - var span = spans[i];
1429 - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
1430 - { spans.splice(i--, 1); }
1431 - }
1432 - if (!spans.length) { return null }
1433 - return spans
1434 - }
1576 + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
1577 +}
1435 1578
1436 - // Used to 'clip' out readOnly ranges when making a change.
1437 - function removeReadOnlyRanges(doc, from, to) {
1438 - var markers = null;
1439 - doc.iter(from.line, to.line + 1, function (line) {
1440 - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
1441 - var mark = line.markedSpans[i].marker;
1442 - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
1443 - { (markers || (markers = [])).push(mark); }
1444 - } }
1445 - });
1446 - if (!markers) { return null }
1447 - var parts = [{from: from, to: to}];
1448 - for (var i = 0; i < markers.length; ++i) {
1449 - var mk = markers[i], m = mk.find(0);
1450 - for (var j = 0; j < parts.length; ++j) {
1451 - var p = parts[j];
1452 - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
1453 - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
1454 - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
1455 - { newParts.push({from: p.from, to: m.from}); }
1456 - if (dto > 0 || !mk.inclusiveRight && !dto)
1457 - { newParts.push({from: m.to, to: p.to}); }
1458 - parts.splice.apply(parts, newParts);
1459 - j += newParts.length - 3;
1460 - }
1461 - }
1462 - return parts
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); }
1463 1591 }
1592 + return line.styles
1593 +}
1464 1594
1465 - // Connect or disconnect spans from a line.
1466 - function detachMarkedSpans(line) {
1467 - var spans = line.markedSpans;
1468 - if (!spans) { return }
1469 - for (var i = 0; i < spans.length; ++i)
1470 - { spans[i].marker.detachLine(line); }
1471 - line.markedSpans = null;
1472 - }
1473 - function attachMarkedSpans(line, spans) {
1474 - if (!spans) { return }
1475 - for (var i = 0; i < spans.length; ++i)
1476 - { spans[i].marker.attachLine(line); }
1477 - line.markedSpans = spans;
1478 - }
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);
1479 1601
1480 - // Helpers used when computing which overlapping collapsed span
1481 - // counts as the larger one.
1482 - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
1483 - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
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 +}
1484 1611
1485 - // Returns a number indicating which of two overlapping collapsed
1486 - // spans is larger (and thus includes the other). Falls back to
1487 - // comparing ids when the spans cover exactly the same range.
1488 - function compareCollapsedMarkers(a, b) {
1489 - var lenDiff = a.lines.length - b.lines.length;
1490 - if (lenDiff != 0) { return lenDiff }
1491 - var aPos = a.find(), bPos = b.find();
1492 - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
1493 - if (fromCmp) { return -fromCmp }
1494 - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
1495 - if (toCmp) { return toCmp }
1496 - return b.id - a.id
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;
1497 1623 }
1624 +}
1498 1625
1499 - // Find out whether a line ends or starts in a collapsed span. If
1500 - // so, return the marker for that span.
1501 - function collapsedSpanAtSide(line, start) {
1502 - var sps = sawCollapsedSpans && line.markedSpans, found;
1503 - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1504 - sp = sps[i];
1505 - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
1506 - (!found || compareCollapsedMarkers(found, sp.marker) < 0))
1507 - { found = sp.marker; }
1508 - } }
1509 - return found
1510 - }
1511 - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
1512 - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
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 +}
1513 1632
1514 - function collapsedSpanAround(line, ch) {
1515 - var sps = sawCollapsedSpans && line.markedSpans, found;
1516 - if (sps) { for (var i = 0; i < sps.length; ++i) {
1517 - var sp = sps[i];
1518 - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
1519 - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
1520 - } }
1521 - return found
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 }
1522 1638 }
1639 + throw new Error("Mode " + mode.name + " failed to advance stream.")
1640 +}
1523 1641
1524 - // Test whether there exists a collapsed span that partially
1525 - // overlaps (covers the start or end, but not both) of a new span.
1526 - // Such overlap is not allowed.
1527 - function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
1528 - var line = getLine(doc, lineNo);
1529 - var sps = sawCollapsedSpans && line.markedSpans;
1530 - if (sps) { for (var i = 0; i < sps.length; ++i) {
1531 - var sp = sps[i];
1532 - if (!sp.marker.collapsed) { continue }
1533 - var found = sp.marker.find(0);
1534 - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
1535 - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
1536 - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
1537 - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
1538 - fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
1539 - { return true }
1540 - } }
1541 - }
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 +};
1542 1648
1543 - // A visual line is a line as drawn on the screen. Folding, for
1544 - // example, can cause multiple logical lines to appear on the same
1545 - // visual line. This finds the start of the visual line that the
1546 - // given line is part of (usually that is the line itself).
1547 - function visualLine(line) {
1548 - var merged;
1549 - while (merged = collapsedSpanAtStart(line))
1550 - { line = merged.find(-1, true).line; }
1551 - return line
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))); }
1552 1660 }
1661 + return asArray ? tokens : new Token(stream, style, context.state)
1662 +}
1553 1663
1554 - function visualLineEnd(line) {
1555 - var merged;
1556 - while (merged = collapsedSpanAtEnd(line))
1557 - { line = merged.find(1, true).line; }
1558 - return line
1559 - }
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 +}
1560 1677
1561 - // Returns an array of logical lines that continue the visual line
1562 - // started by the argument, or undefined if there are no such lines.
1563 - function visualLineContinued(line) {
1564 - var merged, lines;
1565 - while (merged = collapsedSpanAtEnd(line)) {
1566 - line = merged.find(1, true).line
1567 - ;(lines || (lines = [])).push(line);
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);
1568 1694 }
1569 - return lines
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;
1570 1707 }
1571 -
1572 - // Get the line number of the start of the visual line that the
1573 - // given line number is part of.
1574 - function visualLineNo(doc, lineN) {
1575 - var line = getLine(doc, lineN), vis = visualLine(line);
1576 - if (line == vis) { return lineN }
1577 - return lineNo(vis)
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;
1578 1715 }
1716 +}
1579 1717
1580 - // Get the line number of the start of the next visual line after
1581 - // the given line.
1582 - function visualLineEndNo(doc, lineN) {
1583 - if (lineN > doc.lastLine()) { return lineN }
1584 - var line = getLine(doc, lineN), merged;
1585 - if (!lineIsHidden(doc, line)) { return lineN }
1586 - while (merged = collapsedSpanAtEnd(line))
1587 - { line = merged.find(1, true).line; }
1588 - return lineNo(line) + 1
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 + }
1589 1736 }
1737 + return minline
1738 +}
1590 1739
1591 - // Compute whether a line is hidden. Lines count as hidden when they
1592 - // are part of a visual line that starts with another line, or when
1593 - // they are entirely covered by collapsed, non-widget span.
1594 - function lineIsHidden(doc, line) {
1595 - var sps = sawCollapsedSpans && line.markedSpans;
1596 - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
1597 - sp = sps[i];
1598 - if (!sp.marker.collapsed) { continue }
1599 - if (sp.from == null) { return true }
1600 - if (sp.marker.widgetNode) { continue }
1601 - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
1602 - { return true }
1603 - } }
1604 - }
1605 - function lineIsHiddenInner(doc, line, span) {
1606 - if (span.to == null) {
1607 - var end = span.marker.find(1, true);
1608 - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
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
1609 1752 }
1610 - if (span.marker.inclusiveRight && span.to == line.text.length)
1611 - { return true }
1612 - for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
1613 - sp = line.markedSpans[i];
1614 - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
1615 - (sp.to == null || sp.to != span.from) &&
1616 - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
1617 - lineIsHiddenInner(doc, line, sp)) { return true }
1618 - }
1619 1753 }
1754 + doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
1755 +}
1620 1756
1621 - // Find the height above the given line.
1622 - function heightAtLine(lineObj) {
1623 - lineObj = visualLine(lineObj);
1757 +// LINE DATA STRUCTURE
1624 1758
1625 - var h = 0, chunk = lineObj.parent;
1626 - for (var i = 0; i < chunk.lines.length; ++i) {
1627 - var line = chunk.lines[i];
1628 - if (line == lineObj) { break }
1629 - else { h += line.height; }
1630 - }
1631 - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
1632 - for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
1633 - var cur = p.children[i$1];
1634 - if (cur == chunk) { break }
1635 - else { h += cur.height; }
1636 - }
1637 - }
1638 - return h
1639 - }
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 +};
1640 1766
1641 - // Compute the character length of a line, taking into account
1642 - // collapsed ranges (see markText) that might hide parts, and join
1643 - // other lines onto it.
1644 - function lineLength(line) {
1645 - if (line.height == 0) { return 0 }
1646 - var len = line.text.length, merged, cur = line;
1647 - while (merged = collapsedSpanAtStart(cur)) {
1648 - var found = merged.find(0, true);
1649 - cur = found.from.line;
1650 - len += found.from.ch - found.to.ch;
1651 - }
1652 - cur = line;
1653 - while (merged = collapsedSpanAtEnd(cur)) {
1654 - var found$1 = merged.find(0, true);
1655 - len -= cur.text.length - found$1.from.ch;
1656 - cur = found$1.to.line;
1657 - len += cur.text.length - found$1.to.ch;
1658 - }
1659 - return len
1660 - }
1767 +Line.prototype.lineNo = function () { return lineNo(this) };
1768 +eventMixin(Line);
1661 1769
1662 - // Find the longest line in the document.
1663 - function findMaxLine(cm) {
1664 - var d = cm.display, doc = cm.doc;
1665 - d.maxLine = getLine(doc, doc.first);
1666 - d.maxLineLength = lineLength(d.maxLine);
1667 - d.maxLineChanged = true;
1668 - doc.iter(function (line) {
1669 - var len = lineLength(line);
1670 - if (len > d.maxLineLength) {
1671 - d.maxLineLength = len;
1672 - d.maxLine = line;
1673 - }
1674 - });
1675 - }
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 +}
1676 1783
1677 - // LINE DATA STRUCTURE
1784 +// Detach a line from the document tree and its markers.
1785 +function cleanUpLine(line) {
1786 + line.parent = null;
1787 + detachMarkedSpans(line);
1788 +}
1678 1789
1679 - // Line objects. These hold state related to a line, including
1680 - // highlighting info (the styles array).
1681 - var Line = function(text, markedSpans, estimateHeight) {
1682 - this.text = text;
1683 - attachMarkedSpans(this, markedSpans);
1684 - this.height = estimateHeight ? estimateHeight(this) : 1;
1685 - };
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 +}
1686 1801
1687 - Line.prototype.lineNo = function () { return lineNo(this) };
1688 - eventMixin(Line);
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 = {};
1689 1817
1690 - // Change the content (text, markers) of a line. Automatically
1691 - // invalidates cached information and tries to re-estimate the
1692 - // line's height.
1693 - function updateLine(line, text, markedSpans, estimateHeight) {
1694 - line.text = text;
1695 - if (line.stateAfter) { line.stateAfter = null; }
1696 - if (line.styles) { line.styles = null; }
1697 - if (line.order != null) { line.order = null; }
1698 - detachMarkedSpans(line);
1699 - attachMarkedSpans(line, markedSpans);
1700 - var estHeight = estimateHeight ? estimateHeight(line) : 1;
1701 - if (estHeight != line.height) { updateLineHeight(line, estHeight); }
1702 - }
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 + }
1703 1836
1704 - // Detach a line from the document tree and its markers.
1705 - function cleanUpLine(line) {
1706 - line.parent = null;
1707 - detachMarkedSpans(line);
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 + }
1708 1849 }
1709 1850
1710 - // Convert a style as returned by a mode (either null, or a string
1711 - // containing one or more styles) to a CSS style. This is cached,
1712 - // and also looks for line-wide styles.
1713 - var styleToClassCache = {}, styleToClassCacheWithMode = {};
1714 - function interpretTokenStyle(style, options) {
1715 - if (!style || /^\s*$/.test(style)) { return null }
1716 - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
1717 - return cache[style] ||
1718 - (cache[style] = style.replace(/\S+/g, "cm-$&"))
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"; }
1719 1856 }
1720 1857
1721 - // Render the DOM representation of the text of a line. Also builds
1722 - // up a 'line map', which points at the DOM nodes that represent
1723 - // specific stretches of text, and is used by the measuring code.
1724 - // The returned object contains the DOM node, this map, and
1725 - // information about line-wide styles that were set by the mode.
1726 - function buildLineContent(cm, lineView) {
1727 - // The padding-right forces the element to have a 'border', which
1728 - // is needed on Webkit to be able to get line-level bounding
1729 - // rectangles for it (in measureChar).
1730 - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
1731 - var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
1732 - col: 0, pos: 0, cm: cm,
1733 - trailingSpace: false,
1734 - splitSpaces: cm.getOption("lineWrapping")};
1735 - lineView.measure = {};
1858 + signal(cm, "renderLine", cm, lineView.line, builder.pre);
1859 + if (builder.pre.className)
1860 + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1736 1861
1737 - // Iterate over the logical lines that make up this visual line.
1738 - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
1739 - var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
1740 - builder.pos = 0;
1741 - builder.addToken = buildToken;
1742 - // Optionally wire in some hacks into the token-rendering
1743 - // algorithm, to deal with browser quirks.
1744 - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
1745 - { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
1746 - builder.map = [];
1747 - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
1748 - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
1749 - if (line.styleClasses) {
1750 - if (line.styleClasses.bgClass)
1751 - { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
1752 - if (line.styleClasses.textClass)
1753 - { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
1754 - }
1862 + return builder
1863 +}
1755 1864
1756 - // Ensure at least a single node is present, for measuring.
1757 - if (builder.map.length == 0)
1758 - { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
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 +}
1759 1871
1760 - // Store the map and a cache object for the current logical line
1761 - if (i == 0) {
1762 - lineView.measure.map = builder.map;
1763 - lineView.measure.cache = {};
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;
1764 1913 } else {
1765 - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
1766 - ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
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;
1767 1919 }
1920 + builder.map.push(builder.pos, builder.pos + 1, txt$1);
1921 + builder.pos++;
1768 1922 }
1769 -
1770 - // See issue #2901
1771 - if (webkit) {
1772 - var last = builder.content.lastChild;
1773 - if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
1774 - { builder.content.className = "cm-tab-wrap-hack"; }
1775 - }
1776 -
1777 - signal(cm, "renderLine", cm, lineView.line, builder.pre);
1778 - if (builder.pre.className)
1779 - { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
1780 -
1781 - return builder
1782 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 +}
1783 1935
1784 - function defaultSpecialCharPlaceholder(ch) {
1785 - var token = elt("span", "\u2022", "cm-invalidchar");
1786 - token.title = "\\u" + ch.charCodeAt(0).toString(16);
1787 - token.setAttribute("aria-label", token.title);
1788 - return token
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 == " ";
1789 1945 }
1946 + return result
1947 +}
1790 1948
1791 - // Build up the DOM representation for a single token, and add it to
1792 - // the line map. Takes care to render special characters separately.
1793 - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
1794 - if (!text) { return }
1795 - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
1796 - var special = builder.cm.state.specialChars, mustWrap = false;
1797 - var content;
1798 - if (!special.test(text)) {
1799 - builder.col += text.length;
1800 - content = document.createTextNode(displayText);
1801 - builder.map.push(builder.pos, builder.pos + text.length, content);
1802 - if (ie && ie_version < 9) { mustWrap = true; }
1803 - builder.pos += text.length;
1804 - } else {
1805 - content = document.createDocumentFragment();
1806 - var pos = 0;
1807 - while (true) {
1808 - special.lastIndex = pos;
1809 - var m = special.exec(text);
1810 - var skipped = m ? m.index - pos : text.length - pos;
1811 - if (skipped) {
1812 - var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
1813 - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
1814 - else { content.appendChild(txt); }
1815 - builder.map.push(builder.pos, builder.pos + skipped, txt);
1816 - builder.col += skipped;
1817 - builder.pos += skipped;
1818 - }
1819 - if (!m) { break }
1820 - pos += skipped + 1;
1821 - var txt$1 = (void 0);
1822 - if (m[0] == "\t") {
1823 - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
1824 - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
1825 - txt$1.setAttribute("role", "presentation");
1826 - txt$1.setAttribute("cm-text", "\t");
1827 - builder.col += tabWidth;
1828 - } else if (m[0] == "\r" || m[0] == "\n") {
1829 - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
1830 - txt$1.setAttribute("cm-text", m[0]);
1831 - builder.col += 1;
1832 - } else {
1833 - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
1834 - txt$1.setAttribute("cm-text", m[0]);
1835 - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
1836 - else { content.appendChild(txt$1); }
1837 - builder.col += 1;
1838 - }
1839 - builder.map.push(builder.pos, builder.pos + 1, txt$1);
1840 - builder.pos++;
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 }
1841 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;
1842 1967 }
1843 - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
1844 - if (style || startStyle || endStyle || mustWrap || css || attributes) {
1845 - var fullStyle = style || "";
1846 - if (startStyle) { fullStyle += startStyle; }
1847 - if (endStyle) { fullStyle += endStyle; }
1848 - var token = elt("span", [content], fullStyle, css);
1849 - if (attributes) {
1850 - for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
1851 - { token.setAttribute(attr, attributes[attr]); } }
1852 - }
1853 - return builder.content.appendChild(token)
1854 - }
1855 - builder.content.appendChild(content);
1856 1968 }
1969 +}
1857 1970
1858 - // Change some spaces to NBSP to prevent the browser from collapsing
1859 - // trailing spaces at the end of a line when rendering text (issue #1362).
1860 - function splitSpaces(text, trailingBefore) {
1861 - if (text.length > 1 && !/ /.test(text)) { return text }
1862 - var spaceBefore = trailingBefore, result = "";
1863 - for (var i = 0; i < text.length; i++) {
1864 - var ch = text.charAt(i);
1865 - if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
1866 - { ch = "\u00a0"; }
1867 - result += ch;
1868 - spaceBefore = ch == " ";
1869 - }
1870 - return result
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);
1871 1978 }
1872 -
1873 - // Work around nonsense dimensions being reported for stretches of
1874 - // right-to-left text.
1875 - function buildTokenBadBidi(inner, order) {
1876 - return function (builder, text, style, startStyle, endStyle, css, attributes) {
1877 - style = style ? style + " cm-force-border" : "cm-force-border";
1878 - var start = builder.pos, end = start + text.length;
1879 - for (;;) {
1880 - // Find the part that overlaps with the start of this text
1881 - var part = (void 0);
1882 - for (var i = 0; i < order.length; i++) {
1883 - part = order[i];
1884 - if (part.to > start && part.from <= start) { break }
1885 - }
1886 - if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
1887 - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
1888 - startStyle = null;
1889 - text = text.slice(part.to - start);
1890 - start = part.to;
1891 - }
1892 - }
1979 + if (widget) {
1980 + builder.cm.display.input.setUneditable(widget);
1981 + builder.content.appendChild(widget);
1893 1982 }
1983 + builder.pos += size;
1984 + builder.trailingSpace = false;
1985 +}
1894 1986
1895 - function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
1896 - var widget = !ignoreWidget && marker.widgetNode;
1897 - if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
1898 - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
1899 - if (!widget)
1900 - { widget = builder.content.appendChild(document.createElement("span")); }
1901 - widget.setAttribute("cm-marker", marker.id);
1902 - }
1903 - if (widget) {
1904 - builder.cm.display.input.setUneditable(widget);
1905 - builder.content.appendChild(widget);
1906 - }
1907 - builder.pos += size;
1908 - builder.trailingSpace = false;
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
1909 1995 }
1910 1996
1911 - // Outputs a number of spans to make up a line, taking highlighting
1912 - // and marked text into account.
1913 - function insertLineContent(line, builder, styles) {
1914 - var spans = line.markedSpans, allText = line.text, at = 0;
1915 - if (!spans) {
1916 - for (var i$1 = 1; i$1 < styles.length; i$1+=2)
1917 - { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
1918 - return
1919 - }
1920 -
1921 - var len = allText.length, pos = 0, i = 1, text = "", style, css;
1922 - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
1923 - for (;;) {
1924 - if (nextChange == pos) { // Update current marker set
1925 - spanStyle = spanEndStyle = spanStartStyle = css = "";
1926 - attributes = null;
1927 - collapsed = null; nextChange = Infinity;
1928 - var foundBookmarks = [], endStyles = (void 0);
1929 - for (var j = 0; j < spans.length; ++j) {
1930 - var sp = spans[j], m = sp.marker;
1931 - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
1932 - foundBookmarks.push(m);
1933 - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
1934 - if (sp.to != null && sp.to != pos && nextChange > sp.to) {
1935 - nextChange = sp.to;
1936 - spanEndStyle = "";
1937 - }
1938 - if (m.className) { spanStyle += " " + m.className; }
1939 - if (m.css) { css = (css ? css + ";" : "") + m.css; }
1940 - if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
1941 - if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
1942 - // support for the old title property
1943 - // https://github.com/codemirror/CodeMirror/pull/5673
1944 - if (m.title) { (attributes || (attributes = {})).title = m.title; }
1945 - if (m.attributes) {
1946 - for (var attr in m.attributes)
1947 - { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
1948 - }
1949 - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
1950 - { collapsed = sp; }
1951 - } else if (sp.from > pos && nextChange > sp.from) {
1952 - nextChange = sp.from;
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 = "";
1953 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;
1954 2022 }
1955 - if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
1956 - { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
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]; } } }
1957 2026
1958 - if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
1959 - { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
1960 - if (collapsed && (collapsed.from || 0) == pos) {
1961 - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
1962 - collapsed.marker, collapsed.from == null);
1963 - if (collapsed.to == null) { return }
1964 - if (collapsed.to == pos) { collapsed = false; }
1965 - }
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; }
1966 2034 }
1967 - if (pos >= len) { break }
2035 + }
2036 + if (pos >= len) { break }
1968 2037
1969 - var upto = Math.min(len, nextChange);
1970 - while (true) {
1971 - if (text) {
1972 - var end = pos + text.length;
1973 - if (!collapsed) {
1974 - var tokenText = end > upto ? text.slice(0, upto - pos) : text;
1975 - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
1976 - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
1977 - }
1978 - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
1979 - pos = end;
1980 - spanStartStyle = "";
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);
1981 2046 }
1982 - text = allText.slice(at, at = styles[i++]);
1983 - style = interpretTokenStyle(styles[i++], builder.cm.options);
2047 + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
2048 + pos = end;
2049 + spanStartStyle = "";
1984 2050 }
2051 + text = allText.slice(at, at = styles[i++]);
2052 + style = interpretTokenStyle(styles[i++], builder.cm.options);
1985 2053 }
1986 2054 }
2055 +}
1987 2056
1988 2057
1989 - // These objects are used to represent the visible (currently drawn)
1990 - // part of the document. A LineView may correspond to multiple
1991 - // logical lines, if those are connected by collapsed ranges.
1992 - function LineView(doc, line, lineN) {
1993 - // The starting line
1994 - this.line = line;
1995 - // Continuing lines, if any
1996 - this.rest = visualLineContinued(line);
1997 - // Number of logical lines in this visual line
1998 - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
1999 - this.node = this.text = null;
2000 - this.hidden = lineIsHidden(doc, line);
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);
2001 2079 }
2080 + return array
2081 +}
2002 2082
2003 - // Create a range of LineView objects for the given lines.
2004 - function buildViewArray(cm, from, to) {
2005 - var array = [], nextPos;
2006 - for (var pos = from; pos < to; pos = nextPos) {
2007 - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2008 - nextPos = pos + view.size;
2009 - array.push(view);
2010 - }
2011 - return array
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 + };
2012 2093 }
2094 +}
2013 2095
2014 - var operationGroup = null;
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 +}
2015 2111
2016 - function pushOperation(op) {
2017 - if (operationGroup) {
2018 - operationGroup.ops.push(op);
2019 - } else {
2020 - op.ownsGroup = operationGroup = {
2021 - ops: [op],
2022 - delayedCallbacks: []
2023 - };
2024 - }
2025 - }
2112 +function finishOperation(op, endCb) {
2113 + var group = op.ownsGroup;
2114 + if (!group) { return }
2026 2115
2027 - function fireCallbacksForOps(group) {
2028 - // Calls delayed callbacks and cursorActivity handlers until no
2029 - // new ones appear
2030 - var callbacks = group.delayedCallbacks, i = 0;
2031 - do {
2032 - for (; i < callbacks.length; i++)
2033 - { callbacks[i].call(null); }
2034 - for (var j = 0; j < group.ops.length; j++) {
2035 - var op = group.ops[j];
2036 - if (op.cursorActivityHandlers)
2037 - { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2038 - { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
2039 - }
2040 - } while (i < callbacks.length)
2116 + try { fireCallbacksForOps(group); }
2117 + finally {
2118 + operationGroup = null;
2119 + endCb(group);
2041 2120 }
2121 +}
2042 2122
2043 - function finishOperation(op, endCb) {
2044 - var group = op.ownsGroup;
2045 - if (!group) { return }
2123 +var orphanDelayedCallbacks = null;
2046 2124
2047 - try { fireCallbacksForOps(group); }
2048 - finally {
2049 - operationGroup = null;
2050 - endCb(group);
2051 - }
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);
2052 2143 }
2144 + var loop = function ( i ) {
2145 + list.push(function () { return arr[i].apply(null, args); });
2146 + };
2053 2147
2054 - var orphanDelayedCallbacks = null;
2148 + for (var i = 0; i < arr.length; ++i)
2149 + loop( i );
2150 +}
2055 2151
2056 - // Often, we want to signal events at a point where we are in the
2057 - // middle of some work, but don't want the handler to start calling
2058 - // other methods on the editor, which might be in an inconsistent
2059 - // state or simply not expect any other events to happen.
2060 - // signalLater looks whether there are any handlers, and schedules
2061 - // them to be executed when the last operation ends, or, if no
2062 - // operation is active, when a timeout fires.
2063 - function signalLater(emitter, type /*, values...*/) {
2064 - var arr = getHandlers(emitter, type);
2065 - if (!arr.length) { return }
2066 - var args = Array.prototype.slice.call(arguments, 2), list;
2067 - if (operationGroup) {
2068 - list = operationGroup.delayedCallbacks;
2069 - } else if (orphanDelayedCallbacks) {
2070 - list = orphanDelayedCallbacks;
2071 - } else {
2072 - list = orphanDelayedCallbacks = [];
2073 - setTimeout(fireOrphanDelayed, 0);
2074 - }
2075 - var loop = function ( i ) {
2076 - list.push(function () { return arr[i].apply(null, args); });
2077 - };
2152 +function fireOrphanDelayed() {
2153 + var delayed = orphanDelayedCallbacks;
2154 + orphanDelayedCallbacks = null;
2155 + for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
2156 +}
2078 2157
2079 - for (var i = 0; i < arr.length; ++i)
2080 - loop( i );
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); }
2081 2168 }
2169 + lineView.changes = null;
2170 +}
2082 2171
2083 - function fireOrphanDelayed() {
2084 - var delayed = orphanDelayedCallbacks;
2085 - orphanDelayedCallbacks = null;
2086 - for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
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; }
2087 2181 }
2182 + return lineView.node
2183 +}
2088 2184
2089 - // When an aspect of a line changes, a string is added to
2090 - // lineView.changes. This updates the relevant part of the line's
2091 - // DOM structure.
2092 - function updateLineForChanges(cm, lineView, lineN, dims) {
2093 - for (var j = 0; j < lineView.changes.length; j++) {
2094 - var type = lineView.changes[j];
2095 - if (type == "text") { updateLineText(cm, lineView); }
2096 - else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
2097 - else if (type == "class") { updateLineClasses(cm, lineView); }
2098 - else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
2099 - }
2100 - lineView.changes = null;
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);
2101 2195 }
2196 +}
2102 2197
2103 - // Lines with gutter elements, widgets or a background class need to
2104 - // be wrapped, and have the extra elements added to the wrapper div
2105 - function ensureLineWrapped(lineView) {
2106 - if (lineView.node == lineView.text) {
2107 - lineView.node = elt("div", null, null, "position: relative");
2108 - if (lineView.text.parentNode)
2109 - { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
2110 - lineView.node.appendChild(lineView.text);
2111 - if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
2112 - }
2113 - return lineView.node
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
2114 2206 }
2207 + return buildLineContent(cm, lineView)
2208 +}
2115 2209
2116 - function updateLineBackground(cm, lineView) {
2117 - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
2118 - if (cls) { cls += " CodeMirror-linebackground"; }
2119 - if (lineView.background) {
2120 - if (cls) { lineView.background.className = cls; }
2121 - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
2122 - } else if (cls) {
2123 - var wrap = ensureLineWrapped(lineView);
2124 - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
2125 - cm.display.input.setUneditable(lineView.background);
2126 - }
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;
2127 2225 }
2226 +}
2128 2227
2129 - // Wrapper around buildLineContent which will reuse the structure
2130 - // in display.externalMeasured when possible.
2131 - function getLineContent(cm, lineView) {
2132 - var ext = cm.display.externalMeasured;
2133 - if (ext && ext.line == lineView.line) {
2134 - cm.display.externalMeasured = null;
2135 - lineView.measure = ext.measure;
2136 - return ext.built
2137 - }
2138 - return buildLineContent(cm, lineView)
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;
2139 2242 }
2140 -
2141 - // Redraw the line's text. Interacts with the background and text
2142 - // classes because the mode may output tokens that influence these
2143 - // classes.
2144 - function updateLineText(cm, lineView) {
2145 - var cls = lineView.text.className;
2146 - var built = getLineContent(cm, lineView);
2147 - if (lineView.text == lineView.node) { lineView.node = built.pre; }
2148 - lineView.text.parentNode.replaceChild(built.pre, lineView.text);
2149 - lineView.text = built.pre;
2150 - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
2151 - lineView.bgClass = built.bgClass;
2152 - lineView.textClass = built.textClass;
2153 - updateLineClasses(cm, lineView);
2154 - } else if (cls) {
2155 - lineView.text.className = cls;
2156 - }
2243 + if (lineView.gutterBackground) {
2244 + lineView.node.removeChild(lineView.gutterBackground);
2245 + lineView.gutterBackground = null;
2157 2246 }
2158 -
2159 - function updateLineClasses(cm, lineView) {
2160 - updateLineBackground(cm, lineView);
2161 - if (lineView.line.wrapClass)
2162 - { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
2163 - else if (lineView.node != lineView.text)
2164 - { lineView.node.className = ""; }
2165 - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
2166 - lineView.text.className = textClass || "";
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);
2167 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 +}
2168 2275
2169 - function updateLineGutter(cm, lineView, lineN, dims) {
2170 - if (lineView.gutter) {
2171 - lineView.node.removeChild(lineView.gutter);
2172 - lineView.gutter = null;
2173 - }
2174 - if (lineView.gutterBackground) {
2175 - lineView.node.removeChild(lineView.gutterBackground);
2176 - lineView.gutterBackground = null;
2177 - }
2178 - if (lineView.line.gutterClass) {
2179 - var wrap = ensureLineWrapped(lineView);
2180 - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
2181 - ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
2182 - cm.display.input.setUneditable(lineView.gutterBackground);
2183 - wrap.insertBefore(lineView.gutterBackground, lineView.text);
2184 - }
2185 - var markers = lineView.line.gutterMarkers;
2186 - if (cm.options.lineNumbers || markers) {
2187 - var wrap$1 = ensureLineWrapped(lineView);
2188 - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
2189 - cm.display.input.setUneditable(gutterWrap);
2190 - wrap$1.insertBefore(gutterWrap, lineView.text);
2191 - if (lineView.line.gutterClass)
2192 - { gutterWrap.className += " " + lineView.line.gutterClass; }
2193 - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
2194 - { lineView.lineNumber = gutterWrap.appendChild(
2195 - elt("div", lineNumberFor(cm.options, lineN),
2196 - "CodeMirror-linenumber CodeMirror-gutter-elt",
2197 - ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
2198 - if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
2199 - var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
2200 - if (found)
2201 - { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
2202 - ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
2203 - } }
2204 - }
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); }
2205 2282 }
2283 + insertLineWidgets(cm, lineView, dims);
2284 +}
2206 2285
2207 - function updateLineWidgets(cm, lineView, dims) {
2208 - if (lineView.alignable) { lineView.alignable = null; }
2209 - var isWidget = classTest("CodeMirror-linewidget");
2210 - for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
2211 - next = node.nextSibling;
2212 - if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
2213 - }
2214 - insertLineWidgets(cm, lineView, dims);
2215 - }
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; }
2216 2292
2217 - // Build a line's DOM representation from scratch
2218 - function buildLineElement(cm, lineView, lineN, dims) {
2219 - var built = getLineContent(cm, lineView);
2220 - lineView.text = lineView.node = built.pre;
2221 - if (built.bgClass) { lineView.bgClass = built.bgClass; }
2222 - if (built.textClass) { lineView.textClass = built.textClass; }
2293 + updateLineClasses(cm, lineView);
2294 + updateLineGutter(cm, lineView, lineN, dims);
2295 + insertLineWidgets(cm, lineView, dims);
2296 + return lineView.node
2297 +}
2223 2298
2224 - updateLineClasses(cm, lineView);
2225 - updateLineGutter(cm, lineView, lineN, dims);
2226 - insertLineWidgets(cm, lineView, dims);
2227 - return lineView.node
2228 - }
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 +}
2229 2306
2230 - // A lineView may contain multiple logical lines (when merged by
2231 - // collapsed spans). The widgets for all of them need to be drawn.
2232 - function insertLineWidgets(cm, lineView, dims) {
2233 - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
2234 - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2235 - { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
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");
2236 2320 }
2321 +}
2237 2322
2238 - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
2239 - if (!line.widgets) { return }
2240 - var wrap = ensureLineWrapped(lineView);
2241 - for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
2242 - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
2243 - if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
2244 - positionLineWidget(widget, node, lineView, dims);
2245 - cm.display.input.setUneditable(node);
2246 - if (allowAbove && widget.above)
2247 - { wrap.insertBefore(node, lineView.gutter || lineView.text); }
2248 - else
2249 - { wrap.appendChild(node); }
2250 - signalLater(widget, "redraw");
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";
2251 2331 }
2332 + node.style.width = width + "px";
2252 2333 }
2253 -
2254 - function positionLineWidget(widget, node, lineView, dims) {
2255 - if (widget.noHScroll) {
2256 - (lineView.alignable || (lineView.alignable = [])).push(node);
2257 - var width = dims.wrapperWidth;
2258 - node.style.left = dims.fixedPos + "px";
2259 - if (!widget.coverGutter) {
2260 - width -= dims.gutterTotalWidth;
2261 - node.style.paddingLeft = dims.gutterTotalWidth + "px";
2262 - }
2263 - node.style.width = width + "px";
2264 - }
2265 - if (widget.coverGutter) {
2266 - node.style.zIndex = 5;
2267 - node.style.position = "relative";
2268 - if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2269 - }
2334 + if (widget.coverGutter) {
2335 + node.style.zIndex = 5;
2336 + node.style.position = "relative";
2337 + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
2270 2338 }
2339 +}
2271 2340
2272 - function widgetHeight(widget) {
2273 - if (widget.height != null) { return widget.height }
2274 - var cm = widget.doc.cm;
2275 - if (!cm) { return 0 }
2276 - if (!contains(document.body, widget.node)) {
2277 - var parentStyle = "position: relative;";
2278 - if (widget.coverGutter)
2279 - { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
2280 - if (widget.noHScroll)
2281 - { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
2282 - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
2283 - }
2284 - return widget.height = widget.node.parentNode.offsetHeight
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));
2285 2352 }
2353 + return widget.height = widget.node.parentNode.offsetHeight
2354 +}
2286 2355
2287 - // Return true when the given mouse event happened in a widget
2288 - function eventInWidget(display, e) {
2289 - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2290 - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
2291 - (n.parentNode == display.sizer && n != display.mover))
2292 - { return true }
2293 - }
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 }
2294 2362 }
2363 +}
2295 2364
2296 - // POSITION MEASUREMENT
2365 +// POSITION MEASUREMENT
2297 2366
2298 - function paddingTop(display) {return display.lineSpace.offsetTop}
2299 - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
2300 - function paddingH(display) {
2301 - if (display.cachedPaddingH) { return display.cachedPaddingH }
2302 - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
2303 - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2304 - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2305 - if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
2306 - return data
2307 - }
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 +}
2308 2377
2309 - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
2310 - function displayWidth(cm) {
2311 - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
2312 - }
2313 - function displayHeight(cm) {
2314 - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
2315 - }
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 +}
2316 2385
2317 - // Ensure the lineView.wrapping.heights array is populated. This is
2318 - // an array of bottom offsets for the lines that make up a drawn
2319 - // line. When lineWrapping is on, there might be more than one
2320 - // height.
2321 - function ensureLineHeights(cm, lineView, rect) {
2322 - var wrapping = cm.options.lineWrapping;
2323 - var curWidth = wrapping && displayWidth(cm);
2324 - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2325 - var heights = lineView.measure.heights = [];
2326 - if (wrapping) {
2327 - lineView.measure.width = curWidth;
2328 - var rects = lineView.text.firstChild.getClientRects();
2329 - for (var i = 0; i < rects.length - 1; i++) {
2330 - var cur = rects[i], next = rects[i + 1];
2331 - if (Math.abs(cur.bottom - next.bottom) > 2)
2332 - { heights.push((cur.bottom + next.top) / 2 - rect.top); }
2333 - }
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); }
2334 2402 }
2335 - heights.push(rect.bottom - rect.top);
2336 2403 }
2404 + heights.push(rect.bottom - rect.top);
2337 2405 }
2406 +}
2338 2407
2339 - // Find a line map (mapping character offsets to text nodes) and a
2340 - // measurement cache for the given line number. (A line view might
2341 - // contain multiple lines when collapsed ranges are present.)
2342 - function mapFromLineView(lineView, line, lineN) {
2343 - if (lineView.line == line)
2344 - { return {map: lineView.measure.map, cache: lineView.measure.cache} }
2345 - for (var i = 0; i < lineView.rest.length; i++)
2346 - { if (lineView.rest[i] == line)
2347 - { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
2348 - for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
2349 - { if (lineNo(lineView.rest[i$1]) > lineN)
2350 - { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
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;
2351 2463 }
2464 + if (!view)
2465 + { view = updateExternalMeasurement(cm, line); }
2352 2466
2353 - // Render a line into the hidden node display.externalMeasured. Used
2354 - // when measurement is needed for a line that's not in the viewport.
2355 - function updateExternalMeasurement(cm, line) {
2356 - line = visualLine(line);
2357 - var lineN = lineNo(line);
2358 - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2359 - view.lineN = lineN;
2360 - var built = view.built = buildLineContent(cm, view);
2361 - view.text = built.pre;
2362 - removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2363 - return view
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
2364 2472 }
2473 +}
2365 2474
2366 - // Get a {top, bottom, left, right} box (in line-local coordinates)
2367 - // for a given character.
2368 - function measureChar(cm, line, ch, bias) {
2369 - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
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; }
2370 2491 }
2492 + return {left: found.left, right: found.right,
2493 + top: varHeight ? found.rtop : found.top,
2494 + bottom: varHeight ? found.rbottom : found.bottom}
2495 +}
2371 2496
2372 - // Find a line view that corresponds to the given line number.
2373 - function findViewForLine(cm, lineN) {
2374 - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2375 - { return cm.display.view[findViewIndex(cm, lineN)] }
2376 - var ext = cm.display.externalMeasured;
2377 - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2378 - { return ext }
2379 - }
2497 +var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2380 2498
2381 - // Measurement can be split in two steps, the set-up work that
2382 - // applies to the whole line, and the measurement of the actual
2383 - // character. Functions like coordsChar, that need to do a lot of
2384 - // measurements in a row, can thus ensure that the set-up work is
2385 - // only done once.
2386 - function prepareMeasureForLine(cm, line) {
2387 - var lineN = lineNo(line);
2388 - var view = findViewForLine(cm, lineN);
2389 - if (view && !view.text) {
2390 - view = null;
2391 - } else if (view && view.changes) {
2392 - updateLineForChanges(cm, view, lineN, getDimensions(cm));
2393 - cm.curOp.forceUpdate = true;
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"; }
2394 2516 }
2395 - if (!view)
2396 - { view = updateExternalMeasurement(cm, line); }
2397 -
2398 - var info = mapFromLineView(view, line, lineN);
2399 - return {
2400 - line: line, view: view, rect: null,
2401 - map: info.map, cache: info.cache, before: info.before,
2402 - hasHeights: false
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
2403 2532 }
2404 2533 }
2534 + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
2535 +}
2405 2536
2406 - // Given a prepared measurement object, measures the position of an
2407 - // actual character (or fetches it from the cache).
2408 - function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2409 - if (prepared.before) { ch = -1; }
2410 - var key = ch + (bias || ""), found;
2411 - if (prepared.cache.hasOwnProperty(key)) {
2412 - found = prepared.cache[key];
2413 - } else {
2414 - if (!prepared.rect)
2415 - { prepared.rect = prepared.view.text.getBoundingClientRect(); }
2416 - if (!prepared.hasHeights) {
2417 - ensureLineHeights(cm, prepared.view, prepared.rect);
2418 - prepared.hasHeights = true;
2419 - }
2420 - found = measureCharInner(cm, prepared, ch, bias);
2421 - if (!found.bogus) { prepared.cache[key] = found; }
2422 - }
2423 - return {left: found.left, right: found.right,
2424 - top: varHeight ? found.rtop : found.top,
2425 - bottom: varHeight ? found.rbottom : found.bottom}
2426 - }
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 +}
2427 2546
2428 - var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
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;
2429 2550
2430 - function nodeAndOffsetInLineMap(map, ch, bias) {
2431 - var node, start, end, collapse, mStart, mEnd;
2432 - // First, search the line map for the text node corresponding to,
2433 - // or closest to, the target character.
2434 - for (var i = 0; i < map.length; i += 3) {
2435 - mStart = map[i];
2436 - mEnd = map[i + 1];
2437 - if (ch < mStart) {
2438 - start = 0; end = 1;
2439 - collapse = "left";
2440 - } else if (ch < mEnd) {
2441 - start = ch - mStart;
2442 - end = start + 1;
2443 - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2444 - end = mEnd - mStart;
2445 - start = end - 1;
2446 - if (ch >= mEnd) { collapse = "right"; }
2447 - }
2448 - if (start != null) {
2449 - node = map[i + 2];
2450 - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2451 - { collapse = bias; }
2452 - if (bias == "left" && start == 0)
2453 - { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2454 - node = map[(i -= 3) + 2];
2455 - collapse = "left";
2456 - } }
2457 - if (bias == "right" && start == mEnd - mStart)
2458 - { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2459 - node = map[(i += 3) + 2];
2460 - collapse = "right";
2461 - } }
2462 - break
2463 - }
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";
2464 2564 }
2465 - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
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(); }
2466 2573 }
2467 -
2468 - function getUsefulRect(rects, bias) {
2469 - var rect = nullRect;
2470 - if (bias == "left") { for (var i = 0; i < rects.length; i++) {
2471 - if ((rect = rects[i]).left != rect.right) { break }
2472 - } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
2473 - if ((rect = rects[i$1]).left != rect.right) { break }
2474 - } }
2475 - return rect
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; }
2476 2580 }
2477 2581
2478 - function measureCharInner(cm, prepared, ch, bias) {
2479 - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2480 - var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
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; }
2481 2594
2482 - var rect;
2483 - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2484 - for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2485 - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
2486 - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
2487 - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2488 - { rect = node.parentNode.getBoundingClientRect(); }
2489 - else
2490 - { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
2491 - if (rect.left || rect.right || start == 0) { break }
2492 - end = start;
2493 - start = start - 1;
2494 - collapse = "right";
2495 - }
2496 - if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
2497 - } else { // If it is a widget, simply get the box for the whole widget.
2498 - if (start > 0) { collapse = bias = "right"; }
2499 - var rects;
2500 - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2501 - { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
2502 - else
2503 - { rect = node.getBoundingClientRect(); }
2504 - }
2505 - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2506 - var rSpan = node.parentNode.getClientRects()[0];
2507 - if (rSpan)
2508 - { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
2509 - else
2510 - { rect = nullRect; }
2511 - }
2595 + return result
2596 +}
2512 2597
2513 - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2514 - var mid = (rtop + rbot) / 2;
2515 - var heights = prepared.view.measure.heights;
2516 - var i = 0;
2517 - for (; i < heights.length - 1; i++)
2518 - { if (mid < heights[i]) { break } }
2519 - var top = i ? heights[i - 1] : 0, bot = heights[i];
2520 - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2521 - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2522 - top: top, bottom: bot};
2523 - if (!rect.left && !rect.right) { result.bogus = true; }
2524 - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
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 +}
2525 2609
2526 - return result
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] = {}; } }
2527 2616 }
2617 +}
2528 2618
2529 - // Work around problem with bounding client rects on ranges being
2530 - // returned incorrectly when zoomed on IE10 and below.
2531 - function maybeUpdateRectForZooming(measure, rect) {
2532 - if (!window.screen || screen.logicalXDPI == null ||
2533 - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2534 - { return rect }
2535 - var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2536 - var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2537 - return {left: rect.left * scaleX, right: rect.right * scaleX,
2538 - top: rect.top * scaleY, bottom: rect.bottom * scaleY}
2539 - }
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 +}
2540 2625
2541 - function clearLineMeasurementCacheFor(lineView) {
2542 - if (lineView.measure) {
2543 - lineView.measure.cache = {};
2544 - lineView.measure.heights = null;
2545 - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
2546 - { lineView.measure.caches[i] = {}; } }
2547 - }
2548 - }
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 +}
2549 2632
2550 - function clearLineMeasurementCache(cm) {
2551 - cm.display.externalMeasure = null;
2552 - removeChildren(cm.display.lineMeasure);
2553 - for (var i = 0; i < cm.display.view.length; i++)
2554 - { clearLineMeasurementCacheFor(cm.display.view[i]); }
2555 - }
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 +}
2556 2644
2557 - function clearCaches(cm) {
2558 - clearLineMeasurementCache(cm);
2559 - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2560 - if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
2561 - cm.display.lineNumChars = null;
2562 - }
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 +}
2563 2651
2564 - function pageScrollX() {
2565 - // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
2566 - // which causes page_Offset and bounding client rects to use
2567 - // different reference viewports and invalidate our calculations.
2568 - if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
2569 - return window.pageXOffset || (document.documentElement || document.body).scrollLeft
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;
2570 2660 }
2571 - function pageScrollY() {
2572 - if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
2573 - return window.pageYOffset || (document.documentElement || document.body).scrollTop
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;
2574 2671 }
2672 + rect.top += yOff; rect.bottom += yOff;
2673 + return rect
2674 +}
2575 2675
2576 - function widgetTopHeight(lineObj) {
2577 - var height = 0;
2578 - if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
2579 - { height += widgetHeight(lineObj.widgets[i]); } } }
2580 - return height
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;
2581 2689 }
2582 2690
2583 - // Converts a {top, bottom, left, right} box from line-local
2584 - // coordinates into another coordinate system. Context may be one of
2585 - // "line", "div" (display.lineDiv), "local"./null (editor), "window",
2586 - // or "page".
2587 - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
2588 - if (!includeWidgets) {
2589 - var height = widgetTopHeight(lineObj);
2590 - rect.top += height; rect.bottom += height;
2591 - }
2592 - if (context == "line") { return rect }
2593 - if (!context) { context = "local"; }
2594 - var yOff = heightAtLine(lineObj);
2595 - if (context == "local") { yOff += paddingTop(cm.display); }
2596 - else { yOff -= cm.display.viewOffset; }
2597 - if (context == "page" || context == "window") {
2598 - var lOff = cm.display.lineSpace.getBoundingClientRect();
2599 - yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2600 - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2601 - rect.left += xOff; rect.right += xOff;
2602 - }
2603 - rect.top += yOff; rect.bottom += yOff;
2604 - return rect
2605 - }
2691 + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2692 + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
2693 +}
2606 2694
2607 - // Coverts a box from "div" coords to another coordinate system.
2608 - // Context may be "window", "page", "div", or "local"./null.
2609 - function fromCoordSystem(cm, coords, context) {
2610 - if (context == "div") { return coords }
2611 - var left = coords.left, top = coords.top;
2612 - // First move into "page" coordinate system
2613 - if (context == "page") {
2614 - left -= pageScrollX();
2615 - top -= pageScrollY();
2616 - } else if (context == "local" || !context) {
2617 - var localBox = cm.display.sizer.getBoundingClientRect();
2618 - left += localBox.left;
2619 - top += localBox.top;
2620 - }
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 +}
2621 2699
2622 - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2623 - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
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)
2624 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") }
2625 2733
2626 - function charCoords(cm, pos, context, lineObj, bias) {
2627 - if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
2628 - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
2734 + function getBidi(ch, partPos, invert) {
2735 + var part = order[partPos], right = part.level == 1;
2736 + return get(invert ? ch - 1 : ch, right != invert)
2629 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 +}
2630 2744
2631 - // Returns a box for a given cursor position, which may have an
2632 - // 'other' property containing the position of the secondary cursor
2633 - // on a bidi boundary.
2634 - // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
2635 - // and after `char - 1` in writing order of `char - 1`
2636 - // A cursor Pos(line, char, "after") is on the same visual line as `char`
2637 - // and before `char` in writing order of `char`
2638 - // Examples (upper-case letters are RTL, lower-case are LTR):
2639 - // Pos(0, 1, ...)
2640 - // before after
2641 - // ab a|b a|b
2642 - // aB a|B aB|
2643 - // Ab |Ab A|b
2644 - // AB B|A B|A
2645 - // Every position after the last character on a line is considered to stick
2646 - // to the last character on the line.
2647 - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2648 - lineObj = lineObj || getLine(cm.doc, pos.line);
2649 - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2650 - function get(ch, right) {
2651 - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2652 - if (right) { m.left = m.right; } else { m.right = m.left; }
2653 - return intoCoordSystem(cm, lineObj, m, context)
2654 - }
2655 - var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
2656 - if (ch >= lineObj.text.length) {
2657 - ch = lineObj.text.length;
2658 - sticky = "before";
2659 - } else if (ch <= 0) {
2660 - ch = 0;
2661 - sticky = "after";
2662 - }
2663 - if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
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 +}
2664 2755
2665 - function getBidi(ch, partPos, invert) {
2666 - var part = order[partPos], right = part.level == 1;
2667 - return get(invert ? ch - 1 : ch, right != invert)
2668 - }
2669 - var partPos = getBidiPartAt(order, ch, sticky);
2670 - var other = bidiOther;
2671 - var val = getBidi(ch, partPos, sticky == "before");
2672 - if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
2673 - return val
2674 - }
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 +}
2675 2768
2676 - // Used to cheaply estimate the coordinates for a position. Used for
2677 - // intermediate scroll updates.
2678 - function estimateCoords(cm, pos) {
2679 - var left = 0;
2680 - pos = clipPos(cm.doc, pos);
2681 - if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
2682 - var lineObj = getLine(cm.doc, pos.line);
2683 - var top = heightAtLine(lineObj) + paddingTop(cm.display);
2684 - return {left: left, right: left, top: top, bottom: top + lineObj.height}
2685 - }
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; }
2686 2779
2687 - // Positions returned by coordsChar contain some extra information.
2688 - // xRel is the relative x position of the input coordinates compared
2689 - // to the found position (so xRel > 0 means the coordinates are to
2690 - // the right of the character position, for example). When outside
2691 - // is true, that means the coordinates lie outside the line's
2692 - // vertical range.
2693 - function PosWithInfo(line, ch, sticky, outside, xRel) {
2694 - var pos = Pos(line, ch, sticky);
2695 - pos.xRel = xRel;
2696 - if (outside) { pos.outside = outside; }
2697 - return pos
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 }
2698 2789 }
2790 +}
2699 2791
2700 - // Compute the character position closest to the given coordinates.
2701 - // Input must be lineSpace-local ("div" coordinate system).
2702 - function coordsChar(cm, x, y) {
2703 - var doc = cm.doc;
2704 - y += cm.display.viewOffset;
2705 - if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
2706 - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2707 - if (lineN > last)
2708 - { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
2709 - if (x < 0) { x = 0; }
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 +}
2710 2799
2711 - var lineObj = getLine(doc, lineN);
2712 - for (;;) {
2713 - var found = coordsCharInner(cm, lineObj, lineN, x, y);
2714 - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
2715 - if (!collapsed) { return found }
2716 - var rangeEnd = collapsed.find(1);
2717 - if (rangeEnd.line == lineN) { return rangeEnd }
2718 - lineObj = getLine(doc, lineN = rangeEnd.line);
2719 - }
2720 - }
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 +}
2721 2805
2722 - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
2723 - y -= widgetTopHeight(lineObj);
2724 - var end = lineObj.text.length;
2725 - var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
2726 - end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
2727 - return {begin: begin, end: end}
2728 - }
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 +}
2729 2811
2730 - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
2731 - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
2732 - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
2733 - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
2734 - }
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;
2735 2820
2736 - // Returns true if the given side of a box is after the given
2737 - // coordinates, in top-to-bottom, left-to-right order.
2738 - function boxIsAfter(box, x, y, left) {
2739 - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
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;
2740 2834 }
2741 2835
2742 - function coordsCharInner(cm, lineObj, lineNo, x, y) {
2743 - // Move y into line-local coordinate space
2744 - y -= heightAtLine(lineObj);
2745 - var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2746 - // When directly calling `measureCharPrepared`, we have to adjust
2747 - // for the widgets at this line.
2748 - var widgetHeight = widgetTopHeight(lineObj);
2749 - var begin = 0, end = lineObj.text.length, ltr = true;
2750 -
2751 - var order = getOrder(lineObj, cm.doc.direction);
2752 - // If the line isn't plain left-to-right text, first figure out
2753 - // which bidi section the coordinates fall into.
2754 - if (order) {
2755 - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
2756 - (cm, lineObj, lineNo, preparedMeasure, order, x, y);
2757 - ltr = part.level != 1;
2758 - // The awkward -1 offsets are needed because findFirst (called
2759 - // on these below) will treat its first bound as inclusive,
2760 - // second as exclusive, but we want to actually address the
2761 - // characters in the part's range
2762 - begin = ltr ? part.from : part.to - 1;
2763 - end = ltr ? part.to : part.from - 1;
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;
2764 2847 }
2848 + return true
2849 + }, begin, end);
2765 2850
2766 - // A binary search to find the first character whose bounding box
2767 - // starts after the coordinates. If we run across any whose box wrap
2768 - // the coordinates, store that.
2769 - var chAround = null, boxAround = null;
2770 - var ch = findFirst(function (ch) {
2771 - var box = measureCharPrepared(cm, preparedMeasure, ch);
2772 - box.top += widgetHeight; box.bottom += widgetHeight;
2773 - if (!boxIsAfter(box, x, y, false)) { return false }
2774 - if (box.top <= y && box.left <= x) {
2775 - chAround = ch;
2776 - boxAround = box;
2777 - }
2778 - return true
2779 - }, begin, end);
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 + }
2780 2874
2781 - var baseX, sticky, outside = false;
2782 - // If a box around the coordinates was found, use that
2783 - if (boxAround) {
2784 - // Distinguish coordinates nearer to the left or right side of the box
2785 - var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
2786 - ch = chAround + (atStart ? 0 : 1);
2787 - sticky = atStart ? "after" : "before";
2788 - baseX = atLeft ? boxAround.left : boxAround.right;
2789 - } else {
2790 - // (Adjust for extended bound, if necessary.)
2791 - if (!ltr && (ch == end || ch == begin)) { ch++; }
2792 - // To determine which side to associate with, get the box to the
2793 - // left of the character and compare it's vertical position to the
2794 - // coordinates
2795 - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
2796 - (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
2797 - "after" : "before";
2798 - // Now get accurate coordinates for this place, in order to get a
2799 - // base X position
2800 - var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
2801 - baseX = coords.left;
2802 - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
2803 - }
2875 + ch = skipExtendingChars(lineObj.text, ch, 1);
2876 + return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
2877 +}
2804 2878
2805 - ch = skipExtendingChars(lineObj.text, ch, 1);
2806 - return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
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]; }
2807 2899 }
2900 + return part
2901 +}
2808 2902
2809 - function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
2810 - // Bidi parts are sorted left-to-right, and in a non-line-wrapping
2811 - // situation, we can take this ordering to correspond to the visual
2812 - // ordering. This finds the first part whose end is after the given
2813 - // coordinates.
2814 - var index = findFirst(function (i) {
2815 - var part = order[i], ltr = part.level != 1;
2816 - return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
2817 - "line", lineObj, preparedMeasure), x, y, true)
2818 - }, 0, order.length - 1);
2819 - var part = order[index];
2820 - // If this isn't the first part, the part's start is also after
2821 - // the coordinates, and the coordinates aren't on the same line as
2822 - // that start, move one part back.
2823 - if (index > 0) {
2824 - var ltr = part.level != 1;
2825 - var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
2826 - "line", lineObj, preparedMeasure);
2827 - if (boxIsAfter(start, x, y, true) && start.top > y)
2828 - { part = order[index - 1]; }
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;
2829 2927 }
2830 - return part
2831 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 +}
2832 2935
2833 - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
2834 - // In a wrapped line, rtl text on wrapping boundaries can do things
2835 - // that don't correspond to the ordering in our `order` array at
2836 - // all, so a binary search doesn't work, and we want to return a
2837 - // part that only spans one line so that the binary search in
2838 - // coordsCharInner is safe. As such, we first find the extent of the
2839 - // wrapped line, and then do a flat search in which we discard any
2840 - // spans that aren't on the line.
2841 - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
2842 - var begin = ref.begin;
2843 - var end = ref.end;
2844 - if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
2845 - var part = null, closestDist = null;
2846 - for (var i = 0; i < order.length; i++) {
2847 - var p = order[i];
2848 - if (p.from >= end || p.to <= begin) { continue }
2849 - var ltr = p.level != 1;
2850 - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
2851 - // Weigh against spans ending before this, so that they are only
2852 - // picked if nothing ends after
2853 - var dist = endX < x ? x - endX + 1e9 : endX - x;
2854 - if (!part || closestDist > dist) {
2855 - part = p;
2856 - closestDist = dist;
2857 - }
2858 - }
2859 - if (!part) { part = order[order.length - 1]; }
2860 - // Clip the part to the wrapped line.
2861 - if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
2862 - if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
2863 - return part
2864 - }
2865 -
2866 - var measureText;
2867 - // Compute the default text height.
2868 - function textHeight(display) {
2869 - if (display.cachedTextHeight != null) { return display.cachedTextHeight }
2870 - if (measureText == null) {
2871 - measureText = elt("pre", null, "CodeMirror-line-like");
2872 - // Measure a bunch of lines, for browsers that compute
2873 - // fractional heights.
2874 - for (var i = 0; i < 49; ++i) {
2875 - measureText.appendChild(document.createTextNode("x"));
2876 - measureText.appendChild(elt("br"));
2877 - }
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) {
2878 2945 measureText.appendChild(document.createTextNode("x"));
2946 + measureText.appendChild(elt("br"));
2879 2947 }
2880 - removeChildrenAndAdd(display.measure, measureText);
2881 - var height = measureText.offsetHeight / 50;
2882 - if (height > 3) { display.cachedTextHeight = height; }
2883 - removeChildren(display.measure);
2884 - return height || 1
2948 + measureText.appendChild(document.createTextNode("x"));
2885 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 +}
2886 2956
2887 - // Compute the default character width.
2888 - function charWidth(display) {
2889 - if (display.cachedCharWidth != null) { return display.cachedCharWidth }
2890 - var anchor = elt("span", "xxxxxxxxxx");
2891 - var pre = elt("pre", [anchor], "CodeMirror-line-like");
2892 - removeChildrenAndAdd(display.measure, pre);
2893 - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2894 - if (width > 2) { display.cachedCharWidth = width; }
2895 - return width || 10
2896 - }
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 +}
2897 2967
2898 - // Do a bulk-read of the DOM positions and sizes needed to draw the
2899 - // view, so that we don't interleave reading and writing to the DOM.
2900 - function getDimensions(cm) {
2901 - var d = cm.display, left = {}, width = {};
2902 - var gutterLeft = d.gutters.clientLeft;
2903 - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
2904 - var id = cm.display.gutterSpecs[i].className;
2905 - left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
2906 - width[id] = n.clientWidth;
2907 - }
2908 - return {fixedPos: compensateForHScroll(d),
2909 - gutterTotalWidth: d.gutters.offsetWidth,
2910 - gutterLeft: left,
2911 - gutterWidth: width,
2912 - wrapperWidth: d.wrapper.clientWidth}
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;
2913 2976 }
2977 + return {fixedPos: compensateForHScroll(d),
2978 + gutterTotalWidth: d.gutters.offsetWidth,
2979 + gutterLeft: left,
2980 + gutterWidth: width,
2981 + wrapperWidth: d.wrapper.clientWidth}
2982 +}
2914 2983
2915 - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
2916 - // but using getBoundingClientRect to get a sub-pixel-accurate
2917 - // result.
2918 - function compensateForHScroll(display) {
2919 - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
2920 - }
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 +}
2921 2990
2922 - // Returns a function that estimates the height of a line, to use as
2923 - // first approximation until the line becomes visible (and is thus
2924 - // properly measurable).
2925 - function estimateHeight(cm) {
2926 - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
2927 - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
2928 - return function (line) {
2929 - if (lineIsHidden(cm.doc, line)) { return 0 }
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 }
2930 2999
2931 - var widgetsHeight = 0;
2932 - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
2933 - if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
2934 - } }
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 + } }
2935 3004
2936 - if (wrapping)
2937 - { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
2938 - else
2939 - { return widgetsHeight + th }
2940 - }
3005 + if (wrapping)
3006 + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
3007 + else
3008 + { return widgetsHeight + th }
2941 3009 }
3010 +}
2942 3011
2943 - function estimateLineHeights(cm) {
2944 - var doc = cm.doc, est = estimateHeight(cm);
2945 - doc.iter(function (line) {
2946 - var estHeight = est(line);
2947 - if (estHeight != line.height) { updateLineHeight(line, estHeight); }
2948 - });
2949 - }
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 +}
2950 3019
2951 - // Given a mouse event, find the corresponding position. If liberal
2952 - // is false, it checks whether a gutter or scrollbar was clicked,
2953 - // and returns null if it was. forRect is used by rectangular
2954 - // selections, and tries to estimate a character position even for
2955 - // coordinates beyond the right of the text.
2956 - function posFromMouse(cm, e, liberal, forRect) {
2957 - var display = cm.display;
2958 - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
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 }
2959 3028
2960 - var x, y, space = display.lineSpace.getBoundingClientRect();
2961 - // Fails unpredictably on IE[67] when mouse is dragged around quickly.
2962 - try { x = e.clientX - space.left; y = e.clientY - space.top; }
2963 - catch (e$1) { return null }
2964 - var coords = coordsChar(cm, x, y), line;
2965 - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
2966 - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
2967 - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
2968 - }
2969 - return coords
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));
2970 3037 }
3038 + return coords
3039 +}
2971 3040
2972 - // Find the view element corresponding to a given line. Return null
2973 - // when the line isn't visible.
2974 - function findViewIndex(cm, n) {
2975 - if (n >= cm.display.viewTo) { return null }
2976 - n -= cm.display.viewFrom;
2977 - if (n < 0) { return null }
2978 - var view = cm.display.view;
2979 - for (var i = 0; i < view.length; i++) {
2980 - n -= view[i].size;
2981 - if (n < 0) { return i }
2982 - }
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 }
2983 3051 }
3052 +}
2984 3053
2985 - // Updates the display.view data structure for a given change to the
2986 - // document. From and to are in pre-change coordinates. Lendiff is
2987 - // the amount of lines added or subtracted by the change. This is
2988 - // used for changes that span multiple lines, or change the way
2989 - // lines are divided into visual lines. regLineChange (below)
2990 - // registers single-line changes.
2991 - function regChange(cm, from, to, lendiff) {
2992 - if (from == null) { from = cm.doc.first; }
2993 - if (to == null) { to = cm.doc.first + cm.doc.size; }
2994 - if (!lendiff) { lendiff = 0; }
3054 +function updateSelection(cm) {
3055 + cm.display.input.showSelection(cm.display.input.prepareSelection());
3056 +}
2995 3057
2996 - var display = cm.display;
2997 - if (lendiff && to < display.viewTo &&
2998 - (display.updateLineNumbers == null || display.updateLineNumbers > from))
2999 - { display.updateLineNumbers = from; }
3058 +function prepareSelection(cm, primary) {
3059 + if ( primary === void 0 ) primary = true;
3000 3060
3001 - cm.curOp.viewChanged = true;
3061 + var doc = cm.doc, result = {};
3062 + var curFragment = result.cursors = document.createDocumentFragment();
3063 + var selFragment = result.selection = document.createDocumentFragment();
3002 3064
3003 - if (from >= display.viewTo) { // Change after
3004 - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3005 - { resetView(cm); }
3006 - } else if (to <= display.viewFrom) { // Change before
3007 - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3008 - resetView(cm);
3009 - } else {
3010 - display.viewFrom += lendiff;
3011 - display.viewTo += lendiff;
3012 - }
3013 - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3014 - resetView(cm);
3015 - } else if (from <= display.viewFrom) { // Top overlap
3016 - var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3017 - if (cut) {
3018 - display.view = display.view.slice(cut.index);
3019 - display.viewFrom = cut.lineN;
3020 - display.viewTo += lendiff;
3021 - } else {
3022 - resetView(cm);
3023 - }
3024 - } else if (to >= display.viewTo) { // Bottom overlap
3025 - var cut$1 = viewCuttingPoint(cm, from, from, -1);
3026 - if (cut$1) {
3027 - display.view = display.view.slice(0, cut$1.index);
3028 - display.viewTo = cut$1.lineN;
3029 - } else {
3030 - resetView(cm);
3031 - }
3032 - } else { // Gap in the middle
3033 - var cutTop = viewCuttingPoint(cm, from, from, -1);
3034 - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3035 - if (cutTop && cutBot) {
3036 - display.view = display.view.slice(0, cutTop.index)
3037 - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3038 - .concat(display.view.slice(cutBot.index));
3039 - display.viewTo += lendiff;
3040 - } else {
3041 - resetView(cm);
3042 - }
3043 - }
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 +}
3044 3077
3045 - var ext = display.externalMeasured;
3046 - if (ext) {
3047 - if (to < ext.lineN)
3048 - { ext.lineN += lendiff; }
3049 - else if (from < ext.lineN + ext.size)
3050 - { display.externalMeasured = null; }
3051 - }
3052 - }
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);
3053 3081
3054 - // Register a change to a single line. Type must be one of "text",
3055 - // "gutter", "class", "widget"
3056 - function regLineChange(cm, line, type) {
3057 - cm.curOp.viewChanged = true;
3058 - var display = cm.display, ext = cm.display.externalMeasured;
3059 - if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3060 - { display.externalMeasured = null; }
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";
3061 3086
3062 - if (line < display.viewFrom || line >= display.viewTo) { return }
3063 - var lineView = display.view[findViewIndex(cm, line)];
3064 - if (lineView.node == null) { return }
3065 - var arr = lineView.changes || (lineView.changes = []);
3066 - if (indexOf(arr, type) == -1) { arr.push(type); }
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";
3067 3094 }
3095 +}
3068 3096
3069 - // Clear the view.
3070 - function resetView(cm) {
3071 - cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3072 - cm.display.view = [];
3073 - cm.display.viewOffset = 0;
3074 - }
3097 +function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3075 3098
3076 - function viewCuttingPoint(cm, oldN, newN, dir) {
3077 - var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3078 - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3079 - { return {index: index, lineN: newN} }
3080 - var n = cm.display.viewFrom;
3081 - for (var i = 0; i < index; i++)
3082 - { n += view[i].size; }
3083 - if (n != oldN) {
3084 - if (dir > 0) {
3085 - if (index == view.length - 1) { return null }
3086 - diff = (n + view[index].size) - oldN;
3087 - index++;
3088 - } else {
3089 - diff = n - oldN;
3090 - }
3091 - oldN += diff; newN += diff;
3092 - }
3093 - while (visualLineNo(cm.doc, newN) != newN) {
3094 - if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
3095 - newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3096 - index += dir;
3097 - }
3098 - return {index: index, lineN: newN}
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")));
3099 3112 }
3100 3113
3101 - // Force the view to cover a given range, adding empty view element
3102 - // or clipping off existing ones as needed.
3103 - function adjustView(cm, from, to) {
3104 - var display = cm.display, view = display.view;
3105 - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3106 - display.view = buildViewArray(cm, from, to);
3107 - display.viewFrom = from;
3108 - } else {
3109 - if (display.viewFrom > from)
3110 - { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
3111 - else if (display.viewFrom < from)
3112 - { display.view = display.view.slice(findViewIndex(cm, from)); }
3113 - display.viewFrom = from;
3114 - if (display.viewTo < to)
3115 - { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
3116 - else if (display.viewTo > to)
3117 - { display.view = display.view.slice(0, findViewIndex(cm, to)); }
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)
3118 3120 }
3119 - display.viewTo = to;
3120 - }
3121 3121
3122 - // Count the number of lines in the view whose DOM representation is
3123 - // out of date (or nonexistent).
3124 - function countDirtyView(cm) {
3125 - var view = cm.display.view, dirty = 0;
3126 - for (var i = 0; i < view.length; i++) {
3127 - var lineView = view[i];
3128 - if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
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]
3129 3127 }
3130 - return dirty
3131 - }
3132 3128
3133 - function updateSelection(cm) {
3134 - cm.display.input.showSelection(cm.display.input.prepareSelection());
3135 - }
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");
3136 3134
3137 - function prepareSelection(cm, primary) {
3138 - if ( primary === void 0 ) primary = true;
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 + }
3139 3160
3140 - var doc = cm.doc, result = {};
3141 - var curFragment = result.cursors = document.createDocumentFragment();
3142 - var selFragment = result.selection = document.createDocumentFragment();
3143 -
3144 - for (var i = 0; i < doc.sel.ranges.length; i++) {
3145 - if (!primary && i == doc.sel.primIndex) { continue }
3146 - var range = doc.sel.ranges[i];
3147 - if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
3148 - var collapsed = range.empty();
3149 - if (collapsed || cm.options.showCursorWhenSelecting)
3150 - { drawSelectionCursor(cm, range.head, curFragment); }
3151 - if (!collapsed)
3152 - { drawSelectionRange(cm, range, selFragment); }
3153 - }
3154 - return result
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}
3155 3167 }
3156 3168
3157 - // Draws a cursor for the given range
3158 - function drawSelectionCursor(cm, head, output) {
3159 - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
3160 -
3161 - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
3162 - cursor.style.left = pos.left + "px";
3163 - cursor.style.top = pos.top + "px";
3164 - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
3165 -
3166 - if (pos.other) {
3167 - // Secondary cursor, shown when on a 'jump' in bi-directional text
3168 - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
3169 - otherCursor.style.display = "";
3170 - otherCursor.style.left = pos.other.left + "px";
3171 - otherCursor.style.top = pos.other.top + "px";
3172 - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
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 + }
3173 3184 }
3185 + if (leftEnd.bottom < rightStart.top)
3186 + { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3174 3187 }
3175 3188
3176 - function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
3189 + output.appendChild(fragment);
3190 +}
3177 3191
3178 - // Draws the given range as a highlighted selection
3179 - function drawSelectionRange(cm, range, output) {
3180 - var display = cm.display, doc = cm.doc;
3181 - var fragment = document.createDocumentFragment();
3182 - var padding = paddingH(cm.display), leftSide = padding.left;
3183 - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
3184 - var docLTR = doc.direction == "ltr";
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 +}
3185 3205
3186 - function add(left, top, width, bottom) {
3187 - if (top < 0) { top = 0; }
3188 - top = Math.round(top);
3189 - bottom = Math.round(bottom);
3190 - 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")));
3191 - }
3206 +function ensureFocus(cm) {
3207 + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
3208 +}
3192 3209
3193 - function drawForLine(line, fromArg, toArg) {
3194 - var lineObj = getLine(doc, line);
3195 - var lineLen = lineObj.text.length;
3196 - var start, end;
3197 - function coords(ch, bias) {
3198 - return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
3199 - }
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 +}
3200 3217
3201 - function wrapX(pos, dir, side) {
3202 - var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
3203 - var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
3204 - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
3205 - return coords(ch, prop)[prop]
3206 - }
3218 +function onFocus(cm, e) {
3219 + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
3207 3220
3208 - var order = getOrder(lineObj, doc.direction);
3209 - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
3210 - var ltr = dir == "ltr";
3211 - var fromPos = coords(from, ltr ? "left" : "right");
3212 - var toPos = coords(to - 1, ltr ? "right" : "left");
3213 -
3214 - var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
3215 - var first = i == 0, last = !order || i == order.length - 1;
3216 - if (toPos.top - fromPos.top <= 3) { // Single line
3217 - var openLeft = (docLTR ? openStart : openEnd) && first;
3218 - var openRight = (docLTR ? openEnd : openStart) && last;
3219 - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
3220 - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
3221 - add(left, fromPos.top, right - left, fromPos.bottom);
3222 - } else { // Multiple lines
3223 - var topLeft, topRight, botLeft, botRight;
3224 - if (ltr) {
3225 - topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
3226 - topRight = docLTR ? rightSide : wrapX(from, dir, "before");
3227 - botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
3228 - botRight = docLTR && openEnd && last ? rightSide : toPos.right;
3229 - } else {
3230 - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
3231 - topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
3232 - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
3233 - botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
3234 - }
3235 - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
3236 - if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
3237 - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
3238 - }
3239 -
3240 - if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
3241 - if (cmpCoords(toPos, start) < 0) { start = toPos; }
3242 - if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
3243 - if (cmpCoords(toPos, end) < 0) { end = toPos; }
3244 - });
3245 - return {start: start, end: end}
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
3246 3232 }
3247 -
3248 - var sFrom = range.from(), sTo = range.to();
3249 - if (sFrom.line == sTo.line) {
3250 - drawForLine(sFrom.line, sFrom.ch, sTo.ch);
3251 - } else {
3252 - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3253 - var singleVLine = visualLine(fromLine) == visualLine(toLine);
3254 - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
3255 - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
3256 - if (singleVLine) {
3257 - if (leftEnd.top < rightStart.top - 2) {
3258 - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
3259 - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
3260 - } else {
3261 - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
3262 - }
3263 - }
3264 - if (leftEnd.bottom < rightStart.top)
3265 - { add(leftSide, leftEnd.bottom, null, rightStart.top); }
3266 - }
3267 -
3268 - output.appendChild(fragment);
3233 + cm.display.input.receivedFocus();
3269 3234 }
3235 + restartBlink(cm);
3236 +}
3237 +function onBlur(cm, e) {
3238 + if (cm.state.delayingBlurEvent) { return }
3270 3239
3271 - // Cursor-blinking
3272 - function restartBlink(cm) {
3273 - if (!cm.state.focused) { return }
3274 - var display = cm.display;
3275 - clearInterval(display.blinker);
3276 - var on = true;
3277 - display.cursorDiv.style.visibility = "";
3278 - if (cm.options.cursorBlinkRate > 0)
3279 - { display.blinker = setInterval(function () {
3280 - if (!cm.hasFocus()) { onBlur(cm); }
3281 - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
3282 - }, cm.options.cursorBlinkRate); }
3283 - else if (cm.options.cursorBlinkRate < 0)
3284 - { display.cursorDiv.style.visibility = "hidden"; }
3240 + if (cm.state.focused) {
3241 + signal(cm, "blur", cm, e);
3242 + cm.state.focused = false;
3243 + rmClass(cm.display.wrapper, "CodeMirror-focused");
3285 3244 }
3245 + clearInterval(cm.display.blinker);
3246 + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3247 +}
3286 3248
3287 - function ensureFocus(cm) {
3288 - if (!cm.hasFocus()) {
3289 - cm.display.input.focus();
3290 - if (!cm.state.focused) { onFocus(cm); }
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;
3291 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 + }
3292 3273 }
3274 +}
3293 3275
3294 - function delayBlurEvent(cm) {
3295 - cm.state.delayingBlurEvent = true;
3296 - setTimeout(function () { if (cm.state.delayingBlurEvent) {
3297 - cm.state.delayingBlurEvent = false;
3298 - if (cm.state.focused) { onBlur(cm); }
3299 - } }, 100);
3300 - }
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 +}
3301 3284
3302 - function onFocus(cm, e) {
3303 - if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
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;
3304 3292
3305 - if (cm.options.readOnly == "nocursor") { return }
3306 - if (!cm.state.focused) {
3307 - signal(cm, "focus", cm, e);
3308 - cm.state.focused = true;
3309 - addClass(cm.display.wrapper, "CodeMirror-focused");
3310 - // This test prevents this from firing when a context
3311 - // menu is closed (since the input reset would kill the
3312 - // select-all detection hack)
3313 - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3314 - cm.display.input.reset();
3315 - if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
3316 - }
3317 - cm.display.input.receivedFocus();
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;
3318 3304 }
3319 - restartBlink(cm);
3320 3305 }
3321 - function onBlur(cm, e) {
3322 - if (cm.state.delayingBlurEvent) { return }
3306 + return {from: from, to: Math.max(to, from + 1)}
3307 +}
3323 3308
3324 - if (cm.state.focused) {
3325 - signal(cm, "blur", cm, e);
3326 - cm.state.focused = false;
3327 - rmClass(cm.display.wrapper, "CodeMirror-focused");
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; }
3328 3322 }
3329 - clearInterval(cm.display.blinker);
3330 - setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
3331 - }
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 +}
3332 3330
3333 - // Read the actual heights of the rendered lines, and update their
3334 - // stored heights to match.
3335 - function updateHeightsInViewport(cm) {
3336 - var display = cm.display;
3337 - var prevBottom = display.lineDiv.offsetTop;
3338 - for (var i = 0; i < display.view.length; i++) {
3339 - var cur = display.view[i], wrapping = cm.options.lineWrapping;
3340 - var height = (void 0), width = 0;
3341 - if (cur.hidden) { continue }
3342 - if (ie && ie_version < 8) {
3343 - var bot = cur.node.offsetTop + cur.node.offsetHeight;
3344 - height = bot - prevBottom;
3345 - prevBottom = bot;
3346 - } else {
3347 - var box = cur.node.getBoundingClientRect();
3348 - height = box.bottom - box.top;
3349 - // Check that lines don't extend past the right of the current
3350 - // editor width
3351 - if (!wrapping && cur.text.firstChild)
3352 - { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
3353 - }
3354 - var diff = cur.line.height - height;
3355 - if (diff > .005 || diff < -.005) {
3356 - updateLineHeight(cur.line, height);
3357 - updateWidgetHeight(cur.line);
3358 - if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
3359 - { updateWidgetHeight(cur.rest[j]); } }
3360 - }
3361 - if (width > cm.display.sizerWidth) {
3362 - var chWidth = Math.ceil(width / charWidth(cm.display));
3363 - if (chWidth > cm.display.maxLineLength) {
3364 - cm.display.maxLineLength = chWidth;
3365 - cm.display.maxLine = cur.line;
3366 - cm.display.maxLineChanged = true;
3367 - }
3368 - }
3369 - }
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
3370 3348 }
3349 + return false
3350 +}
3371 3351
3372 - // Read and store the height of line widgets associated with the
3373 - // given line.
3374 - function updateWidgetHeight(line) {
3375 - if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
3376 - var w = line.widgets[i], parent = w.node.parentNode;
3377 - if (parent) { w.height = parent.offsetHeight; }
3378 - } }
3379 - }
3352 +// SCROLLING THINGS INTO VIEW
3380 3353
3381 - // Compute the lines that are visible in a given viewport (defaults
3382 - // the the current scroll position). viewport may contain top,
3383 - // height, and ensure (see op.scrollToPos) properties.
3384 - function visibleLines(display, doc, viewport) {
3385 - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
3386 - top = Math.floor(top - paddingTop(display));
3387 - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
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 }
3388 3358
3389 - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
3390 - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
3391 - // forces those lines into the viewport (if possible).
3392 - if (viewport && viewport.ensure) {
3393 - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
3394 - if (ensureFrom < from) {
3395 - from = ensureFrom;
3396 - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
3397 - } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
3398 - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
3399 - to = ensureTo;
3400 - }
3401 - }
3402 - return {from: from, to: Math.max(to, from + 1)}
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);
3403 3367 }
3368 +}
3404 3369
3405 - // SCROLLING THINGS INTO VIEW
3406 -
3407 - // If an editor sits on the top or bottom of the window, partially
3408 - // scrolled out of view, this ensures that the cursor is visible.
3409 - function maybeScrollWindow(cm, rect) {
3410 - if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
3411 -
3412 - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
3413 - if (rect.top + box.top < 0) { doScroll = true; }
3414 - else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
3415 - if (doScroll != null && !phantom) {
3416 - 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;"));
3417 - cm.display.lineSpace.appendChild(scrollNode);
3418 - scrollNode.scrollIntoView(doScroll);
3419 - cm.display.lineSpace.removeChild(scrollNode);
3420 - }
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;
3421 3382 }
3422 -
3423 - // Scroll a given position into view (immediately), verifying that
3424 - // it actually became visible (as line heights are accurately
3425 - // measured, the position of something may 'drift' during drawing).
3426 - function scrollPosIntoView(cm, pos, end, margin) {
3427 - if (margin == null) { margin = 0; }
3428 - var rect;
3429 - if (!cm.options.lineWrapping && pos == end) {
3430 - // Set pos and end to the cursor positions around the character pos sticks to
3431 - // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
3432 - // If pos == Pos(_, 0, "before"), pos and end are unchanged
3433 - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
3434 - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
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; }
3435 3396 }
3436 - for (var limit = 0; limit < 5; limit++) {
3437 - var changed = false;
3438 - var coords = cursorCoords(cm, pos);
3439 - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3440 - rect = {left: Math.min(coords.left, endCoords.left),
3441 - top: Math.min(coords.top, endCoords.top) - margin,
3442 - right: Math.max(coords.left, endCoords.left),
3443 - bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
3444 - var scrollPos = calculateScrollPos(cm, rect);
3445 - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3446 - if (scrollPos.scrollTop != null) {
3447 - updateScrollTop(cm, scrollPos.scrollTop);
3448 - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
3449 - }
3450 - if (scrollPos.scrollLeft != null) {
3451 - setScrollLeft(cm, scrollPos.scrollLeft);
3452 - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3453 - }
3454 - if (!changed) { break }
3397 + if (scrollPos.scrollLeft != null) {
3398 + setScrollLeft(cm, scrollPos.scrollLeft);
3399 + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
3455 3400 }
3456 - return rect
3401 + if (!changed) { break }
3457 3402 }
3403 + return rect
3404 +}
3458 3405
3459 - // Scroll a given set of coordinates into view (immediately).
3460 - function scrollIntoView(cm, rect) {
3461 - var scrollPos = calculateScrollPos(cm, rect);
3462 - if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
3463 - if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
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; }
3464 3430 }
3465 3431
3466 - // Calculate a new scroll position needed to scroll the given
3467 - // rectangle into view. Returns an object with scrollTop and
3468 - // scrollLeft properties. When these are undefined, the
3469 - // vertical/horizontal position does not need to be adjusted.
3470 - function calculateScrollPos(cm, rect) {
3471 - var display = cm.display, snapMargin = textHeight(cm.display);
3472 - if (rect.top < 0) { rect.top = 0; }
3473 - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3474 - var screen = displayHeight(cm), result = {};
3475 - if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
3476 - var docBottom = cm.doc.height + paddingVert(display);
3477 - var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
3478 - if (rect.top < screentop) {
3479 - result.scrollTop = atTop ? 0 : rect.top;
3480 - } else if (rect.bottom > screentop + screen) {
3481 - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
3482 - if (newTop != screentop) { result.scrollTop = newTop; }
3483 - }
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 +}
3484 3444
3485 - var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
3486 - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
3487 - var screenw = displayWidth(cm) - display.gutters.offsetWidth;
3488 - var tooWide = rect.right - rect.left > screenw;
3489 - if (tooWide) { rect.right = rect.left + screenw; }
3490 - if (rect.left < 10)
3491 - { result.scrollLeft = 0; }
3492 - else if (rect.left < screenleft)
3493 - { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
3494 - else if (rect.right > screenw + screenleft - 3)
3495 - { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
3496 - return result
3497 - }
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 +}
3498 3452
3499 - // Store a relative adjustment to the scroll position in the current
3500 - // operation (to be applied when the operation finishes).
3501 - function addToScrollTop(cm, top) {
3502 - if (top == null) { return }
3503 - resolveScrollToPos(cm);
3504 - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3505 - }
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 +}
3506 3460
3507 - // Make sure that at the end of the operation the current cursor is
3508 - // shown.
3509 - function ensureCursorVisible(cm) {
3510 - resolveScrollToPos(cm);
3511 - var cur = cm.getCursor();
3512 - cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
3513 - }
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 +}
3514 3466
3515 - function scrollToCoords(cm, x, y) {
3516 - if (x != null || y != null) { resolveScrollToPos(cm); }
3517 - if (x != null) { cm.curOp.scrollLeft = x; }
3518 - if (y != null) { cm.curOp.scrollTop = y; }
3519 - }
3467 +function scrollToRange(cm, range$$1) {
3468 + resolveScrollToPos(cm);
3469 + cm.curOp.scrollToPos = range$$1;
3470 +}
3520 3471
3521 - function scrollToRange(cm, range) {
3522 - resolveScrollToPos(cm);
3523 - cm.curOp.scrollToPos = range;
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);
3524 3482 }
3483 +}
3525 3484
3526 - // When an operation has its scrollToPos property set, and another
3527 - // scroll action is applied before the end of the operation, this
3528 - // 'simulates' scrolling that position into view in a cheap way, so
3529 - // that the effect of intermediate scroll commands is not ignored.
3530 - function resolveScrollToPos(cm) {
3531 - var range = cm.curOp.scrollToPos;
3532 - if (range) {
3533 - cm.curOp.scrollToPos = null;
3534 - var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
3535 - scrollToCoordsRange(cm, from, to, range.margin);
3536 - }
3537 - }
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 +}
3538 3494
3539 - function scrollToCoordsRange(cm, from, to, margin) {
3540 - var sPos = calculateScrollPos(cm, {
3541 - left: Math.min(from.left, to.left),
3542 - top: Math.min(from.top, to.top) - margin,
3543 - right: Math.max(from.right, to.right),
3544 - bottom: Math.max(from.bottom, to.bottom) + margin
3545 - });
3546 - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
3547 - }
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 +}
3548 3504
3549 - // Sync the scrollable area and scrollbars, ensure the viewport
3550 - // covers the visible area.
3551 - function updateScrollTop(cm, val) {
3552 - if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
3553 - if (!gecko) { updateDisplaySimple(cm, {top: val}); }
3554 - setScrollTop(cm, val, true);
3555 - if (gecko) { updateDisplaySimple(cm); }
3556 - startWorker(cm, 100);
3557 - }
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 +}
3558 3512
3559 - function setScrollTop(cm, val, forceScroll) {
3560 - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
3561 - if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
3562 - cm.doc.scrollTop = val;
3563 - cm.display.scrollbars.setScrollTop(val);
3564 - if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
3565 - }
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 +}
3566 3523
3567 - // Sync scroller and scrollbar, ensure the gutter elements are
3568 - // aligned.
3569 - function setScrollLeft(cm, val, isScroller, forceScroll) {
3570 - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
3571 - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
3572 - cm.doc.scrollLeft = val;
3573 - alignHorizontally(cm);
3574 - if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
3575 - cm.display.scrollbars.setScrollLeft(val);
3576 - }
3524 +// SCROLLBARS
3577 3525
3578 - // SCROLLBARS
3579 -
3580 - // Prepare DOM reads needed to update the scrollbars. Done in one
3581 - // shot to minimize update/measure roundtrips.
3582 - function measureForScrollbars(cm) {
3583 - var d = cm.display, gutterW = d.gutters.offsetWidth;
3584 - var docH = Math.round(cm.doc.height + paddingVert(cm.display));
3585 - return {
3586 - clientHeight: d.scroller.clientHeight,
3587 - viewHeight: d.wrapper.clientHeight,
3588 - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
3589 - viewWidth: d.wrapper.clientWidth,
3590 - barLeft: cm.options.fixedGutter ? gutterW : 0,
3591 - docHeight: docH,
3592 - scrollHeight: docH + scrollGap(cm) + d.barHeight,
3593 - nativeBarWidth: d.nativeBarWidth,
3594 - gutterWidth: gutterW
3595 - }
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
3596 3541 }
3542 +}
3597 3543
3598 - var NativeScrollbars = function(place, scroll, cm) {
3599 - this.cm = cm;
3600 - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
3601 - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
3602 - vert.tabIndex = horiz.tabIndex = -1;
3603 - place(vert); place(horiz);
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);
3604 3549
3605 - on(vert, "scroll", function () {
3606 - if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
3607 - });
3608 - on(horiz, "scroll", function () {
3609 - if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
3610 - });
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 + });
3611 3556
3612 - this.checkedZeroWidth = false;
3613 - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
3614 - if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
3615 - };
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 +};
3616 3561
3617 - NativeScrollbars.prototype.update = function (measure) {
3618 - var needsH = measure.scrollWidth > measure.clientWidth + 1;
3619 - var needsV = measure.scrollHeight > measure.clientHeight + 1;
3620 - var sWidth = measure.nativeBarWidth;
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;
3621 3566
3622 - if (needsV) {
3623 - this.vert.style.display = "block";
3624 - this.vert.style.bottom = needsH ? sWidth + "px" : "0";
3625 - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
3626 - // A bug in IE8 can cause this value to be negative, so guard it.
3627 - this.vert.firstChild.style.height =
3628 - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
3629 - } else {
3630 - this.vert.style.display = "";
3631 - this.vert.firstChild.style.height = "0";
3632 - }
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 + }
3633 3578
3634 - if (needsH) {
3635 - this.horiz.style.display = "block";
3636 - this.horiz.style.right = needsV ? sWidth + "px" : "0";
3637 - this.horiz.style.left = measure.barLeft + "px";
3638 - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
3639 - this.horiz.firstChild.style.width =
3640 - Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
3641 - } else {
3642 - this.horiz.style.display = "";
3643 - this.horiz.firstChild.style.width = "0";
3644 - }
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 + }
3645 3590
3646 - if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3647 - if (sWidth == 0) { this.zeroWidthHack(); }
3648 - this.checkedZeroWidth = true;
3649 - }
3591 + if (!this.checkedZeroWidth && measure.clientHeight > 0) {
3592 + if (sWidth == 0) { this.zeroWidthHack(); }
3593 + this.checkedZeroWidth = true;
3594 + }
3650 3595
3651 - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3652 - };
3596 + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
3597 +};
3653 3598
3654 - NativeScrollbars.prototype.setScrollLeft = function (pos) {
3655 - if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
3656 - if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
3657 - };
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 +};
3658 3603
3659 - NativeScrollbars.prototype.setScrollTop = function (pos) {
3660 - if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
3661 - if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
3662 - };
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 +};
3663 3608
3664 - NativeScrollbars.prototype.zeroWidthHack = function () {
3665 - var w = mac && !mac_geMountainLion ? "12px" : "18px";
3666 - this.horiz.style.height = this.vert.style.width = w;
3667 - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
3668 - this.disableHoriz = new Delayed;
3669 - this.disableVert = new Delayed;
3670 - };
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 +};
3671 3616
3672 - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
3673 - bar.style.pointerEvents = "auto";
3674 - function maybeDisable() {
3675 - // To find out whether the scrollbar is still visible, we
3676 - // check whether the element under the pixel in the bottom
3677 - // right corner of the scrollbar box is the scrollbar box
3678 - // itself (when the bar is still visible) or its filler child
3679 - // (when the bar is hidden). If it is still visible, we keep
3680 - // it enabled, if it's hidden, we disable pointer events.
3681 - var box = bar.getBoundingClientRect();
3682 - var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
3683 - : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
3684 - if (elt != bar) { bar.style.pointerEvents = "none"; }
3685 - else { delay.set(1000, maybeDisable); }
3686 - }
3687 - delay.set(1000, maybeDisable);
3688 - };
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 +};
3689 3634
3690 - NativeScrollbars.prototype.clear = function () {
3691 - var parent = this.horiz.parentNode;
3692 - parent.removeChild(this.horiz);
3693 - parent.removeChild(this.vert);
3694 - };
3635 +NativeScrollbars.prototype.clear = function () {
3636 + var parent = this.horiz.parentNode;
3637 + parent.removeChild(this.horiz);
3638 + parent.removeChild(this.vert);
3639 +};
3695 3640
3696 - var NullScrollbars = function () {};
3641 +var NullScrollbars = function () {};
3697 3642
3698 - NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
3699 - NullScrollbars.prototype.setScrollLeft = function () {};
3700 - NullScrollbars.prototype.setScrollTop = function () {};
3701 - NullScrollbars.prototype.clear = function () {};
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 () {};
3702 3647
3703 - function updateScrollbars(cm, measure) {
3704 - if (!measure) { measure = measureForScrollbars(cm); }
3705 - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
3706 - updateScrollbarsInner(cm, measure);
3707 - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
3708 - if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
3709 - { updateHeightsInViewport(cm); }
3710 - updateScrollbarsInner(cm, measureForScrollbars(cm));
3711 - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
3712 - }
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;
3713 3657 }
3658 +}
3714 3659
3715 - // Re-synchronize the fake scrollbars with the actual size of the
3716 - // content.
3717 - function updateScrollbarsInner(cm, measure) {
3718 - var d = cm.display;
3719 - var sizes = d.scrollbars.update(measure);
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);
3720 3665
3721 - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
3722 - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
3723 - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
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";
3724 3669
3725 - if (sizes.right && sizes.bottom) {
3726 - d.scrollbarFiller.style.display = "block";
3727 - d.scrollbarFiller.style.height = sizes.bottom + "px";
3728 - d.scrollbarFiller.style.width = sizes.right + "px";
3729 - } else { d.scrollbarFiller.style.display = ""; }
3730 - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
3731 - d.gutterFiller.style.display = "block";
3732 - d.gutterFiller.style.height = sizes.bottom + "px";
3733 - d.gutterFiller.style.width = measure.gutterWidth + "px";
3734 - } else { d.gutterFiller.style.display = ""; }
3735 - }
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 +}
3736 3681
3737 - var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3682 +var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
3738 3683
3739 - function initScrollbars(cm) {
3740 - if (cm.display.scrollbars) {
3741 - cm.display.scrollbars.clear();
3742 - if (cm.display.scrollbars.addClass)
3743 - { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3744 - }
3745 -
3746 - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
3747 - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
3748 - // Prevent clicks in the scrollbars from killing focus
3749 - on(node, "mousedown", function () {
3750 - if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
3751 - });
3752 - node.setAttribute("cm-not-content", "true");
3753 - }, function (pos, axis) {
3754 - if (axis == "horizontal") { setScrollLeft(cm, pos); }
3755 - else { updateScrollTop(cm, pos); }
3756 - }, cm);
3684 +function initScrollbars(cm) {
3685 + if (cm.display.scrollbars) {
3686 + cm.display.scrollbars.clear();
3757 3687 if (cm.display.scrollbars.addClass)
3758 - { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3688 + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
3759 3689 }
3760 3690
3761 - // Operations are used to wrap a series of changes to the editor
3762 - // state in such a way that each change won't have to update the
3763 - // cursor and display (which would be awkward, slow, and
3764 - // error-prone). Instead, display updates are batched and then all
3765 - // combined and executed at once.
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 +}
3766 3705
3767 - var nextOpId = 0;
3768 - // Start a new operation.
3769 - function startOperation(cm) {
3770 - cm.curOp = {
3771 - cm: cm,
3772 - viewChanged: false, // Flag that indicates that lines might need to be redrawn
3773 - startHeight: cm.doc.height, // Used to detect need to update scrollbar
3774 - forceUpdate: false, // Used to force a redraw
3775 - updateInput: 0, // Whether to reset the input textarea
3776 - typing: false, // Whether this reset should be careful to leave existing text (for compositing)
3777 - changeObjs: null, // Accumulated changes, for firing change events
3778 - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3779 - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3780 - selectionChanged: false, // Whether the selection needs to be redrawn
3781 - updateMaxLine: false, // Set when the widest line needs to be determined anew
3782 - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3783 - scrollToPos: null, // Used to scroll to a specific position
3784 - focus: false,
3785 - id: ++nextOpId // Unique ID
3786 - };
3787 - pushOperation(cm.curOp);
3788 - }
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.
3789 3711
3790 - // Finish an operation, updating the display and signalling delayed events
3791 - function endOperation(cm) {
3792 - var op = cm.curOp;
3793 - if (op) { finishOperation(op, function (group) {
3794 - for (var i = 0; i < group.ops.length; i++)
3795 - { group.ops[i].cm.curOp = null; }
3796 - endOperations(group);
3797 - }); }
3798 - }
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 +}
3799 3734
3800 - // The DOM updates done when an operation finishes are batched so
3801 - // that the minimum number of relayouts are required.
3802 - function endOperations(group) {
3803 - var ops = group.ops;
3804 - for (var i = 0; i < ops.length; i++) // Read DOM
3805 - { endOperation_R1(ops[i]); }
3806 - for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
3807 - { endOperation_W1(ops[i$1]); }
3808 - for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
3809 - { endOperation_R2(ops[i$2]); }
3810 - for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
3811 - { endOperation_W2(ops[i$3]); }
3812 - for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
3813 - { endOperation_finish(ops[i$4]); }
3814 - }
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 +}
3815 3744
3816 - function endOperation_R1(op) {
3817 - var cm = op.cm, display = cm.display;
3818 - maybeClipScrollbars(cm);
3819 - if (op.updateMaxLine) { findMaxLine(cm); }
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 +}
3820 3760
3821 - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3822 - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3823 - op.scrollToPos.to.line >= display.viewTo) ||
3824 - display.maxLineChanged && cm.options.lineWrapping;
3825 - op.update = op.mustUpdate &&
3826 - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3827 - }
3761 +function endOperation_R1(op) {
3762 + var cm = op.cm, display = cm.display;
3763 + maybeClipScrollbars(cm);
3764 + if (op.updateMaxLine) { findMaxLine(cm); }
3828 3765
3829 - function endOperation_W1(op) {
3830 - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3831 - }
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 +}
3832 3773
3833 - function endOperation_R2(op) {
3834 - var cm = op.cm, display = cm.display;
3835 - if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3774 +function endOperation_W1(op) {
3775 + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3776 +}
3836 3777
3837 - op.barMeasure = measureForScrollbars(cm);
3778 +function endOperation_R2(op) {
3779 + var cm = op.cm, display = cm.display;
3780 + if (op.updatedDisplay) { updateHeightsInViewport(cm); }
3838 3781
3839 - // If the max line changed since it was last measured, measure it,
3840 - // and ensure the document's width matches it.
3841 - // updateDisplay_W2 will use these properties to do the actual resizing
3842 - if (display.maxLineChanged && !cm.options.lineWrapping) {
3843 - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3844 - cm.display.sizerWidth = op.adjustWidthTo;
3845 - op.barMeasure.scrollWidth =
3846 - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3847 - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3848 - }
3782 + op.barMeasure = measureForScrollbars(cm);
3849 3783
3850 - if (op.updatedDisplay || op.selectionChanged)
3851 - { op.preparedSelection = display.input.prepareSelection(); }
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));
3852 3793 }
3853 3794
3854 - function endOperation_W2(op) {
3855 - var cm = op.cm;
3795 + if (op.updatedDisplay || op.selectionChanged)
3796 + { op.preparedSelection = display.input.prepareSelection(); }
3797 +}
3856 3798
3857 - if (op.adjustWidthTo != null) {
3858 - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3859 - if (op.maxScrollLeft < cm.doc.scrollLeft)
3860 - { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
3861 - cm.display.maxLineChanged = false;
3862 - }
3799 +function endOperation_W2(op) {
3800 + var cm = op.cm;
3863 3801
3864 - var takeFocus = op.focus && op.focus == activeElt();
3865 - if (op.preparedSelection)
3866 - { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
3867 - if (op.updatedDisplay || op.startHeight != cm.doc.height)
3868 - { updateScrollbars(cm, op.barMeasure); }
3869 - if (op.updatedDisplay)
3870 - { setDocumentHeight(cm, op.barMeasure); }
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 + }
3871 3808
3872 - if (op.selectionChanged) { restartBlink(cm); }
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); }
3873 3816
3874 - if (cm.state.focused && op.updateInput)
3875 - { cm.display.input.reset(op.typing); }
3876 - if (takeFocus) { ensureFocus(op.cm); }
3877 - }
3817 + if (op.selectionChanged) { restartBlink(cm); }
3878 3818
3879 - function endOperation_finish(op) {
3880 - var cm = op.cm, display = cm.display, doc = cm.doc;
3819 + if (cm.state.focused && op.updateInput)
3820 + { cm.display.input.reset(op.typing); }
3821 + if (takeFocus) { ensureFocus(op.cm); }
3822 +}
3881 3823
3882 - if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3824 +function endOperation_finish(op) {
3825 + var cm = op.cm, display = cm.display, doc = cm.doc;
3883 3826
3884 - // Abort mouse wheel delta measurement, when scrolling explicitly
3885 - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3886 - { display.wheelStartX = display.wheelStartY = null; }
3827 + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
3887 3828
3888 - // Propagate the scroll position to the actual DOM scroller
3889 - if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
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; }
3890 3832
3891 - if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
3892 - // If we need to scroll a specific position into view, do so.
3893 - if (op.scrollToPos) {
3894 - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3895 - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3896 - maybeScrollWindow(cm, rect);
3897 - }
3833 + // Propagate the scroll position to the actual DOM scroller
3834 + if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
3898 3835
3899 - // Fire events for markers that are hidden/unidden by editing or
3900 - // undoing
3901 - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3902 - if (hidden) { for (var i = 0; i < hidden.length; ++i)
3903 - { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
3904 - if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
3905 - { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
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 + }
3906 3843
3907 - if (display.wrapper.offsetHeight)
3908 - { doc.scrollTop = cm.display.scroller.scrollTop; }
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"); } } }
3909 3851
3910 - // Fire change events, and delayed event handlers
3911 - if (op.changeObjs)
3912 - { signal(cm, "changes", cm, op.changeObjs); }
3913 - if (op.update)
3914 - { op.update.finish(); }
3915 - }
3852 + if (display.wrapper.offsetHeight)
3853 + { doc.scrollTop = cm.display.scroller.scrollTop; }
3916 3854
3917 - // Run the given function in an operation
3918 - function runInOp(cm, f) {
3919 - if (cm.curOp) { return f() }
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) }
3920 3873 startOperation(cm);
3921 - try { return f() }
3874 + try { return f.apply(cm, arguments) }
3922 3875 finally { endOperation(cm); }
3923 3876 }
3924 - // Wraps a function in an operation. Returns the wrapped function.
3925 - function operation(cm, f) {
3926 - return function() {
3927 - if (cm.curOp) { return f.apply(cm, arguments) }
3928 - startOperation(cm);
3929 - try { return f.apply(cm, arguments) }
3930 - finally { endOperation(cm); }
3931 - }
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); }
3932 3886 }
3933 - // Used to add methods to editor and doc instances, wrapping them in
3934 - // operations.
3935 - function methodOp(f) {
3936 - return function() {
3937 - if (this.curOp) { return f.apply(this, arguments) }
3938 - startOperation(this);
3939 - try { return f.apply(this, arguments) }
3940 - finally { endOperation(this); }
3941 - }
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); }
3942 3895 }
3943 - function docMethodOp(f) {
3944 - return function() {
3945 - var cm = this.cm;
3946 - if (!cm || cm.curOp) { return f.apply(this, arguments) }
3947 - startOperation(cm);
3948 - try { return f.apply(this, arguments) }
3949 - finally { endOperation(cm); }
3950 - }
3951 - }
3896 +}
3952 3897
3953 - // HIGHLIGHT WORKER
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; }
3954 3908
3955 - function startWorker(cm, time) {
3956 - if (cm.doc.highlightFrontier < cm.display.viewTo)
3957 - { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
3958 - }
3909 + var display = cm.display;
3910 + if (lendiff && to < display.viewTo &&
3911 + (display.updateLineNumbers == null || display.updateLineNumbers > from))
3912 + { display.updateLineNumbers = from; }
3959 3913
3960 - function highlightWorker(cm) {
3961 - var doc = cm.doc;
3962 - if (doc.highlightFrontier >= cm.display.viewTo) { return }
3963 - var end = +new Date + cm.options.workTime;
3964 - var context = getContextBefore(cm, doc.highlightFrontier);
3965 - var changedLines = [];
3914 + cm.curOp.viewChanged = true;
3966 3915
3967 - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
3968 - if (context.line >= cm.display.viewFrom) { // Visible
3969 - var oldStyles = line.styles;
3970 - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
3971 - var highlighted = highlightLine(cm, line, context, true);
3972 - if (resetState) { context.state = resetState; }
3973 - line.styles = highlighted.styles;
3974 - var oldCls = line.styleClasses, newCls = highlighted.classes;
3975 - if (newCls) { line.styleClasses = newCls; }
3976 - else if (oldCls) { line.styleClasses = null; }
3977 - var ischange = !oldStyles || oldStyles.length != line.styles.length ||
3978 - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
3979 - for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
3980 - if (ischange) { changedLines.push(context.line); }
3981 - line.stateAfter = context.save();
3982 - context.nextLine();
3983 - } else {
3984 - if (line.text.length <= cm.options.maxHighlightLength)
3985 - { processLine(cm, line.text, context); }
3986 - line.stateAfter = context.line % 5 == 0 ? context.save() : null;
3987 - context.nextLine();
3988 - }
3989 - if (+new Date > end) {
3990 - startWorker(cm, cm.options.workDelay);
3991 - return true
3992 - }
3993 - });
3994 - doc.highlightFrontier = context.line;
3995 - doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
3996 - if (changedLines.length) { runInOp(cm, function () {
3997 - for (var i = 0; i < changedLines.length; i++)
3998 - { regLineChange(cm, changedLines[i], "text"); }
3999 - }); }
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 + }
4000 3956 }
4001 3957
4002 - // DISPLAY DRAWING
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 +}
4003 3966
4004 - var DisplayUpdate = function(cm, viewport, force) {
4005 - var display = cm.display;
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; }
4006 3974
4007 - this.viewport = viewport;
4008 - // Store some values that we'll need later (but don't want to force a relayout for)
4009 - this.visible = visibleLines(display, cm.doc, viewport);
4010 - this.editorIsHidden = !display.wrapper.offsetWidth;
4011 - this.wrapperHeight = display.wrapper.clientHeight;
4012 - this.wrapperWidth = display.wrapper.clientWidth;
4013 - this.oldDisplayWidth = displayWidth(cm);
4014 - this.force = force;
4015 - this.dims = getDimensions(cm);
4016 - this.events = [];
4017 - };
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 +}
4018 3981
4019 - DisplayUpdate.prototype.signal = function (emitter, type) {
4020 - if (hasHandler(emitter, type))
4021 - { this.events.push(arguments); }
4022 - };
4023 - DisplayUpdate.prototype.finish = function () {
4024 - for (var i = 0; i < this.events.length; i++)
4025 - { signal.apply(null, this.events[i]); }
4026 - };
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 +}
4027 3988
4028 - function maybeClipScrollbars(cm) {
4029 - var display = cm.display;
4030 - if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
4031 - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
4032 - display.heightForcer.style.height = scrollGap(cm) + "px";
4033 - display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
4034 - display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
4035 - display.scrollbarsClipped = true;
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;
4036 4003 }
4004 + oldN += diff; newN += diff;
4037 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 +}
4038 4013
4039 - function selectionSnapshot(cm) {
4040 - if (cm.hasFocus()) { return null }
4041 - var active = activeElt();
4042 - if (!active || !contains(cm.display.lineDiv, active)) { return null }
4043 - var result = {activeElt: active};
4044 - if (window.getSelection) {
4045 - var sel = window.getSelection();
4046 - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
4047 - result.anchorNode = sel.anchorNode;
4048 - result.anchorOffset = sel.anchorOffset;
4049 - result.focusNode = sel.focusNode;
4050 - result.focusOffset = sel.focusOffset;
4051 - }
4052 - }
4053 - return result
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)); }
4054 4031 }
4032 + display.viewTo = to;
4033 +}
4055 4034
4056 - function restoreSelection(snapshot) {
4057 - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
4058 - snapshot.activeElt.focus();
4059 - if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
4060 - snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
4061 - var sel = window.getSelection(), range = document.createRange();
4062 - range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
4063 - range.collapse(false);
4064 - sel.removeAllRanges();
4065 - sel.addRange(range);
4066 - sel.extend(snapshot.focusNode, snapshot.focusOffset);
4067 - }
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; }
4068 4042 }
4043 + return dirty
4044 +}
4069 4045
4070 - // Does the actual updating of the line display. Bails out
4071 - // (returning false) when there is nothing to be done and forced is
4072 - // false.
4073 - function updateDisplayIfNeeded(cm, update) {
4074 - var display = cm.display, doc = cm.doc;
4046 +// HIGHLIGHT WORKER
4075 4047
4076 - if (update.editorIsHidden) {
4077 - resetView(cm);
4078 - return false
4079 - }
4048 +function startWorker(cm, time) {
4049 + if (cm.doc.highlightFrontier < cm.display.viewTo)
4050 + { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
4051 +}
4080 4052
4081 - // Bail out if the visible area is already rendered and nothing changed.
4082 - if (!update.force &&
4083 - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
4084 - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
4085 - display.renderedView == display.view && countDirtyView(cm) == 0)
4086 - { return false }
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 = [];
4087 4059
4088 - if (maybeUpdateLineNumberWidth(cm)) {
4089 - resetView(cm);
4090 - update.dims = getDimensions(cm);
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();
4091 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 +}
4092 4094
4093 - // Compute a suitable new viewport (from & to)
4094 - var end = doc.first + doc.size;
4095 - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
4096 - var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
4097 - if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
4098 - if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
4099 - if (sawCollapsedSpans) {
4100 - from = visualLineNo(cm.doc, from);
4101 - to = visualLineEndNo(cm.doc, to);
4102 - }
4095 +// DISPLAY DRAWING
4103 4096
4104 - var different = from != display.viewFrom || to != display.viewTo ||
4105 - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
4106 - adjustView(cm, from, to);
4097 +var DisplayUpdate = function(cm, viewport, force) {
4098 + var display = cm.display;
4107 4099
4108 - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
4109 - // Position the mover div to align with the current scroll position
4110 - cm.display.mover.style.top = display.viewOffset + "px";
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 4111
4112 - var toUpdate = countDirtyView(cm);
4113 - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
4114 - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
4115 - { return false }
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;
4116 4118
4117 - // For big changes, we hide the enclosing element during the
4118 - // update, since that speeds up the operations on most browsers.
4119 - var selSnapshot = selectionSnapshot(cm);
4120 - if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
4121 - patchDisplay(cm, display.updateLineNumbers, update.dims);
4122 - if (toUpdate > 4) { display.lineDiv.style.display = ""; }
4123 - display.renderedView = display.view;
4124 - // There might have been a widget with a focused element that got
4125 - // hidden or updated, if so re-focus it.
4126 - restoreSelection(selSnapshot);
4119 + for (var i = 0; i < this.events.length; i++)
4120 + { signal.apply(null, this$1.events[i]); }
4121 +};
4127 4122
4128 - // Prevent selection and cursors from interfering with the scroll
4129 - // width and height.
4130 - removeChildren(display.cursorDiv);
4131 - removeChildren(display.selectionDiv);
4132 - display.gutters.style.height = display.sizer.style.minHeight = 0;
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 4133
4134 - if (different) {
4135 - display.lastWrapHeight = update.wrapperHeight;
4136 - display.lastWrapWidth = update.wrapperWidth;
4137 - startWorker(cm, 400);
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;
4138 4146 }
4147 + }
4148 + return result
4149 +}
4139 4150
4140 - display.updateLineNumbers = null;
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 +}
4141 4163
4142 - return true
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
4143 4173 }
4144 4174
4145 - function postUpdateDisplay(cm, update) {
4146 - var viewport = update.viewport;
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 }
4147 4181
4148 - for (var first = true;; first = false) {
4149 - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
4150 - // Clip forced viewport to actual scrollable area.
4151 - if (viewport && viewport.top != null)
4152 - { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
4153 - // Updated line heights might result in the drawn area not
4154 - // actually covering the viewport. Keep looping until it does.
4155 - update.visible = visibleLines(cm.display, cm.doc, viewport);
4156 - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
4157 - { break }
4158 - } else if (first) {
4159 - update.visible = visibleLines(cm.display, cm.doc, viewport);
4160 - }
4161 - if (!updateDisplayIfNeeded(cm, update)) { break }
4162 - updateHeightsInViewport(cm);
4163 - var barMeasure = measureForScrollbars(cm);
4164 - updateSelection(cm);
4165 - updateScrollbars(cm, barMeasure);
4166 - setDocumentHeight(cm, barMeasure);
4167 - update.force = false;
4168 - }
4182 + if (maybeUpdateLineNumberWidth(cm)) {
4183 + resetView(cm);
4184 + update.dims = getDimensions(cm);
4185 + }
4169 4186
4170 - update.signal(cm, "update", cm);
4171 - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
4172 - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
4173 - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
4174 - }
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);
4175 4196 }
4176 4197
4177 - function updateDisplaySimple(cm, viewport) {
4178 - var update = new DisplayUpdate(cm, viewport);
4179 - if (updateDisplayIfNeeded(cm, update)) {
4180 - updateHeightsInViewport(cm);
4181 - postUpdateDisplay(cm, update);
4182 - var barMeasure = measureForScrollbars(cm);
4183 - updateSelection(cm);
4184 - updateScrollbars(cm, barMeasure);
4185 - setDocumentHeight(cm, barMeasure);
4186 - update.finish();
4187 - }
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);
4188 4232 }
4189 4233
4190 - // Sync the actual display DOM structure with display.view, removing
4191 - // nodes for lines that are no longer in view, and creating the ones
4192 - // that are not there yet, and updating the ones that are out of
4193 - // date.
4194 - function patchDisplay(cm, updateNumbersFrom, dims) {
4195 - var display = cm.display, lineNumbers = cm.options.lineNumbers;
4196 - var container = display.lineDiv, cur = container.firstChild;
4234 + display.updateLineNumbers = null;
4197 4235
4198 - function rm(node) {
4199 - var next = node.nextSibling;
4200 - // Works around a throw-scroll bug in OS X Webkit
4201 - if (webkit && mac && cm.display.currentWheelTarget == node)
4202 - { node.style.display = "none"; }
4203 - else
4204 - { node.parentNode.removeChild(node); }
4205 - return next
4206 - }
4236 + return true
4237 +}
4207 4238
4208 - var view = display.view, lineN = display.viewFrom;
4209 - // Loop over the elements in the view, syncing cur (the DOM nodes
4210 - // in display.lineDiv) with the view as we go.
4211 - for (var i = 0; i < view.length; i++) {
4212 - var lineView = view[i];
4213 - if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
4214 - var node = buildLineElement(cm, lineView, lineN, dims);
4215 - container.insertBefore(node, cur);
4216 - } else { // Already drawn
4217 - while (cur != lineView.node) { cur = rm(cur); }
4218 - var updateNumber = lineNumbers && updateNumbersFrom != null &&
4219 - updateNumbersFrom <= lineN && lineView.lineNumber;
4220 - if (lineView.changes) {
4221 - if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
4222 - updateLineForChanges(cm, lineView, lineN, dims);
4223 - }
4224 - if (updateNumber) {
4225 - removeChildren(lineView.lineNumber);
4226 - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4227 - }
4228 - cur = lineView.node.nextSibling;
4229 - }
4230 - lineN += lineView.size;
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 }
4231 4252 }
4232 - while (cur) { cur = rm(cur); }
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;
4233 4260 }
4234 4261
4235 - function updateGutterSpace(display) {
4236 - var width = display.gutters.offsetWidth;
4237 - display.sizer.style.marginLeft = width + "px";
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;
4238 4266 }
4267 +}
4239 4268
4240 - function setDocumentHeight(cm, measure) {
4241 - cm.display.sizer.style.minHeight = measure.docHeight + "px";
4242 - cm.display.heightForcer.style.top = measure.docHeight + "px";
4243 - cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
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();
4244 4279 }
4280 +}
4245 4281
4246 - // Re-align line numbers and gutter marks to compensate for
4247 - // horizontal scrolling.
4248 - function alignHorizontally(cm) {
4249 - var display = cm.display, view = display.view;
4250 - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
4251 - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
4252 - var gutterW = display.gutters.offsetWidth, left = comp + "px";
4253 - for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
4254 - if (cm.options.fixedGutter) {
4255 - if (view[i].gutter)
4256 - { view[i].gutter.style.left = left; }
4257 - if (view[i].gutterBackground)
4258 - { view[i].gutterBackground.style.left = left; }
4259 - }
4260 - var align = view[i].alignable;
4261 - if (align) { for (var j = 0; j < align.length; j++)
4262 - { align[j].style.left = left; } }
4263 - } }
4264 - if (cm.options.fixedGutter)
4265 - { display.gutters.style.left = (comp + gutterW) + "px"; }
4266 - }
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;
4267 4289
4268 - // Used to ensure that the line number gutter is still the right
4269 - // size for the current document size. Returns true when an update
4270 - // is needed.
4271 - function maybeUpdateLineNumberWidth(cm) {
4272 - if (!cm.options.lineNumbers) { return false }
4273 - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
4274 - if (last.length != display.lineNumChars) {
4275 - var test = display.measure.appendChild(elt("div", [elt("div", last)],
4276 - "CodeMirror-linenumber CodeMirror-gutter-elt"));
4277 - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
4278 - display.lineGutter.style.width = "";
4279 - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
4280 - display.lineNumWidth = display.lineNumInnerWidth + padding;
4281 - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
4282 - display.lineGutter.style.width = display.lineNumWidth + "px";
4283 - updateGutterSpace(cm.display);
4284 - return true
4285 - }
4286 - return false
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
4287 4298 }
4288 4299
4289 - function getGutters(gutters, lineNumbers) {
4290 - var result = [], sawLineNumbers = false;
4291 - for (var i = 0; i < gutters.length; i++) {
4292 - var name = gutters[i], style = null;
4293 - if (typeof name != "string") { style = name.style; name = name.className; }
4294 - if (name == "CodeMirror-linenumbers") {
4295 - if (!lineNumbers) { continue }
4296 - else { sawLineNumbers = true; }
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);
4297 4316 }
4298 - result.push({className: name, style: style});
4299 - }
4300 - if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
4301 - return result
4302 - }
4303 -
4304 - // Rebuild the gutter elements, ensure the margin to the left of the
4305 - // code matches their width.
4306 - function renderGutters(display) {
4307 - var gutters = display.gutters, specs = display.gutterSpecs;
4308 - removeChildren(gutters);
4309 - display.lineGutter = null;
4310 - for (var i = 0; i < specs.length; ++i) {
4311 - var ref = specs[i];
4312 - var className = ref.className;
4313 - var style = ref.style;
4314 - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
4315 - if (style) { gElt.style.cssText = style; }
4316 - if (className == "CodeMirror-linenumbers") {
4317 - display.lineGutter = gElt;
4318 - gElt.style.width = (display.lineNumWidth || 1) + "px";
4317 + if (updateNumber) {
4318 + removeChildren(lineView.lineNumber);
4319 + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
4319 4320 }
4321 + cur = lineView.node.nextSibling;
4320 4322 }
4321 - gutters.style.display = specs.length ? "" : "none";
4322 - updateGutterSpace(display);
4323 + lineN += lineView.size;
4323 4324 }
4325 + while (cur) { cur = rm(cur); }
4326 +}
4324 4327
4325 - function updateGutters(cm) {
4326 - renderGutters(cm.display);
4327 - regChange(cm);
4328 - alignHorizontally(cm);
4329 - }
4328 +function updateGutterSpace(cm) {
4329 + var width = cm.display.gutters.offsetWidth;
4330 + cm.display.sizer.style.marginLeft = width + "px";
4331 +}
4330 4332
4331 - // The display handles the DOM integration, both for input reading
4332 - // and content drawing. It holds references to DOM nodes and
4333 - // display-related state.
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 +}
4334 4338
4335 - function Display(place, doc, input, options) {
4336 - var d = this;
4337 - this.input = input;
4338 -
4339 - // Covers bottom-right square when both scrollbars are present.
4340 - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
4341 - d.scrollbarFiller.setAttribute("cm-not-content", "true");
4342 - // Covers bottom of gutter when coverGutterNextToScrollbar is on
4343 - // and h scrollbar is present.
4344 - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
4345 - d.gutterFiller.setAttribute("cm-not-content", "true");
4346 - // Will contain the actual code, positioned to cover the viewport.
4347 - d.lineDiv = eltP("div", null, "CodeMirror-code");
4348 - // Elements are added to these to represent selection and cursors.
4349 - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
4350 - d.cursorDiv = elt("div", null, "CodeMirror-cursors");
4351 - // A visibility: hidden element used to find the size of things.
4352 - d.measure = elt("div", null, "CodeMirror-measure");
4353 - // When lines outside of the viewport are measured, they are drawn in this.
4354 - d.lineMeasure = elt("div", null, "CodeMirror-measure");
4355 - // Wraps everything that needs to exist inside the vertically-padded coordinate system
4356 - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
4357 - null, "position: relative; outline: none");
4358 - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
4359 - // Moved around its parent to cover visible view.
4360 - d.mover = elt("div", [lines], null, "position: relative");
4361 - // Set to the height of the document, allowing scrolling.
4362 - d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
4363 - d.sizerWidth = null;
4364 - // Behavior of elts with overflow: auto and padding is
4365 - // inconsistent across browsers. This is used to ensure the
4366 - // scrollable area is big enough.
4367 - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
4368 - // Will contain the gutters, if any.
4369 - d.gutters = elt("div", null, "CodeMirror-gutters");
4370 - d.lineGutter = null;
4371 - // Actual scrollable element.
4372 - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
4373 - d.scroller.setAttribute("tabIndex", "-1");
4374 - // The element in which the editor lives.
4375 - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
4376 -
4377 - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
4378 - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
4379 - if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
4380 -
4381 - if (place) {
4382 - if (place.appendChild) { place.appendChild(d.wrapper); }
4383 - else { place(d.wrapper); }
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";
4384 4351 }
4352 + }
4353 + gutters.style.display = i ? "" : "none";
4354 + updateGutterSpace(cm);
4355 +}
4385 4356
4386 - // Current rendered range (may be bigger than the view window).
4387 - d.viewFrom = d.viewTo = doc.first;
4388 - d.reportedViewFrom = d.reportedViewTo = doc.first;
4389 - // Information about the rendered lines.
4390 - d.view = [];
4391 - d.renderedView = null;
4392 - // Holds info about a single rendered line when it was rendered
4393 - // for measurement, while not in view.
4394 - d.externalMeasured = null;
4395 - // Empty space (in pixels) above the view
4396 - d.viewOffset = 0;
4397 - d.lastWrapHeight = d.lastWrapWidth = 0;
4398 - d.updateLineNumbers = null;
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 +}
4399 4368
4400 - d.nativeBarWidth = d.barHeight = d.barWidth = 0;
4401 - d.scrollbarsClipped = false;
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.
4402 4379
4403 - // Used to only resize the line number gutter when necessary (when
4404 - // the amount of lines crosses a boundary that makes its width change)
4405 - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
4406 - // Set to true when a non-horizontal-scrolling line widget is
4407 - // added. As an optimization, line widget aligning is skipped when
4408 - // this is false.
4409 - d.alignWidgets = false;
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; }
4410 4390
4411 - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
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 +}
4412 4404
4413 - // Tracks the maximum line length so that the horizontal scrollbar
4414 - // can be kept static when scrolling.
4415 - d.maxLine = null;
4416 - d.maxLineLength = 0;
4417 - d.maxLineChanged = false;
4405 +function onScrollWheel(cm, e) {
4406 + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
4418 4407
4419 - // Used for measuring wheel scrolling granularity
4420 - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
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 }
4421 4413
4422 - // True when shift is held down.
4423 - d.shift = false;
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 + }
4424 4428
4425 - // Used to track whether anything happened since the context menu
4426 - // was opened.
4427 - d.selForContextMenu = null;
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 + }
4428 4448
4429 - d.activeTouch = null;
4430 -
4431 - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
4432 - renderGutters(d);
4433 -
4434 - input.init(d);
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});
4435 4457 }
4436 4458
4437 - // Since the delta values reported on mouse wheel events are
4438 - // unstandardized between browsers and even browser versions, and
4439 - // generally horribly unpredictable, this code starts by measuring
4440 - // the scroll effect that the first few mouse wheel events have,
4441 - // and, from that, detects the way it can convert deltas to pixel
4442 - // offsets afterwards.
4443 - //
4444 - // The reason we want to know the amount a wheel event will scroll
4445 - // is that it gives us a chance to update the display before the
4446 - // actual scrolling happens, reducing flickering.
4447 -
4448 - var wheelSamples = 0, wheelPixelsPerUnit = null;
4449 - // Fill in a browser-detected starting value on browsers where we
4450 - // know one. These don't have to be accurate -- the result of them
4451 - // being wrong would just be a slight flicker on the first wheel
4452 - // scroll (if it is large enough).
4453 - if (ie) { wheelPixelsPerUnit = -.53; }
4454 - else if (gecko) { wheelPixelsPerUnit = 15; }
4455 - else if (chrome) { wheelPixelsPerUnit = -.7; }
4456 - else if (safari) { wheelPixelsPerUnit = -1/3; }
4457 -
4458 - function wheelEventDelta(e) {
4459 - var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4460 - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
4461 - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
4462 - else if (dy == null) { dy = e.wheelDelta; }
4463 - return {x: dx, y: dy}
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 + }
4464 4477 }
4465 - function wheelEventPixels(e) {
4466 - var delta = wheelEventDelta(e);
4467 - delta.x *= wheelPixelsPerUnit;
4468 - delta.y *= wheelPixelsPerUnit;
4469 - return delta
4470 - }
4478 +}
4471 4479
4472 - function onScrollWheel(cm, e) {
4473 - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
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 +};
4474 4489
4475 - var display = cm.display, scroll = display.scroller;
4476 - // Quit if there's nothing to scroll here
4477 - var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4478 - var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4479 - if (!(dx && canScrollX || dy && canScrollY)) { return }
4490 +Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
4480 4491
4481 - // Webkit browsers on OS X abort momentum scrolls when the target
4482 - // of the scroll event is removed from the scrollable element.
4483 - // This hack (see related code in patchDisplay) makes sure the
4484 - // element is kept around.
4485 - if (dy && mac && webkit) {
4486 - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4487 - for (var i = 0; i < view.length; i++) {
4488 - if (view[i].node == cur) {
4489 - cm.display.currentWheelTarget = cur;
4490 - break outer
4491 - }
4492 - }
4493 - }
4494 - }
4492 +Selection.prototype.equals = function (other) {
4493 + var this$1 = this;
4495 4494
4496 - // On some browsers, horizontal scrolling will cause redraws to
4497 - // happen before the gutter has been realigned, causing it to
4498 - // wriggle around in a most unseemly way. When we have an
4499 - // estimated pixels/delta value, we just handle horizontal
4500 - // scrolling entirely here. It'll be slightly off from native, but
4501 - // better than glitching out.
4502 - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4503 - if (dy && canScrollY)
4504 - { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
4505 - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
4506 - // Only prevent default scrolling if vertical scrolling is
4507 - // actually possible. Otherwise, it causes vertical scroll
4508 - // jitter on OSX trackpads when deltaX is small and deltaY
4509 - // is large (issue #3579)
4510 - if (!dy || (dy && canScrollY))
4511 - { e_preventDefault(e); }
4512 - display.wheelStartX = null; // Abort measurement, if in progress
4513 - return
4514 - }
4515 -
4516 - // 'Project' the visible viewport to cover the area that is being
4517 - // scrolled into view (if we know enough to estimate it).
4518 - if (dy && wheelPixelsPerUnit != null) {
4519 - var pixels = dy * wheelPixelsPerUnit;
4520 - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4521 - if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
4522 - else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
4523 - updateDisplaySimple(cm, {top: top, bottom: bot});
4524 - }
4525 -
4526 - if (wheelSamples < 20) {
4527 - if (display.wheelStartX == null) {
4528 - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4529 - display.wheelDX = dx; display.wheelDY = dy;
4530 - setTimeout(function () {
4531 - if (display.wheelStartX == null) { return }
4532 - var movedX = scroll.scrollLeft - display.wheelStartX;
4533 - var movedY = scroll.scrollTop - display.wheelStartY;
4534 - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4535 - (movedX && display.wheelDX && movedX / display.wheelDX);
4536 - display.wheelStartX = display.wheelStartY = null;
4537 - if (!sample) { return }
4538 - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4539 - ++wheelSamples;
4540 - }, 200);
4541 - } else {
4542 - display.wheelDX += dx; display.wheelDY += dy;
4543 - }
4544 - }
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 }
4545 4500 }
4501 + return true
4502 +};
4546 4503
4547 - // Selection objects are immutable. A new one is created every time
4548 - // the selection changes. A selection is one or more non-overlapping
4549 - // (and non-touching) ranges, sorted, and an integer that indicates
4550 - // which one is the primary selection (the one that's scrolled into
4551 - // view, that getCursor returns, etc).
4552 - var Selection = function(ranges, primIndex) {
4553 - this.ranges = ranges;
4554 - this.primIndex = primIndex;
4555 - };
4504 +Selection.prototype.deepCopy = function () {
4505 + var this$1 = this;
4556 4506
4557 - Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
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 +};
4558 4512
4559 - Selection.prototype.equals = function (other) {
4560 - if (other == this) { return true }
4561 - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
4562 - for (var i = 0; i < this.ranges.length; i++) {
4563 - var here = this.ranges[i], there = other.ranges[i];
4564 - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
4565 - }
4566 - return true
4567 - };
4513 +Selection.prototype.somethingSelected = function () {
4514 + var this$1 = this;
4568 4515
4569 - Selection.prototype.deepCopy = function () {
4570 - var out = [];
4571 - for (var i = 0; i < this.ranges.length; i++)
4572 - { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
4573 - return new Selection(out, this.primIndex)
4574 - };
4516 + for (var i = 0; i < this.ranges.length; i++)
4517 + { if (!this$1.ranges[i].empty()) { return true } }
4518 + return false
4519 +};
4575 4520
4576 - Selection.prototype.somethingSelected = function () {
4577 - for (var i = 0; i < this.ranges.length; i++)
4578 - { if (!this.ranges[i].empty()) { return true } }
4579 - return false
4580 - };
4521 +Selection.prototype.contains = function (pos, end) {
4522 + var this$1 = this;
4581 4523
4582 - Selection.prototype.contains = function (pos, end) {
4583 - if (!end) { end = pos; }
4584 - for (var i = 0; i < this.ranges.length; i++) {
4585 - var range = this.ranges[i];
4586 - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
4587 - { return i }
4588 - }
4589 - return -1
4590 - };
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 +};
4591 4532
4592 - var Range = function(anchor, head) {
4593 - this.anchor = anchor; this.head = head;
4594 - };
4533 +var Range = function(anchor, head) {
4534 + this.anchor = anchor; this.head = head;
4535 +};
4595 4536
4596 - Range.prototype.from = function () { return minPos(this.anchor, this.head) };
4597 - Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
4598 - Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
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 };
4599 4540
4600 - // Take an unsorted, potentially overlapping set of ranges, and
4601 - // build a selection out of it. 'Consumes' ranges array (modifying
4602 - // it).
4603 - function normalizeSelection(cm, ranges, primIndex) {
4604 - var mayTouch = cm && cm.options.selectionsMayTouch;
4605 - var prim = ranges[primIndex];
4606 - ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
4607 - primIndex = indexOf(ranges, prim);
4608 - for (var i = 1; i < ranges.length; i++) {
4609 - var cur = ranges[i], prev = ranges[i - 1];
4610 - var diff = cmp(prev.to(), cur.from());
4611 - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
4612 - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
4613 - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
4614 - if (i <= primIndex) { --primIndex; }
4615 - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
4616 - }
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));
4617 4555 }
4618 - return new Selection(ranges, primIndex)
4619 4556 }
4557 + return new Selection(ranges, primIndex)
4558 +}
4620 4559
4621 - function simpleSelection(anchor, head) {
4622 - return new Selection([new Range(anchor, head || anchor)], 0)
4623 - }
4560 +function simpleSelection(anchor, head) {
4561 + return new Selection([new Range(anchor, head || anchor)], 0)
4562 +}
4624 4563
4625 - // Compute the position of the end of a change (its 'to' property
4626 - // refers to the pre-change end).
4627 - function changeEnd(change) {
4628 - if (!change.text) { return change.to }
4629 - return Pos(change.from.line + change.text.length - 1,
4630 - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
4631 - }
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 +}
4632 4571
4633 - // Adjust a position to refer to the post-change position of the
4634 - // same text, or the end of the change if the change covers it.
4635 - function adjustForChange(pos, change) {
4636 - if (cmp(pos, change.from) < 0) { return pos }
4637 - if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
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) }
4638 4577
4639 - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4640 - if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
4641 - return Pos(line, ch)
4642 - }
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 +}
4643 4582
4644 - function computeSelAfterChange(doc, change) {
4645 - var out = [];
4646 - for (var i = 0; i < doc.sel.ranges.length; i++) {
4647 - var range = doc.sel.ranges[i];
4648 - out.push(new Range(adjustForChange(range.anchor, change),
4649 - adjustForChange(range.head, change)));
4650 - }
4651 - return normalizeSelection(doc.cm, out, doc.sel.primIndex)
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)));
4652 4589 }
4590 + return normalizeSelection(out, doc.sel.primIndex)
4591 +}
4653 4592
4654 - function offsetPos(pos, old, nw) {
4655 - if (pos.line == old.line)
4656 - { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
4657 - else
4658 - { return Pos(nw.line + (pos.line - old.line), pos.ch) }
4659 - }
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 +}
4660 4599
4661 - // Used by replaceSelections to allow moving the selection to the
4662 - // start or around the replaced test. Hint may be "start" or "around".
4663 - function computeReplacedSel(doc, changes, hint) {
4664 - var out = [];
4665 - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4666 - for (var i = 0; i < changes.length; i++) {
4667 - var change = changes[i];
4668 - var from = offsetPos(change.from, oldPrev, newPrev);
4669 - var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4670 - oldPrev = change.to;
4671 - newPrev = to;
4672 - if (hint == "around") {
4673 - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4674 - out[i] = new Range(inv ? to : from, inv ? from : to);
4675 - } else {
4676 - out[i] = new Range(from, from);
4677 - }
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);
4678 4616 }
4679 - return new Selection(out, doc.sel.primIndex)
4680 4617 }
4618 + return new Selection(out, doc.sel.primIndex)
4619 +}
4681 4620
4682 - // Used to get the editor into a consistent state again when options change.
4621 +// Used to get the editor into a consistent state again when options change.
4683 4622
4684 - function loadMode(cm) {
4685 - cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4686 - resetModeState(cm);
4687 - }
4623 +function loadMode(cm) {
4624 + cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
4625 + resetModeState(cm);
4626 +}
4688 4627
4689 - function resetModeState(cm) {
4690 - cm.doc.iter(function (line) {
4691 - if (line.stateAfter) { line.stateAfter = null; }
4692 - if (line.styles) { line.styles = null; }
4693 - });
4694 - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
4695 - startWorker(cm, 100);
4696 - cm.state.modeGen++;
4697 - if (cm.curOp) { regChange(cm); }
4698 - }
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 +}
4699 4638
4700 - // DOCUMENT DATA STRUCTURE
4639 +// DOCUMENT DATA STRUCTURE
4701 4640
4702 - // By default, updates that start and end at the beginning of a line
4703 - // are treated specially, in order to make the association of line
4704 - // widgets and marker elements with the text behave more intuitive.
4705 - function isWholeLineUpdate(doc, change) {
4706 - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
4707 - (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
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);
4708 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 + }
4709 4662
4710 - // Perform a change on the document data structure.
4711 - function updateDoc(doc, change, markedSpans, estimateHeight) {
4712 - function spansFor(n) {return markedSpans ? markedSpans[n] : null}
4713 - function update(line, text, spans) {
4714 - updateLine(line, text, spans, estimateHeight);
4715 - signalLater(line, "change", line, change);
4716 - }
4717 - function linesFor(start, end) {
4718 - var result = [];
4719 - for (var i = start; i < end; ++i)
4720 - { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
4721 - return result
4722 - }
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;
4723 4666
4724 - var from = change.from, to = change.to, text = change.text;
4725 - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4726 - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4727 -
4728 - // Adjust the line structure
4729 - if (change.full) {
4730 - doc.insert(0, linesFor(0, text.length));
4731 - doc.remove(text.length, doc.size - text.length);
4732 - } else if (isWholeLineUpdate(doc, change)) {
4733 - // This is a whole-line replace. Treated specially to make
4734 - // sure line objects move the way they are supposed to.
4735 - var added = linesFor(0, text.length - 1);
4736 - update(lastLine, lastLine.text, lastSpans);
4737 - if (nlines) { doc.remove(from.line, nlines); }
4738 - if (added.length) { doc.insert(from.line, added); }
4739 - } else if (firstLine == lastLine) {
4740 - if (text.length == 1) {
4741 - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4742 - } else {
4743 - var added$1 = linesFor(1, text.length - 1);
4744 - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
4745 - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4746 - doc.insert(from.line + 1, added$1);
4747 - }
4748 - } else if (text.length == 1) {
4749 - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4750 - doc.remove(from.line + 1, nlines);
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);
4751 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));
4752 4684 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4753 - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4754 - var added$2 = linesFor(1, text.length - 1);
4755 - if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
4756 - doc.insert(from.line + 1, added$2);
4685 + doc.insert(from.line + 1, added$1);
4757 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 + }
4758 4697
4759 - signalLater(doc, "change", doc, change);
4760 - }
4698 + signalLater(doc, "change", doc, change);
4699 +}
4761 4700
4762 - // Call f for all linked documents.
4763 - function linkedDocs(doc, f, sharedHistOnly) {
4764 - function propagate(doc, skip, sharedHist) {
4765 - if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
4766 - var rel = doc.linked[i];
4767 - if (rel.doc == skip) { continue }
4768 - var shared = sharedHist && rel.sharedHist;
4769 - if (sharedHistOnly && !shared) { continue }
4770 - f(rel.doc, shared);
4771 - propagate(rel.doc, doc, shared);
4772 - } }
4773 - }
4774 - propagate(doc, null, true);
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 + } }
4775 4712 }
4713 + propagate(doc, null, true);
4714 +}
4776 4715
4777 - // Attach a document to an editor.
4778 - function attachDoc(cm, doc) {
4779 - if (doc.cm) { throw new Error("This document is already in use.") }
4780 - cm.doc = doc;
4781 - doc.cm = cm;
4782 - estimateLineHeights(cm);
4783 - loadMode(cm);
4784 - setDirectionClass(cm);
4785 - if (!cm.options.lineWrapping) { findMaxLine(cm); }
4786 - cm.options.mode = doc.modeOption;
4787 - regChange(cm);
4788 - }
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 +}
4789 4728
4790 - function setDirectionClass(cm) {
4729 +function setDirectionClass(cm) {
4791 4730 (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
4792 - }
4731 +}
4793 4732
4794 - function directionChanged(cm) {
4795 - runInOp(cm, function () {
4796 - setDirectionClass(cm);
4797 - regChange(cm);
4798 - });
4799 - }
4733 +function directionChanged(cm) {
4734 + runInOp(cm, function () {
4735 + setDirectionClass(cm);
4736 + regChange(cm);
4737 + });
4738 +}
4800 4739
4801 - function History(startGen) {
4802 - // Arrays of change events and selections. Doing something adds an
4803 - // event to done and clears undo. Undoing moves events from done
4804 - // to undone, redoing moves them in the other direction.
4805 - this.done = []; this.undone = [];
4806 - this.undoDepth = Infinity;
4807 - // Used to track when changes can be merged into a single undo
4808 - // event
4809 - this.lastModTime = this.lastSelTime = 0;
4810 - this.lastOp = this.lastSelOp = null;
4811 - this.lastOrigin = this.lastSelOrigin = null;
4812 - // Used by the isClean() method
4813 - this.generation = this.maxGeneration = startGen || 1;
4814 - }
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 +}
4815 4754
4816 - // Create a history change event from an updateDoc-style change
4817 - // object.
4818 - function historyChangeFromChange(doc, change) {
4819 - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
4820 - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
4821 - linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
4822 - return histChange
4823 - }
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 +}
4824 4763
4825 - // Pop all selection events off the end of a history array. Stop at
4826 - // a change event.
4827 - function clearSelectionEvents(array) {
4828 - while (array.length) {
4829 - var last = lst(array);
4830 - if (last.ranges) { array.pop(); }
4831 - else { break }
4832 - }
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 }
4833 4771 }
4772 +}
4834 4773
4835 - // Find the top change event in the history. Pop off selection
4836 - // events that are in the way.
4837 - function lastChangeEvent(hist, force) {
4838 - if (force) {
4839 - clearSelectionEvents(hist.done);
4840 - return lst(hist.done)
4841 - } else if (hist.done.length && !lst(hist.done).ranges) {
4842 - return lst(hist.done)
4843 - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
4844 - hist.done.pop();
4845 - return lst(hist.done)
4846 - }
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)
4847 4785 }
4786 +}
4848 4787
4849 - // Register a change in the history. Merges changes that are within
4850 - // a single operation, or are close together with an origin that
4851 - // allows merging (starting with "+") into a single event.
4852 - function addChangeToHistory(doc, change, selAfter, opId) {
4853 - var hist = doc.history;
4854 - hist.undone.length = 0;
4855 - var time = +new Date, cur;
4856 - var last;
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;
4857 4796
4858 - if ((hist.lastOp == opId ||
4859 - hist.lastOrigin == change.origin && change.origin &&
4860 - ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
4861 - change.origin.charAt(0) == "*")) &&
4862 - (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
4863 - // Merge this change into the last event
4864 - last = lst(cur.changes);
4865 - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
4866 - // Optimized case for simple insertion -- don't want to add
4867 - // new changesets for every character typed
4868 - last.to = changeEnd(change);
4869 - } else {
4870 - // Add new sub-event
4871 - cur.changes.push(historyChangeFromChange(doc, change));
4872 - }
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);
4873 4808 } else {
4874 - // Can not be merged, start a new event.
4875 - var before = lst(hist.done);
4876 - if (!before || !before.ranges)
4877 - { pushSelectionToHistory(doc.sel, hist.done); }
4878 - cur = {changes: [historyChangeFromChange(doc, change)],
4879 - generation: hist.generation};
4880 - hist.done.push(cur);
4881 - while (hist.done.length > hist.undoDepth) {
4882 - hist.done.shift();
4883 - if (!hist.done[0].ranges) { hist.done.shift(); }
4884 - }
4809 + // Add new sub-event
4810 + cur.changes.push(historyChangeFromChange(doc, change));
4885 4811 }
4886 - hist.done.push(selAfter);
4887 - hist.generation = ++hist.maxGeneration;
4888 - hist.lastModTime = hist.lastSelTime = time;
4889 - hist.lastOp = hist.lastSelOp = opId;
4890 - hist.lastOrigin = hist.lastSelOrigin = change.origin;
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;
4891 4830
4892 - if (!last) { signal(doc, "historyAdded"); }
4893 - }
4831 + if (!last) { signal(doc, "historyAdded"); }
4832 +}
4894 4833
4895 - function selectionEventCanBeMerged(doc, origin, prev, sel) {
4896 - var ch = origin.charAt(0);
4897 - return ch == "*" ||
4898 - ch == "+" &&
4899 - prev.ranges.length == sel.ranges.length &&
4900 - prev.somethingSelected() == sel.somethingSelected() &&
4901 - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
4902 - }
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 +}
4903 4842
4904 - // Called whenever the selection changes, sets the new selection as
4905 - // the pending selection in the history, and pushes the old pending
4906 - // selection into the 'done' array when it was significantly
4907 - // different (in number of selected ranges, emptiness, or time).
4908 - function addSelectionToHistory(doc, sel, opId, options) {
4909 - var hist = doc.history, origin = options && options.origin;
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;
4910 4849
4911 - // A new event is started when the previous origin does not match
4912 - // the current, or the origins don't allow matching. Origins
4913 - // starting with * are always merged, those starting with + are
4914 - // merged when similar and close together in time.
4915 - if (opId == hist.lastSelOp ||
4916 - (origin && hist.lastSelOrigin == origin &&
4917 - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
4918 - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
4919 - { hist.done[hist.done.length - 1] = sel; }
4920 - else
4921 - { pushSelectionToHistory(sel, hist.done); }
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); }
4922 4861
4923 - hist.lastSelTime = +new Date;
4924 - hist.lastSelOrigin = origin;
4925 - hist.lastSelOp = opId;
4926 - if (options && options.clearRedo !== false)
4927 - { clearSelectionEvents(hist.undone); }
4928 - }
4862 + hist.lastSelTime = +new Date;
4863 + hist.lastSelOrigin = origin;
4864 + hist.lastSelOp = opId;
4865 + if (options && options.clearRedo !== false)
4866 + { clearSelectionEvents(hist.undone); }
4867 +}
4929 4868
4930 - function pushSelectionToHistory(sel, dest) {
4931 - var top = lst(dest);
4932 - if (!(top && top.ranges && top.equals(sel)))
4933 - { dest.push(sel); }
4934 - }
4869 +function pushSelectionToHistory(sel, dest) {
4870 + var top = lst(dest);
4871 + if (!(top && top.ranges && top.equals(sel)))
4872 + { dest.push(sel); }
4873 +}
4935 4874
4936 - // Used to store marked span information in the history.
4937 - function attachLocalSpans(doc, change, from, to) {
4938 - var existing = change["spans_" + doc.id], n = 0;
4939 - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
4940 - if (line.markedSpans)
4941 - { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
4942 - ++n;
4943 - });
4944 - }
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 +}
4945 4884
4946 - // When un/re-doing restores text containing marked spans, those
4947 - // that have been explicitly cleared should not be restored.
4948 - function removeClearedSpans(spans) {
4949 - if (!spans) { return null }
4950 - var out;
4951 - for (var i = 0; i < spans.length; ++i) {
4952 - if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
4953 - else if (out) { out.push(spans[i]); }
4954 - }
4955 - return !out ? spans : out.length ? out : null
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]); }
4956 4893 }
4894 + return !out ? spans : out.length ? out : null
4895 +}
4957 4896
4958 - // Retrieve and filter the old marked spans stored in a change event.
4959 - function getOldSpans(doc, change) {
4960 - var found = change["spans_" + doc.id];
4961 - if (!found) { return null }
4962 - var nw = [];
4963 - for (var i = 0; i < change.text.length; ++i)
4964 - { nw.push(removeClearedSpans(found[i])); }
4965 - return nw
4966 - }
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 +}
4967 4906
4968 - // Used for un/re-doing changes from the history. Combines the
4969 - // result of computing the existing spans with the set of spans that
4970 - // existed in the history (so that deleting around a span and then
4971 - // undoing brings back the span).
4972 - function mergeOldSpans(doc, change) {
4973 - var old = getOldSpans(doc, change);
4974 - var stretched = stretchSpansOverChange(doc, change);
4975 - if (!old) { return stretched }
4976 - if (!stretched) { return old }
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 }
4977 4916
4978 - for (var i = 0; i < old.length; ++i) {
4979 - var oldCur = old[i], stretchCur = stretched[i];
4980 - if (oldCur && stretchCur) {
4981 - spans: for (var j = 0; j < stretchCur.length; ++j) {
4982 - var span = stretchCur[j];
4983 - for (var k = 0; k < oldCur.length; ++k)
4984 - { if (oldCur[k].marker == span.marker) { continue spans } }
4985 - oldCur.push(span);
4986 - }
4987 - } else if (stretchCur) {
4988 - old[i] = stretchCur;
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);
4989 4925 }
4926 + } else if (stretchCur) {
4927 + old[i] = stretchCur;
4990 4928 }
4991 - return old
4992 4929 }
4930 + return old
4931 +}
4993 4932
4994 - // Used both to provide a JSON-safe object in .getHistory, and, when
4995 - // detaching a document, to split the history in two
4996 - function copyHistoryArray(events, newGroup, instantiateSel) {
4997 - var copy = [];
4998 - for (var i = 0; i < events.length; ++i) {
4999 - var event = events[i];
5000 - if (event.ranges) {
5001 - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
5002 - continue
5003 - }
5004 - var changes = event.changes, newChanges = [];
5005 - copy.push({changes: newChanges});
5006 - for (var j = 0; j < changes.length; ++j) {
5007 - var change = changes[j], m = (void 0);
5008 - newChanges.push({from: change.from, to: change.to, text: change.text});
5009 - if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
5010 - if (indexOf(newGroup, Number(m[1])) > -1) {
5011 - lst(newChanges)[prop] = change[prop];
5012 - delete change[prop];
5013 - }
5014 - } } }
5015 - }
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
5016 4942 }
5017 - return copy
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 + }
5018 4955 }
4956 + return copy
4957 +}
5019 4958
5020 - // The 'scroll' parameter given to many of these indicated whether
5021 - // the new cursor position should be scrolled into view after
5022 - // modifying the selection.
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.
5023 4962
5024 - // If shift is held or the extend flag is set, extends a range to
5025 - // include a given position (and optionally a second position).
5026 - // Otherwise, simply returns the range between the given positions.
5027 - // Used for cursor motion and such.
5028 - function extendRange(range, head, other, extend) {
5029 - if (extend) {
5030 - var anchor = range.anchor;
5031 - if (other) {
5032 - var posBefore = cmp(head, anchor) < 0;
5033 - if (posBefore != (cmp(other, anchor) < 0)) {
5034 - anchor = head;
5035 - head = other;
5036 - } else if (posBefore != (cmp(head, other) < 0)) {
5037 - head = other;
5038 - }
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;
5039 4977 }
5040 - return new Range(anchor, head)
5041 - } else {
5042 - return new Range(other || head, head)
5043 4978 }
4979 + return new Range(anchor, head)
4980 + } else {
4981 + return new Range(other || head, head)
5044 4982 }
4983 +}
5045 4984
5046 - // Extend the primary selection range, discard the rest.
5047 - function extendSelection(doc, head, other, options, extend) {
5048 - if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
5049 - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
5050 - }
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 +}
5051 4990
5052 - // Extend all selections (pos is an array of selections with length
5053 - // equal the number of selections)
5054 - function extendSelections(doc, heads, options) {
5055 - var out = [];
5056 - var extend = doc.cm && (doc.cm.display.shift || doc.extend);
5057 - for (var i = 0; i < doc.sel.ranges.length; i++)
5058 - { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
5059 - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
5060 - setSelection(doc, newSel, options);
5061 - }
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 +}
5062 5001
5063 - // Updates a single range in the selection.
5064 - function replaceOneSelection(doc, i, range, options) {
5065 - var ranges = doc.sel.ranges.slice(0);
5066 - ranges[i] = range;
5067 - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
5068 - }
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 +}
5069 5008
5070 - // Reset the selection to a single range.
5071 - function setSimpleSelection(doc, anchor, head, options) {
5072 - setSelection(doc, simpleSelection(anchor, head), options);
5073 - }
5009 +// Reset the selection to a single range.
5010 +function setSimpleSelection(doc, anchor, head, options) {
5011 + setSelection(doc, simpleSelection(anchor, head), options);
5012 +}
5074 5013
5075 - // Give beforeSelectionChange handlers a change to influence a
5076 - // selection update.
5077 - function filterSelectionChange(doc, sel, options) {
5078 - var obj = {
5079 - ranges: sel.ranges,
5080 - update: function(ranges) {
5081 - this.ranges = [];
5082 - for (var i = 0; i < ranges.length; i++)
5083 - { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
5084 - clipPos(doc, ranges[i].head)); }
5085 - },
5086 - origin: options && options.origin
5087 - };
5088 - signal(doc, "beforeSelectionChange", doc, obj);
5089 - if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
5090 - if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
5091 - else { return sel }
5092 - }
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;
5093 5021
5094 - function setSelectionReplaceHistory(doc, sel, options) {
5095 - var done = doc.history.done, last = lst(done);
5096 - if (last && last.ranges) {
5097 - done[done.length - 1] = sel;
5098 - setSelectionNoUndo(doc, sel, options);
5099 - } else {
5100 - setSelection(doc, sel, options);
5101 - }
5102 - }
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 +}
5103 5034
5104 - // Set a new selection.
5105 - function setSelection(doc, sel, options) {
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;
5106 5039 setSelectionNoUndo(doc, sel, options);
5107 - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
5040 + } else {
5041 + setSelection(doc, sel, options);
5108 5042 }
5043 +}
5109 5044
5110 - function setSelectionNoUndo(doc, sel, options) {
5111 - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5112 - { sel = filterSelectionChange(doc, sel, options); }
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 +}
5113 5050
5114 - var bias = options && options.bias ||
5115 - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
5116 - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
5051 +function setSelectionNoUndo(doc, sel, options) {
5052 + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
5053 + { sel = filterSelectionChange(doc, sel, options); }
5117 5054
5118 - if (!(options && options.scroll === false) && doc.cm)
5119 - { ensureCursorVisible(doc.cm); }
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);
5120 5071 }
5072 + signalLater(doc, "cursorActivity", doc);
5073 +}
5121 5074
5122 - function setSelectionInner(doc, sel) {
5123 - if (sel.equals(doc.sel)) { return }
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 +}
5124 5080
5125 - doc.sel = sel;
5126 -
5127 - if (doc.cm) {
5128 - doc.cm.curOp.updateInput = 1;
5129 - doc.cm.curOp.selectionChanged = true;
5130 - signalCursorActivity(doc.cm);
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);
5131 5093 }
5132 - signalLater(doc, "cursorActivity", doc);
5133 5094 }
5095 + return out ? normalizeSelection(out, sel.primIndex) : sel
5096 +}
5134 5097
5135 - // Verify that the selection does not partially select any atomic
5136 - // marked ranges.
5137 - function reCheckSelection(doc) {
5138 - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
5139 - }
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 }
5140 5112
5141 - // Return a selection that does not partially select any atomic
5142 - // ranges.
5143 - function skipAtomicInSelection(doc, sel, bias, mayClear) {
5144 - var out;
5145 - for (var i = 0; i < sel.ranges.length; i++) {
5146 - var range = sel.ranges[i];
5147 - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
5148 - var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
5149 - var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
5150 - if (out || newAnchor != range.anchor || newHead != range.head) {
5151 - if (!out) { out = sel.ranges.slice(0, i); }
5152 - out[i] = new Range(newAnchor, newHead);
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) }
5153 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
5154 5125 }
5155 - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
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)
5156 5140 }
5141 + return found
5142 +}
5157 5143
5158 - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
5159 - var line = getLine(doc, pos.line);
5160 - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
5161 - var sp = line.markedSpans[i], m = sp.marker;
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 +}
5162 5155
5163 - // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
5164 - // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
5165 - // is with selectLeft/Right
5166 - var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
5167 - var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
5156 +function selectAll(cm) {
5157 + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
5158 +}
5168 5159
5169 - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
5170 - (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
5171 - if (mayClear) {
5172 - signal(m, "beforeCursorEnter");
5173 - if (m.explicitlyCleared) {
5174 - if (!line.markedSpans) { break }
5175 - else {--i; continue}
5176 - }
5177 - }
5178 - if (!m.atomic) { continue }
5160 +// UPDATING
5179 5161
5180 - if (oldPos) {
5181 - var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
5182 - if (dir < 0 ? preventCursorRight : preventCursorLeft)
5183 - { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
5184 - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
5185 - { return skipAtomicInner(doc, near, pos, dir, mayClear) }
5186 - }
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); }
5187 5180
5188 - var far = m.find(dir < 0 ? -1 : 1);
5189 - if (dir < 0 ? preventCursorLeft : preventCursorRight)
5190 - { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
5191 - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
5192 - }
5193 - } }
5194 - return pos
5195 - }
5181 + if (obj.canceled) { return null }
5182 + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
5183 +}
5196 5184
5197 - // Ensure a given position is not inside an atomic range.
5198 - function skipAtomic(doc, pos, oldPos, bias, mayClear) {
5199 - var dir = bias || 1;
5200 - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
5201 - (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
5202 - skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
5203 - (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
5204 - if (!found) {
5205 - doc.cantEdit = true;
5206 - return Pos(doc.first, 0)
5207 - }
5208 - return found
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 }
5209 5191 }
5210 5192
5211 - function movePos(doc, pos, dir, line) {
5212 - if (dir < 0 && pos.ch == 0) {
5213 - if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
5214 - else { return null }
5215 - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
5216 - if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
5217 - else { return null }
5218 - } else {
5219 - return new Pos(pos.line, pos.ch + dir)
5220 - }
5193 + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5194 + change = filterChange(doc, change, true);
5195 + if (!change) { return }
5221 5196 }
5222 5197
5223 - function selectAll(cm) {
5224 - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
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);
5225 5206 }
5207 +}
5226 5208
5227 - // UPDATING
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);
5228 5213
5229 - // Allow "beforeChange" event handlers to influence a change
5230 - function filterChange(doc, change, update) {
5231 - var obj = {
5232 - canceled: false,
5233 - from: change.from,
5234 - to: change.to,
5235 - text: change.text,
5236 - origin: change.origin,
5237 - cancel: function () { return obj.canceled = true; }
5238 - };
5239 - if (update) { obj.update = function (from, to, text, origin) {
5240 - if (from) { obj.from = clipPos(doc, from); }
5241 - if (to) { obj.to = clipPos(doc, to); }
5242 - if (text) { obj.text = text; }
5243 - if (origin !== undefined) { obj.origin = origin; }
5244 - }; }
5245 - signal(doc, "beforeChange", doc, obj);
5246 - if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
5214 + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
5215 + var rebased = [];
5247 5216
5248 - if (obj.canceled) {
5249 - if (doc.cm) { doc.cm.curOp.updateInput = 2; }
5250 - return null
5217 + linkedDocs(doc, function (doc, sharedHist) {
5218 + if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5219 + rebaseHist(doc.history, change);
5220 + rebased.push(doc.history);
5251 5221 }
5252 - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
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 }
5253 5240 }
5241 + if (i == source.length) { return }
5242 + hist.lastOrigin = hist.lastSelOrigin = null;
5254 5243
5255 - // Apply a change to a document, and add it to the document's
5256 - // history, and propagating it to all linked documents.
5257 - function makeChange(doc, change, ignoreReadOnly) {
5258 - if (doc.cm) {
5259 - if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
5260 - if (doc.cm.state.suppressEdits) { return }
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;
5261 5253 }
5254 + else { break }
5255 + }
5262 5256
5263 - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
5264 - change = filterChange(doc, change, true);
5265 - if (!change) { return }
5266 - }
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;
5267 5263
5268 - // Possibly split or suppress the update based on the presence
5269 - // of read-only spans in its range.
5270 - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
5271 - if (split) {
5272 - for (var i = split.length - 1; i >= 0; --i)
5273 - { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
5274 - } else {
5275 - makeChangeInner(doc, change);
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 {}
5276 5272 }
5277 - }
5278 5273
5279 - function makeChangeInner(doc, change) {
5280 - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
5281 - var selAfter = computeSelAfterChange(doc, change);
5282 - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
5274 + antiChanges.push(historyChangeFromChange(doc, change));
5283 5275
5284 - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
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)}); }
5285 5279 var rebased = [];
5286 5280
5281 + // Propagate to the linked documents
5287 5282 linkedDocs(doc, function (doc, sharedHist) {
5288 5283 if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5289 5284 rebaseHist(doc.history, change);
5290 5285 rebased.push(doc.history);
5291 5286 }
5292 - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
5287 + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5293 5288 });
5294 - }
5289 + };
5295 5290
5296 - // Revert a change stored in a document's history.
5297 - function makeChangeFromHistory(doc, type, allowSelectionOnly) {
5298 - var suppress = doc.cm && doc.cm.state.suppressEdits;
5299 - if (suppress && !allowSelectionOnly) { return }
5291 + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5292 + var returned = loop( i$1 );
5300 5293
5301 - var hist = doc.history, event, selAfter = doc.sel;
5302 - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
5294 + if ( returned ) return returned.v;
5295 + }
5296 +}
5303 5297
5304 - // Verify that there is a useable event (so that ctrl-z won't
5305 - // needlessly clear selection events)
5306 - var i = 0;
5307 - for (; i < source.length; i++) {
5308 - event = source[i];
5309 - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
5310 - { break }
5311 - }
5312 - if (i == source.length) { return }
5313 - hist.lastOrigin = hist.lastSelOrigin = null;
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 +}
5314 5313
5315 - for (;;) {
5316 - event = source.pop();
5317 - if (event.ranges) {
5318 - pushSelectionToHistory(event, dest);
5319 - if (allowSelectionOnly && !event.equals(doc.sel)) {
5320 - setSelection(doc, event, {clearRedo: false});
5321 - return
5322 - }
5323 - selAfter = event;
5324 - } else if (suppress) {
5325 - source.push(event);
5326 - return
5327 - } else { break }
5328 - }
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) }
5329 5319
5330 - // Build up a reverse change object to add to the opposite history
5331 - // stack (redo when undoing, and vice versa).
5332 - var antiChanges = [];
5333 - pushSelectionToHistory(selAfter, dest);
5334 - dest.push({changes: antiChanges, generation: hist.generation});
5335 - hist.generation = event.generation || ++hist.maxGeneration;
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 }
5336 5325
5337 - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
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 5338
5339 - var loop = function ( i ) {
5340 - var change = event.changes[i];
5341 - change.origin = type;
5342 - if (filter && !filterChange(doc, change, false)) {
5343 - source.length = 0;
5344 - return {}
5345 - }
5339 + change.removed = getBetween(doc, change.from, change.to);
5346 5340
5347 - antiChanges.push(historyChangeFromChange(doc, change));
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 +}
5348 5346
5349 - var after = i ? computeSelAfterChange(doc, change) : lst(source);
5350 - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
5351 - if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
5352 - var rebased = [];
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;
5353 5351
5354 - // Propagate to the linked documents
5355 - linkedDocs(doc, function (doc, sharedHist) {
5356 - if (!sharedHist && indexOf(rebased, doc.history) == -1) {
5357 - rebaseHist(doc.history, change);
5358 - rebased.push(doc.history);
5359 - }
5360 - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
5361 - });
5362 - };
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 + }
5363 5362
5364 - for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
5365 - var returned = loop( i$1 );
5363 + if (doc.sel.contains(change.from, change.to) > -1)
5364 + { signalCursorActivity(cm); }
5366 5365
5367 - if ( returned ) return returned.v;
5368 - }
5369 - }
5366 + updateDoc(doc, change, spans, estimateHeight(cm));
5370 5367
5371 - // Sub-views need their line numbers shifted when text is added
5372 - // above or below them in the parent document.
5373 - function shiftDoc(doc, distance) {
5374 - if (distance == 0) { return }
5375 - doc.first += distance;
5376 - doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
5377 - Pos(range.anchor.line + distance, range.anchor.ch),
5378 - Pos(range.head.line + distance, range.head.ch)
5379 - ); }), doc.sel.primIndex);
5380 - if (doc.cm) {
5381 - regChange(doc.cm, doc.first, doc.first - distance, distance);
5382 - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
5383 - { regLineChange(doc.cm, l, "gutter"); }
5384 - }
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; }
5385 5379 }
5386 5380
5387 - // More lower-level change function, handling only a single document
5388 - // (not linked ones).
5389 - function makeChangeSingleDoc(doc, change, selAfter, spans) {
5390 - if (doc.cm && !doc.cm.curOp)
5391 - { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
5381 + retreatFrontier(doc, from.line);
5382 + startWorker(cm, 400);
5392 5383
5393 - if (change.to.line < doc.first) {
5394 - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
5395 - return
5396 - }
5397 - if (change.from.line > doc.lastLine()) { return }
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); }
5398 5392
5399 - // Clip the change to the size of this doc
5400 - if (change.from.line < doc.first) {
5401 - var shift = change.text.length - 1 - (doc.first - change.from.line);
5402 - shiftDoc(doc, shift);
5403 - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
5404 - text: [lst(change.text)], origin: change.origin};
5405 - }
5406 - var last = doc.lastLine();
5407 - if (change.to.line > last) {
5408 - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
5409 - text: [change.text[0]], origin: change.origin};
5410 - }
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 +}
5411 5406
5412 - change.removed = getBetween(doc, change.from, change.to);
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 +}
5413 5414
5414 - if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
5415 - if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
5416 - else { updateDoc(doc, change, spans); }
5417 - setSelectionNoUndo(doc, selAfter, sel_dontScroll);
5415 +// Rebasing/resetting history to deal with externally-sourced changes
5418 5416
5419 - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
5420 - { doc.cantEdit = false; }
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;
5421 5423 }
5424 +}
5422 5425
5423 - // Handle the interaction of a change to a document with the editor
5424 - // that this document is part of.
5425 - function makeChangeSingleDocInEditor(cm, change, spans) {
5426 - var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
5427 -
5428 - var recomputeMaxLength = false, checkWidthStart = from.line;
5429 - if (!cm.options.lineWrapping) {
5430 - checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
5431 - doc.iter(checkWidthStart, to.line + 1, function (line) {
5432 - if (line == display.maxLine) {
5433 - recomputeMaxLength = true;
5434 - return true
5435 - }
5436 - });
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
5437 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 +}
5438 5460
5439 - if (doc.sel.contains(change.from, change.to) > -1)
5440 - { signalCursorActivity(cm); }
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 +}
5441 5466
5442 - updateDoc(doc, change, spans, estimateHeight(cm));
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 +}
5443 5478
5444 - if (!cm.options.lineWrapping) {
5445 - doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
5446 - var len = lineLength(line);
5447 - if (len > display.maxLineLength) {
5448 - display.maxLine = line;
5449 - display.maxLineLength = len;
5450 - display.maxLineChanged = true;
5451 - recomputeMaxLength = false;
5452 - }
5453 - });
5454 - if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
5455 - }
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
5456 5491
5457 - retreatFrontier(doc, from.line);
5458 - startWorker(cm, 400);
5492 +function LeafChunk(lines) {
5493 + var this$1 = this;
5459 5494
5460 - var lendiff = change.text.length - (to.line - from.line) - 1;
5461 - // Remember that these lines changed, for updating the display
5462 - if (change.full)
5463 - { regChange(cm); }
5464 - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
5465 - { regLineChange(cm, from.line, "text"); }
5466 - else
5467 - { regChange(cm, from.line, to.line + 1, lendiff); }
5468 -
5469 - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
5470 - if (changeHandler || changesHandler) {
5471 - var obj = {
5472 - from: from, to: to,
5473 - text: change.text,
5474 - removed: change.removed,
5475 - origin: change.origin
5476 - };
5477 - if (changeHandler) { signalLater(cm, "change", cm, obj); }
5478 - if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
5479 - }
5480 - cm.display.selForContextMenu = null;
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;
5481 5501 }
5502 + this.height = height;
5503 +}
5482 5504
5483 - function replaceRange(doc, code, from, to, origin) {
5484 - var assign;
5505 +LeafChunk.prototype = {
5506 + chunkSize: function() { return this.lines.length },
5485 5507
5486 - if (!to) { to = from; }
5487 - if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
5488 - if (typeof code == "string") { code = doc.splitLines(code); }
5489 - makeChange(doc, {from: from, to: to, text: code, origin: origin});
5490 - }
5508 + // Remove the n lines at offset 'at'.
5509 + removeInner: function(at, n) {
5510 + var this$1 = this;
5491 5511
5492 - // Rebasing/resetting history to deal with externally-sourced changes
5493 -
5494 - function rebaseHistSelSingle(pos, from, to, diff) {
5495 - if (to < pos.line) {
5496 - pos.line += diff;
5497 - } else if (from < pos.line) {
5498 - pos.line = from;
5499 - pos.ch = 0;
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");
5500 5517 }
5501 - }
5518 + this.lines.splice(at, n);
5519 + },
5502 5520
5503 - // Tries to rebase an array of history events given a change in the
5504 - // document. If the change touches the same lines as the event, the
5505 - // event, and everything 'behind' it, is discarded. If the change is
5506 - // before the event, the event's positions are updated. Uses a
5507 - // copy-on-write scheme for the positions, to avoid having to
5508 - // reallocate them all on every rebase, but also avoid problems with
5509 - // shared position objects being unsafely updated.
5510 - function rebaseHistArray(array, from, to, diff) {
5511 - for (var i = 0; i < array.length; ++i) {
5512 - var sub = array[i], ok = true;
5513 - if (sub.ranges) {
5514 - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
5515 - for (var j = 0; j < sub.ranges.length; j++) {
5516 - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
5517 - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
5518 - }
5519 - continue
5520 - }
5521 - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
5522 - var cur = sub.changes[j$1];
5523 - if (to < cur.from.line) {
5524 - cur.from = Pos(cur.from.line + diff, cur.from.ch);
5525 - cur.to = Pos(cur.to.line + diff, cur.to.ch);
5526 - } else if (from <= cur.to.line) {
5527 - ok = false;
5528 - break
5529 - }
5530 - }
5531 - if (!ok) {
5532 - array.splice(0, i + 1);
5533 - i = 0;
5534 - }
5535 - }
5536 - }
5521 + // Helper used to collapse a small branch into a single leaf.
5522 + collapse: function(lines) {
5523 + lines.push.apply(lines, this.lines);
5524 + },
5537 5525
5538 - function rebaseHist(hist, change) {
5539 - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5540 - rebaseHistArray(hist.done, from, to, diff);
5541 - rebaseHistArray(hist.undone, from, to, diff);
5542 - }
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;
5543 5530
5544 - // Utility for applying a change to a line by handle or number,
5545 - // returning the number and optionally registering the line as
5546 - // changed.
5547 - function changeLine(doc, handle, changeType, op) {
5548 - var no = handle, line = handle;
5549 - if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
5550 - else { no = lineNo(handle); }
5551 - if (no == null) { return null }
5552 - if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
5553 - return line
5554 - }
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 + },
5555 5535
5556 - // The document is represented as a BTree consisting of leaves, with
5557 - // chunk of lines in them, and branches, with up to ten leaves or
5558 - // other branch nodes below them. The top node is always a branch
5559 - // node, and is the document object itself (meaning it has
5560 - // additional methods and properties).
5561 - //
5562 - // All nodes have parent links. The tree is used both to go from
5563 - // line numbers to line objects, and to go from objects to numbers.
5564 - // It also indexes by height, and is used to convert between height
5565 - // and line object, and to find the total height of the document.
5566 - //
5567 - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
5536 + // Used to iterate over a part of the tree.
5537 + iterN: function(at, n, op) {
5538 + var this$1 = this;
5568 5539
5569 - function LeafChunk(lines) {
5570 - this.lines = lines;
5571 - this.parent = null;
5572 - var height = 0;
5573 - for (var i = 0; i < lines.length; ++i) {
5574 - lines[i].parent = this;
5575 - height += lines[i].height;
5576 - }
5577 - this.height = height;
5540 + for (var e = at + n; at < e; ++at)
5541 + { if (op(this$1.lines[at])) { return true } }
5578 5542 }
5543 +};
5579 5544
5580 - LeafChunk.prototype = {
5581 - chunkSize: function() { return this.lines.length },
5545 +function BranchChunk(children) {
5546 + var this$1 = this;
5582 5547
5583 - // Remove the n lines at offset 'at'.
5584 - removeInner: function(at, n) {
5585 - for (var i = at, e = at + n; i < e; ++i) {
5586 - var line = this.lines[i];
5587 - this.height -= line.height;
5588 - cleanUpLine(line);
5589 - signalLater(line, "delete");
5590 - }
5591 - this.lines.splice(at, n);
5592 - },
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 +}
5593 5559
5594 - // Helper used to collapse a small branch into a single leaf.
5595 - collapse: function(lines) {
5596 - lines.push.apply(lines, this.lines);
5597 - },
5560 +BranchChunk.prototype = {
5561 + chunkSize: function() { return this.size },
5598 5562
5599 - // Insert the given array of lines at offset 'at', count them as
5600 - // having the given height.
5601 - insertInner: function(at, lines, height) {
5602 - this.height += height;
5603 - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
5604 - for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
5605 - },
5563 + removeInner: function(at, n) {
5564 + var this$1 = this;
5606 5565
5607 - // Used to iterate over a part of the tree.
5608 - iterN: function(at, n, op) {
5609 - for (var e = at + n; at < e; ++at)
5610 - { if (op(this.lines[at])) { return true } }
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; }
5611 5577 }
5612 - };
5613 -
5614 - function BranchChunk(children) {
5615 - this.children = children;
5616 - var size = 0, height = 0;
5617 - for (var i = 0; i < children.length; ++i) {
5618 - var ch = children[i];
5619 - size += ch.chunkSize(); height += ch.height;
5620 - ch.parent = this;
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;
5621 5586 }
5622 - this.size = size;
5623 - this.height = height;
5624 - this.parent = null;
5625 - }
5587 + },
5626 5588
5627 - BranchChunk.prototype = {
5628 - chunkSize: function() { return this.size },
5589 + collapse: function(lines) {
5590 + var this$1 = this;
5629 5591
5630 - removeInner: function(at, n) {
5631 - this.size -= n;
5632 - for (var i = 0; i < this.children.length; ++i) {
5633 - var child = this.children[i], sz = child.chunkSize();
5634 - if (at < sz) {
5635 - var rm = Math.min(n, sz - at), oldHeight = child.height;
5636 - child.removeInner(at, rm);
5637 - this.height -= oldHeight - child.height;
5638 - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
5639 - if ((n -= rm) == 0) { break }
5640 - at = 0;
5641 - } else { at -= sz; }
5642 - }
5643 - // If the result is smaller than 25 lines, ensure that it is a
5644 - // single leaf node.
5645 - if (this.size - n < 25 &&
5646 - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
5647 - var lines = [];
5648 - this.collapse(lines);
5649 - this.children = [new LeafChunk(lines)];
5650 - this.children[0].parent = this;
5651 - }
5652 - },
5592 + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
5593 + },
5653 5594
5654 - collapse: function(lines) {
5655 - for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
5656 - },
5595 + insertInner: function(at, lines, height) {
5596 + var this$1 = this;
5657 5597
5658 - insertInner: function(at, lines, height) {
5659 - this.size += lines.length;
5660 - this.height += height;
5661 - for (var i = 0; i < this.children.length; ++i) {
5662 - var child = this.children[i], sz = child.chunkSize();
5663 - if (at <= sz) {
5664 - child.insertInner(at, lines, height);
5665 - if (child.lines && child.lines.length > 50) {
5666 - // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
5667 - // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
5668 - var remaining = child.lines.length % 25 + 25;
5669 - for (var pos = remaining; pos < child.lines.length;) {
5670 - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
5671 - child.height -= leaf.height;
5672 - this.children.splice(++i, 0, leaf);
5673 - leaf.parent = this;
5674 - }
5675 - child.lines = child.lines.slice(0, remaining);
5676 - this.maybeSpill();
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;
5677 5613 }
5678 - break
5614 + child.lines = child.lines.slice(0, remaining);
5615 + this$1.maybeSpill();
5679 5616 }
5680 - at -= sz;
5617 + break
5681 5618 }
5682 - },
5619 + at -= sz;
5620 + }
5621 + },
5683 5622
5684 - // When a node has grown, check whether it should be split.
5685 - maybeSpill: function() {
5686 - if (this.children.length <= 10) { return }
5687 - var me = this;
5688 - do {
5689 - var spilled = me.children.splice(me.children.length - 5, 5);
5690 - var sibling = new BranchChunk(spilled);
5691 - if (!me.parent) { // Become the parent node
5692 - var copy = new BranchChunk(me.children);
5693 - copy.parent = me;
5694 - me.children = [copy, sibling];
5695 - me = copy;
5696 - } else {
5697 - me.size -= sibling.size;
5698 - me.height -= sibling.height;
5699 - var myIndex = indexOf(me.parent.children, me);
5700 - me.parent.children.splice(myIndex + 1, 0, sibling);
5701 - }
5702 - sibling.parent = me.parent;
5703 - } while (me.children.length > 10)
5704 - me.parent.maybeSpill();
5705 - },
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 + },
5706 5645
5707 - iterN: function(at, n, op) {
5708 - for (var i = 0; i < this.children.length; ++i) {
5709 - var child = this.children[i], sz = child.chunkSize();
5710 - if (at < sz) {
5711 - var used = Math.min(n, sz - at);
5712 - if (child.iterN(at, used, op)) { return true }
5713 - if ((n -= used) == 0) { break }
5714 - at = 0;
5715 - } else { at -= sz; }
5716 - }
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; }
5717 5657 }
5718 - };
5658 + }
5659 +};
5719 5660
5720 - // Line widgets are block elements displayed above or below a line.
5661 +// Line widgets are block elements displayed above or below a line.
5721 5662
5722 - var LineWidget = function(doc, node, options) {
5723 - if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
5724 - { this[opt] = options[opt]; } } }
5725 - this.doc = doc;
5726 - this.node = node;
5727 - };
5663 +var LineWidget = function(doc, node, options) {
5664 + var this$1 = this;
5728 5665
5729 - LineWidget.prototype.clear = function () {
5730 - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5731 - if (no == null || !ws) { return }
5732 - for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
5733 - if (!ws.length) { line.widgets = null; }
5734 - var height = widgetHeight(this);
5735 - updateLineHeight(line, Math.max(0, line.height - height));
5736 - if (cm) {
5737 - runInOp(cm, function () {
5738 - adjustScrollWhenAboveVisible(cm, line, -height);
5739 - regLineChange(cm, no, "widget");
5740 - });
5741 - signalLater(cm, "lineWidgetCleared", cm, this, no);
5742 - }
5743 - };
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 +};
5744 5671
5745 - LineWidget.prototype.changed = function () {
5746 - var this$1 = this;
5672 +LineWidget.prototype.clear = function () {
5673 + var this$1 = this;
5747 5674
5748 - var oldH = this.height, cm = this.doc.cm, line = this.line;
5749 - this.height = null;
5750 - var diff = widgetHeight(this) - oldH;
5751 - if (!diff) { return }
5752 - if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
5753 - if (cm) {
5754 - runInOp(cm, function () {
5755 - cm.curOp.forceUpdate = true;
5756 - adjustScrollWhenAboveVisible(cm, line, diff);
5757 - signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
5758 - });
5759 - }
5760 - };
5761 - eventMixin(LineWidget);
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 +};
5762 5689
5763 - function adjustScrollWhenAboveVisible(cm, line, diff) {
5764 - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5765 - { addToScrollTop(cm, diff); }
5766 - }
5690 +LineWidget.prototype.changed = function () {
5691 + var this$1 = this;
5767 5692
5768 - function addLineWidget(doc, handle, node, options) {
5769 - var widget = new LineWidget(doc, node, options);
5770 - var cm = doc.cm;
5771 - if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
5772 - changeLine(doc, handle, "widget", function (line) {
5773 - var widgets = line.widgets || (line.widgets = []);
5774 - if (widget.insertAt == null) { widgets.push(widget); }
5775 - else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
5776 - widget.line = line;
5777 - if (cm && !lineIsHidden(doc, line)) {
5778 - var aboveVisible = heightAtLine(line) < doc.scrollTop;
5779 - updateLineHeight(line, line.height + widgetHeight(widget));
5780 - if (aboveVisible) { addToScrollTop(cm, widget.height); }
5781 - cm.curOp.forceUpdate = true;
5782 - }
5783 - return true
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));
5784 5703 });
5785 - if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
5786 - return widget
5787 5704 }
5705 +};
5706 +eventMixin(LineWidget);
5788 5707
5789 - // TEXTMARKERS
5708 +function adjustScrollWhenAboveVisible(cm, line, diff) {
5709 + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5710 + { addToScrollTop(cm, diff); }
5711 +}
5790 5712
5791 - // Created with markText and setBookmark methods. A TextMarker is a
5792 - // handle that can be used to clear or find a marked position in the
5793 - // document. Line objects hold arrays (markedSpans) containing
5794 - // {from, to, marker} object pointing to such marker objects, and
5795 - // indicating that such a marker is present on that line. Multiple
5796 - // lines may point to the same marker when it spans across lines.
5797 - // The spans will have null for their from/to properties when the
5798 - // marker continues beyond the start/end of the line. Markers have
5799 - // links back to the lines they currently touch.
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 +}
5800 5733
5801 - // Collapsed markers have unique ids, in order to be able to order
5802 - // them, which is needed for uniquely determining an outer marker
5803 - // when they overlap (they may nest, but not partially overlap).
5804 - var nextMarkerId = 0;
5734 +// TEXTMARKERS
5805 5735
5806 - var TextMarker = function(doc, type) {
5807 - this.lines = [];
5808 - this.type = type;
5809 - this.doc = doc;
5810 - this.id = ++nextMarkerId;
5811 - };
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.
5812 5745
5813 - // Clear the marker.
5814 - TextMarker.prototype.clear = function () {
5815 - if (this.explicitlyCleared) { return }
5816 - var cm = this.doc.cm, withOp = cm && !cm.curOp;
5817 - if (withOp) { startOperation(cm); }
5818 - if (hasHandler(this, "clear")) {
5819 - var found = this.find();
5820 - if (found) { signalLater(this, "clear", found.from, found.to); }
5821 - }
5822 - var min = null, max = null;
5823 - for (var i = 0; i < this.lines.length; ++i) {
5824 - var line = this.lines[i];
5825 - var span = getMarkedSpanFor(line.markedSpans, this);
5826 - if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
5827 - else if (cm) {
5828 - if (span.to != null) { max = lineNo(line); }
5829 - if (span.from != null) { min = lineNo(line); }
5830 - }
5831 - line.markedSpans = removeMarkedSpan(line.markedSpans, span);
5832 - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
5833 - { updateLineHeight(line, textHeight(cm.display)); }
5834 - }
5835 - if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
5836 - var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
5837 - if (len > cm.display.maxLineLength) {
5838 - cm.display.maxLine = visual;
5839 - cm.display.maxLineLength = len;
5840 - cm.display.maxLineChanged = true;
5841 - }
5842 - } }
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;
5843 5750
5844 - if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
5845 - this.lines.length = 0;
5846 - this.explicitlyCleared = true;
5847 - if (this.atomic && this.doc.cantEdit) {
5848 - this.doc.cantEdit = false;
5849 - if (cm) { reCheckSelection(cm.doc); }
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); }
5850 5777 }
5851 - if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
5852 - if (withOp) { endOperation(cm); }
5853 - if (this.parent) { this.parent.clear(); }
5854 - };
5855 -
5856 - // Find the position of the marker in the document. Returns a {from,
5857 - // to} object by default. Side can be passed to get a specific side
5858 - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5859 - // Pos objects returned contain a line object, rather than a line
5860 - // number (used to prevent looking up the same line twice).
5861 - TextMarker.prototype.find = function (side, lineObj) {
5862 - if (side == null && this.type == "bookmark") { side = 1; }
5863 - var from, to;
5864 - for (var i = 0; i < this.lines.length; ++i) {
5865 - var line = this.lines[i];
5866 - var span = getMarkedSpanFor(line.markedSpans, this);
5867 - if (span.from != null) {
5868 - from = Pos(lineObj ? line : lineNo(line), span.from);
5869 - if (side == -1) { return from }
5870 - }
5871 - if (span.to != null) {
5872 - to = Pos(lineObj ? line : lineNo(line), span.to);
5873 - if (side == 1) { return to }
5874 - }
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;
5875 5788 }
5876 - return from && {from: from, to: to}
5877 - };
5789 + } }
5878 5790
5879 - // Signals that the marker's widget changed, and surrounding layout
5880 - // should be recomputed.
5881 - TextMarker.prototype.changed = function () {
5882 - var this$1 = this;
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 +};
5883 5802
5884 - var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
5885 - if (!pos || !cm) { return }
5886 - runInOp(cm, function () {
5887 - var line = pos.line, lineN = lineNo(pos.line);
5888 - var view = findViewForLine(cm, lineN);
5889 - if (view) {
5890 - clearLineMeasurementCacheFor(view);
5891 - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
5892 - }
5893 - cm.curOp.updateMaxLine = true;
5894 - if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5895 - var oldHeight = widget.height;
5896 - widget.height = null;
5897 - var dHeight = widgetHeight(widget) - oldHeight;
5898 - if (dHeight)
5899 - { updateLineHeight(line, line.height + dHeight); }
5900 - }
5901 - signalLater(cm, "markerChanged", cm, this$1);
5902 - });
5903 - };
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;
5904 5810
5905 - TextMarker.prototype.attachLine = function (line) {
5906 - if (!this.lines.length && this.doc.cm) {
5907 - var op = this.doc.cm.curOp;
5908 - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5909 - { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
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 }
5910 5819 }
5911 - this.lines.push(line);
5912 - };
5913 -
5914 - TextMarker.prototype.detachLine = function (line) {
5915 - this.lines.splice(indexOf(this.lines, line), 1);
5916 - if (!this.lines.length && this.doc.cm) {
5917 - var op = this.doc.cm.curOp
5918 - ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5820 + if (span.to != null) {
5821 + to = Pos(lineObj ? line : lineNo(line), span.to);
5822 + if (side == 1) { return to }
5919 5823 }
5920 - };
5921 - eventMixin(TextMarker);
5824 + }
5825 + return from && {from: from, to: to}
5826 +};
5922 5827
5923 - // Create a marker, wire it up to the right lines, and
5924 - function markText(doc, from, to, options, type) {
5925 - // Shared markers (across linked documents) are handled separately
5926 - // (markTextShared will call out to this again, once per
5927 - // document).
5928 - if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
5929 - // Ensure we are in an operation.
5930 - if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
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;
5931 5832
5932 - var marker = new TextMarker(doc, type), diff = cmp(from, to);
5933 - if (options) { copyObj(options, marker, false); }
5934 - // Don't connect empty markers unless clearWhenEmpty is false
5935 - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
5936 - { return marker }
5937 - if (marker.replacedWith) {
5938 - // Showing up as a widget implies collapsed (widget replaces text)
5939 - marker.collapsed = true;
5940 - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
5941 - if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
5942 - if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
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;
5943 5841 }
5944 - if (marker.collapsed) {
5945 - if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
5946 - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
5947 - { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
5948 - seeCollapsedSpans();
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); }
5949 5849 }
5850 + signalLater(cm, "markerChanged", cm, this$1);
5851 + });
5852 +};
5950 5853
5951 - if (marker.addToHistory)
5952 - { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
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 +};
5953 5862
5954 - var curLine = from.line, cm = doc.cm, updateMaxLine;
5955 - doc.iter(curLine, to.line + 1, function (line) {
5956 - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
5957 - { updateMaxLine = true; }
5958 - if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
5959 - addMarkedSpan(line, new MarkedSpan(marker,
5960 - curLine == from.line ? from.ch : null,
5961 - curLine == to.line ? to.ch : null));
5962 - ++curLine;
5963 - });
5964 - // lineIsHidden depends on the presence of the spans, so needs a second pass
5965 - if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
5966 - if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
5967 - }); }
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);
5968 5870
5969 - if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
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) }
5970 5879
5971 - if (marker.readOnly) {
5972 - seeReadOnlySpans();
5973 - if (doc.history.done.length || doc.history.undone.length)
5974 - { doc.clearHistory(); }
5975 - }
5976 - if (marker.collapsed) {
5977 - marker.id = ++nextMarkerId;
5978 - marker.atomic = true;
5979 - }
5980 - if (cm) {
5981 - // Sync editor state
5982 - if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
5983 - if (marker.collapsed)
5984 - { regChange(cm, from.line, to.line + 1); }
5985 - else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
5986 - marker.attributes || marker.title)
5987 - { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
5988 - if (marker.atomic) { reCheckSelection(cm.doc); }
5989 - signalLater(cm, "markerAdded", cm, marker);
5990 - }
5991 - return marker
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; }
5992 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 + }
5993 5898
5994 - // SHARED TEXTMARKERS
5899 + if (marker.addToHistory)
5900 + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
5995 5901
5996 - // A shared marker spans multiple linked documents. It is
5997 - // implemented as a meta-marker-object controlling multiple normal
5998 - // markers.
5999 - var SharedTextMarker = function(markers, primary) {
6000 - this.markers = markers;
6001 - this.primary = primary;
6002 - for (var i = 0; i < markers.length; ++i)
6003 - { markers[i].parent = this; }
6004 - };
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 + }); }
6005 5916
6006 - SharedTextMarker.prototype.clear = function () {
6007 - if (this.explicitlyCleared) { return }
6008 - this.explicitlyCleared = true;
6009 - for (var i = 0; i < this.markers.length; ++i)
6010 - { this.markers[i].clear(); }
6011 - signalLater(this, "clear");
6012 - };
5917 + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
6013 5918
6014 - SharedTextMarker.prototype.find = function (side, lineObj) {
6015 - return this.primary.find(side, lineObj)
6016 - };
6017 - eventMixin(SharedTextMarker);
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 +}
6018 5940
6019 - function markTextShared(doc, from, to, options, type) {
6020 - options = copyObj(options);
6021 - options.shared = false;
6022 - var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6023 - var widget = options.widgetNode;
6024 - linkedDocs(doc, function (doc) {
6025 - if (widget) { options.widgetNode = widget.cloneNode(true); }
6026 - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6027 - for (var i = 0; i < doc.linked.length; ++i)
6028 - { if (doc.linked[i].isParent) { return } }
6029 - primary = lst(markers);
6030 - });
6031 - return new SharedTextMarker(markers, primary)
6032 - }
5941 +// SHARED TEXTMARKERS
6033 5942
6034 - function findSharedMarkers(doc) {
6035 - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
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 + }
6036 5998 }
5999 +}
6037 6000
6038 - function copySharedMarkers(doc, markers) {
6039 - for (var i = 0; i < markers.length; i++) {
6040 - var marker = markers[i], pos = marker.find();
6041 - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6042 - if (cmp(mFrom, mTo)) {
6043 - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6044 - marker.markers.push(subMark);
6045 - subMark.parent = marker;
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);
6046 6010 }
6047 6011 }
6048 - }
6012 + };
6049 6013
6050 - function detachSharedMarkers(markers) {
6051 - var loop = function ( i ) {
6052 - var marker = markers[i], linked = [marker.primary.doc];
6053 - linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
6054 - for (var j = 0; j < marker.markers.length; j++) {
6055 - var subMarker = marker.markers[j];
6056 - if (indexOf(linked, subMarker.doc) == -1) {
6057 - subMarker.parent = null;
6058 - marker.markers.splice(j--, 1);
6059 - }
6060 - }
6061 - };
6014 + for (var i = 0; i < markers.length; i++) loop( i );
6015 +}
6062 6016
6063 - for (var i = 0; i < markers.length; i++) loop( i );
6064 - }
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; }
6065 6021
6066 - var nextDocId = 0;
6067 - var Doc = function(text, mode, firstLine, lineSep, direction) {
6068 - if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
6069 - if (firstLine == null) { firstLine = 0; }
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;
6070 6036
6071 - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
6072 - this.first = firstLine;
6073 - this.scrollTop = this.scrollLeft = 0;
6074 - this.cantEdit = false;
6075 - this.cleanGeneration = 1;
6076 - this.modeFrontier = this.highlightFrontier = firstLine;
6077 - var start = Pos(firstLine, 0);
6078 - this.sel = simpleSelection(start);
6079 - this.history = new History(null);
6080 - this.id = ++nextDocId;
6081 - this.modeOption = mode;
6082 - this.lineSep = lineSep;
6083 - this.direction = (direction == "rtl") ? "rtl" : "ltr";
6084 - this.extend = false;
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 +};
6085 6041
6086 - if (typeof text == "string") { text = this.splitLines(text); }
6087 - updateDoc(this, {from: start, to: start, text: text});
6088 - setSelection(this, simpleSelection(start), sel_dontScroll);
6089 - };
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 + },
6090 6052
6091 - Doc.prototype = createObj(BranchChunk.prototype, {
6092 - constructor: Doc,
6093 - // Iterate over the document. Supports two forms -- with only one
6094 - // argument, it calls that for each line in the document. With
6095 - // three, it iterates over the range given by the first two (with
6096 - // the second being non-inclusive).
6097 - iter: function(from, to, op) {
6098 - if (op) { this.iterN(from - this.first, to - from, op); }
6099 - else { this.iterN(this.first, this.first + this.size, from); }
6100 - },
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); },
6101 6060
6102 - // Non-public interface for adding and removing lines.
6103 - insert: function(at, lines) {
6104 - var height = 0;
6105 - for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
6106 - this.insertInner(at - this.first, lines, height);
6107 - },
6108 - remove: function(at, n) { this.removeInner(at - this.first, n); },
6061 + // From here, the methods are part of the public interface. Most
6062 + // are also available from CodeMirror (editor) instances.
6109 6063
6110 - // From here, the methods are part of the public interface. Most
6111 - // are also available from CodeMirror (editor) instances.
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 + },
6112 6086
6113 - getValue: function(lineSep) {
6114 - var lines = getLines(this, this.first, this.first + this.size);
6115 - if (lineSep === false) { return lines }
6116 - return lines.join(lineSep || this.lineSeparator())
6117 - },
6118 - setValue: docMethodOp(function(code) {
6119 - var top = Pos(this.first, 0), last = this.first + this.size - 1;
6120 - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6121 - text: this.splitLines(code), origin: "setValue", full: true}, true);
6122 - if (this.cm) { scrollToCoords(this.cm, 0, 0); }
6123 - setSelection(this, simpleSelection(top), sel_dontScroll);
6124 - }),
6125 - replaceRange: function(code, from, to, origin) {
6126 - from = clipPos(this, from);
6127 - to = to ? clipPos(this, to) : from;
6128 - replaceRange(this, code, from, to, origin);
6129 - },
6130 - getRange: function(from, to, lineSep) {
6131 - var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6132 - if (lineSep === false) { return lines }
6133 - return lines.join(lineSep || this.lineSeparator())
6134 - },
6087 + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6135 6088
6136 - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
6089 + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6090 + getLineNumber: function(line) {return lineNo(line)},
6137 6091
6138 - getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
6139 - getLineNumber: function(line) {return lineNo(line)},
6092 + getLineHandleVisualStart: function(line) {
6093 + if (typeof line == "number") { line = getLine(this, line); }
6094 + return visualLine(line)
6095 + },
6140 6096
6141 - getLineHandleVisualStart: function(line) {
6142 - if (typeof line == "number") { line = getLine(this, line); }
6143 - return visualLine(line)
6144 - },
6097 + lineCount: function() {return this.size},
6098 + firstLine: function() {return this.first},
6099 + lastLine: function() {return this.first + this.size - 1},
6145 6100
6146 - lineCount: function() {return this.size},
6147 - firstLine: function() {return this.first},
6148 - lastLine: function() {return this.first + this.size - 1},
6101 + clipPos: function(pos) {return clipPos(this, pos)},
6149 6102
6150 - clipPos: function(pos) {return clipPos(this, pos)},
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()},
6151 6113
6152 - getCursor: function(start) {
6153 - var range = this.sel.primary(), pos;
6154 - if (start == null || start == "head") { pos = range.head; }
6155 - else if (start == "anchor") { pos = range.anchor; }
6156 - else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
6157 - else { pos = range.from(); }
6158 - return pos
6159 - },
6160 - listSelections: function() { return this.sel.ranges },
6161 - somethingSelected: function() {return this.sel.somethingSelected()},
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;
6162 6132
6163 - setCursor: docMethodOp(function(line, ch, options) {
6164 - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6165 - }),
6166 - setSelection: docMethodOp(function(anchor, head, options) {
6167 - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6168 - }),
6169 - extendSelection: docMethodOp(function(head, other, options) {
6170 - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6171 - }),
6172 - extendSelections: docMethodOp(function(heads, options) {
6173 - extendSelections(this, clipPosArray(this, heads), options);
6174 - }),
6175 - extendSelectionsBy: docMethodOp(function(f, options) {
6176 - var heads = map(this.sel.ranges, f);
6177 - extendSelections(this, clipPosArray(this, heads), options);
6178 - }),
6179 - setSelections: docMethodOp(function(ranges, primary, options) {
6180 - if (!ranges.length) { return }
6181 - var out = [];
6182 - for (var i = 0; i < ranges.length; i++)
6183 - { out[i] = new Range(clipPos(this, ranges[i].anchor),
6184 - clipPos(this, ranges[i].head)); }
6185 - if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
6186 - setSelection(this, normalizeSelection(this.cm, out, primary), options);
6187 - }),
6188 - addSelection: docMethodOp(function(anchor, head, options) {
6189 - var ranges = this.sel.ranges.slice(0);
6190 - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6191 - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
6192 - }),
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 + }),
6193 6146
6194 - getSelection: function(lineSep) {
6195 - var ranges = this.sel.ranges, lines;
6196 - for (var i = 0; i < ranges.length; i++) {
6197 - var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6198 - lines = lines ? lines.concat(sel) : sel;
6199 - }
6200 - if (lineSep === false) { return lines }
6201 - else { return lines.join(lineSep || this.lineSeparator()) }
6202 - },
6203 - getSelections: function(lineSep) {
6204 - var parts = [], ranges = this.sel.ranges;
6205 - for (var i = 0; i < ranges.length; i++) {
6206 - var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6207 - if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
6208 - parts[i] = sel;
6209 - }
6210 - return parts
6211 - },
6212 - replaceSelection: function(code, collapse, origin) {
6213 - var dup = [];
6214 - for (var i = 0; i < this.sel.ranges.length; i++)
6215 - { dup[i] = code; }
6216 - this.replaceSelections(dup, collapse, origin || "+input");
6217 - },
6218 - replaceSelections: docMethodOp(function(code, collapse, origin) {
6219 - var changes = [], sel = this.sel;
6220 - for (var i = 0; i < sel.ranges.length; i++) {
6221 - var range = sel.ranges[i];
6222 - changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
6223 - }
6224 - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6225 - for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
6226 - { makeChange(this, changes[i$1]); }
6227 - if (newSel) { setSelectionReplaceHistory(this, newSel); }
6228 - else if (this.cm) { ensureCursorVisible(this.cm); }
6229 - }),
6230 - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6231 - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6232 - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6233 - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6147 + getSelection: function(lineSep) {
6148 + var this$1 = this;
6234 6149
6235 - setExtending: function(val) {this.extend = val;},
6236 - getExtending: function() {return this.extend},
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;
6237 6160
6238 - historySize: function() {
6239 - var hist = this.history, done = 0, undone = 0;
6240 - for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
6241 - for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
6242 - return {undo: done, redo: undone}
6243 - },
6244 - clearHistory: function() {
6245 - var this$1 = this;
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;
6246 6177
6247 - this.history = new History(this.history.maxGeneration);
6248 - linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
6249 - },
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);}),
6250 6193
6251 - markClean: function() {
6252 - this.cleanGeneration = this.changeGeneration(true);
6253 - },
6254 - changeGeneration: function(forceSplit) {
6255 - if (forceSplit)
6256 - { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
6257 - return this.history.generation
6258 - },
6259 - isClean: function (gen) {
6260 - return this.history.generation == (gen || this.cleanGeneration)
6261 - },
6194 + setExtending: function(val) {this.extend = val;},
6195 + getExtending: function() {return this.extend},
6262 6196
6263 - getHistory: function() {
6264 - return {done: copyHistoryArray(this.history.done),
6265 - undone: copyHistoryArray(this.history.undone)}
6266 - },
6267 - setHistory: function(histData) {
6268 - var hist = this.history = new History(this.history.maxGeneration);
6269 - hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6270 - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6271 - },
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);},
6272 6204
6273 - setGutterMarker: docMethodOp(function(line, gutterID, value) {
6274 - return changeLine(this, line, "gutter", function (line) {
6275 - var markers = line.gutterMarkers || (line.gutterMarkers = {});
6276 - markers[gutterID] = value;
6277 - if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
6278 - return true
6279 - })
6280 - }),
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 + },
6281 6216
6282 - clearGutter: docMethodOp(function(gutterID) {
6283 - var this$1 = this;
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 + },
6284 6226
6285 - this.iter(function (line) {
6286 - if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
6287 - changeLine(this$1, line, "gutter", function () {
6288 - line.gutterMarkers[gutterID] = null;
6289 - if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
6290 - return true
6291 - });
6292 - }
6293 - });
6294 - }),
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 + }),
6295 6235
6296 - lineInfo: function(line) {
6297 - var n;
6298 - if (typeof line == "number") {
6299 - if (!isLine(this, line)) { return null }
6300 - n = line;
6301 - line = getLine(this, line);
6302 - if (!line) { return null }
6303 - } else {
6304 - n = lineNo(line);
6305 - if (n == null) { return null }
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 + });
6306 6246 }
6307 - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
6308 - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
6309 - widgets: line.widgets}
6310 - },
6247 + });
6248 + }),
6311 6249
6312 - addLineClass: docMethodOp(function(handle, where, cls) {
6313 - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6314 - var prop = where == "text" ? "textClass"
6315 - : where == "background" ? "bgClass"
6316 - : where == "gutter" ? "gutterClass" : "wrapClass";
6317 - if (!line[prop]) { line[prop] = cls; }
6318 - else if (classTest(cls).test(line[prop])) { return false }
6319 - else { line[prop] += " " + cls; }
6320 - return true
6321 - })
6322 - }),
6323 - removeLineClass: docMethodOp(function(handle, where, cls) {
6324 - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
6325 - var prop = where == "text" ? "textClass"
6326 - : where == "background" ? "bgClass"
6327 - : where == "gutter" ? "gutterClass" : "wrapClass";
6328 - var cur = line[prop];
6329 - if (!cur) { return false }
6330 - else if (cls == null) { line[prop] = null; }
6331 - else {
6332 - var found = cur.match(classTest(cls));
6333 - if (!found) { return false }
6334 - var end = found.index + found[0].length;
6335 - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
6336 - }
6337 - return true
6338 - })
6339 - }),
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 + },
6340 6265
6341 - addLineWidget: docMethodOp(function(handle, node, options) {
6342 - return addLineWidget(this, handle, node, options)
6343 - }),
6344 - removeLineWidget: function(widget) { widget.clear(); },
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 + }),
6345 6294
6346 - markText: function(from, to, options) {
6347 - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
6348 - },
6349 - setBookmark: function(pos, options) {
6350 - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6351 - insertLeft: options && options.insertLeft,
6352 - clearWhenEmpty: false, shared: options && options.shared,
6353 - handleMouseEvents: options && options.handleMouseEvents};
6354 - pos = clipPos(this, pos);
6355 - return markText(this, pos, pos, realOpts, "bookmark")
6356 - },
6357 - findMarksAt: function(pos) {
6358 - pos = clipPos(this, pos);
6359 - var markers = [], spans = getLine(this, pos.line).markedSpans;
6360 - if (spans) { for (var i = 0; i < spans.length; ++i) {
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++) {
6361 6328 var span = spans[i];
6362 - if ((span.from == null || span.from <= pos.ch) &&
6363 - (span.to == null || span.to >= pos.ch))
6364 - { markers.push(span.marker.parent || span.marker); }
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); }
6365 6334 } }
6366 - return markers
6367 - },
6368 - findMarks: function(from, to, filter) {
6369 - from = clipPos(this, from); to = clipPos(this, to);
6370 - var found = [], lineNo = from.line;
6371 - this.iter(from.line, to.line + 1, function (line) {
6372 - var spans = line.markedSpans;
6373 - if (spans) { for (var i = 0; i < spans.length; i++) {
6374 - var span = spans[i];
6375 - if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
6376 - span.from == null && lineNo != from.line ||
6377 - span.from != null && lineNo == to.line && span.from >= to.ch) &&
6378 - (!filter || filter(span.marker)))
6379 - { found.push(span.marker.parent || span.marker); }
6380 - } }
6381 - ++lineNo;
6382 - });
6383 - return found
6384 - },
6385 - getAllMarks: function() {
6386 - var markers = [];
6387 - this.iter(function (line) {
6388 - var sps = line.markedSpans;
6389 - if (sps) { for (var i = 0; i < sps.length; ++i)
6390 - { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
6391 - });
6392 - return markers
6393 - },
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 + },
6394 6348
6395 - posFromIndex: function(off) {
6396 - var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
6397 - this.iter(function (line) {
6398 - var sz = line.text.length + sepSize;
6399 - if (sz > off) { ch = off; return true }
6400 - off -= sz;
6401 - ++lineNo;
6402 - });
6403 - return clipPos(this, Pos(lineNo, ch))
6404 - },
6405 - indexFromPos: function (coords) {
6406 - coords = clipPos(this, coords);
6407 - var index = coords.ch;
6408 - if (coords.line < this.first || coords.ch < 0) { return 0 }
6409 - var sepSize = this.lineSeparator().length;
6410 - this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
6411 - index += line.text.length + sepSize;
6412 - });
6413 - return index
6414 - },
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 + },
6415 6369
6416 - copy: function(copyHistory) {
6417 - var doc = new Doc(getLines(this, this.first, this.first + this.size),
6418 - this.modeOption, this.first, this.lineSep, this.direction);
6419 - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6420 - doc.sel = this.sel;
6421 - doc.extend = false;
6422 - if (copyHistory) {
6423 - doc.history.undoDepth = this.history.undoDepth;
6424 - doc.setHistory(this.getHistory());
6425 - }
6426 - return doc
6427 - },
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 + },
6428 6382
6429 - linkedDoc: function(options) {
6430 - if (!options) { options = {}; }
6431 - var from = this.first, to = this.first + this.size;
6432 - if (options.from != null && options.from > from) { from = options.from; }
6433 - if (options.to != null && options.to < to) { to = options.to; }
6434 - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
6435 - if (options.sharedHist) { copy.history = this.history
6436 - ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6437 - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6438 - copySharedMarkers(copy, findSharedMarkers(this));
6439 - return copy
6440 - },
6441 - unlinkDoc: function(other) {
6442 - if (other instanceof CodeMirror) { other = other.doc; }
6443 - if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
6444 - var link = this.linked[i];
6445 - if (link.doc != other) { continue }
6446 - this.linked.splice(i, 1);
6447 - other.unlinkDoc(this);
6448 - detachSharedMarkers(findSharedMarkers(this));
6449 - break
6450 - } }
6451 - // If the histories were shared, split them again
6452 - if (other.history == this.history) {
6453 - var splitIds = [other.id];
6454 - linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
6455 - other.history = new History(null);
6456 - other.history.done = copyHistoryArray(this.history.done, splitIds);
6457 - other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6458 - }
6459 - },
6460 - iterLinkedDocs: function(f) {linkedDocs(this, f);},
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;
6461 6397
6462 - getMode: function() {return this.mode},
6463 - getEditor: function() {return this.cm},
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);},
6464 6417
6465 - splitLines: function(str) {
6466 - if (this.lineSep) { return str.split(this.lineSep) }
6467 - return splitLinesAuto(str)
6468 - },
6469 - lineSeparator: function() { return this.lineSep || "\n" },
6418 + getMode: function() {return this.mode},
6419 + getEditor: function() {return this.cm},
6470 6420
6471 - setDirection: docMethodOp(function (dir) {
6472 - if (dir != "rtl") { dir = "ltr"; }
6473 - if (dir == this.direction) { return }
6474 - this.direction = dir;
6475 - this.iter(function (line) { return line.order = null; });
6476 - if (this.cm) { directionChanged(this.cm); }
6477 - })
6478 - });
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" },
6479 6426
6480 - // Public alias.
6481 - Doc.prototype.eachLine = Doc.prototype.iter;
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 +});
6482 6435
6483 - // Kludge to work around strange IE behavior where it'll sometimes
6484 - // re-fire a series of drag-related events right after the drop (#1551)
6485 - var lastDrop = 0;
6436 +// Public alias.
6437 +Doc.prototype.eachLine = Doc.prototype.iter;
6486 6438
6487 - function onDrop(e) {
6488 - var cm = this;
6489 - clearDragCursor(cm);
6490 - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
6491 - { return }
6492 - e_preventDefault(e);
6493 - if (ie) { lastDrop = +new Date; }
6494 - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
6495 - if (!pos || cm.isReadOnly()) { return }
6496 - // Might be a file drop, in which case we simply extract the text
6497 - // and insert it.
6498 - if (files && files.length && window.FileReader && window.File) {
6499 - var n = files.length, text = Array(n), read = 0;
6500 - var markAsReadAndPasteIfAllFilesAreRead = function () {
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;
6501 6466 if (++read == n) {
6502 - operation(cm, function () {
6503 - pos = clipPos(cm.doc, pos);
6504 - var change = {from: pos, to: pos,
6505 - text: cm.doc.splitLines(
6506 - text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
6507 - origin: "paste"};
6508 - makeChange(cm.doc, change);
6509 - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
6510 - })();
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)));
6511 6473 }
6512 - };
6513 - var readTextFromFile = function (file, i) {
6514 - if (cm.options.allowDropFileTypes &&
6515 - indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
6516 - markAsReadAndPasteIfAllFilesAreRead();
6517 - return
6518 - }
6519 - var reader = new FileReader;
6520 - reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
6521 - reader.onload = function () {
6522 - var content = reader.result;
6523 - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
6524 - markAsReadAndPasteIfAllFilesAreRead();
6525 - return
6526 - }
6527 - text[i] = content;
6528 - markAsReadAndPasteIfAllFilesAreRead();
6529 - };
6530 - reader.readAsText(file);
6531 - };
6532 - for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
6533 - } else { // Normal drop
6534 - // Don't do a replace if the drop happened inside of the selected text.
6535 - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
6536 - cm.state.draggingText(e);
6537 - // Ensure the editor is re-focused
6538 - setTimeout(function () { return cm.display.input.focus(); }, 20);
6539 - return
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();
6540 6497 }
6541 - try {
6542 - var text$1 = e.dataTransfer.getData("Text");
6543 - if (text$1) {
6544 - var selected;
6545 - if (cm.state.draggingText && !cm.state.draggingText.copy)
6546 - { selected = cm.listSelections(); }
6547 - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
6548 - if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
6549 - { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
6550 - cm.replaceSelection(text$1, "around", "paste");
6551 - cm.display.input.focus();
6552 - }
6553 - }
6554 - catch(e$1){}
6555 6498 }
6499 + catch(e){}
6556 6500 }
6501 +}
6557 6502
6558 - function onDragStart(cm, e) {
6559 - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
6560 - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
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 }
6561 6506
6562 - e.dataTransfer.setData("Text", cm.getSelection());
6563 - e.dataTransfer.effectAllowed = "copyMove";
6507 + e.dataTransfer.setData("Text", cm.getSelection());
6508 + e.dataTransfer.effectAllowed = "copyMove";
6564 6509
6565 - // Use dummy image instead of default browsers image.
6566 - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
6567 - if (e.dataTransfer.setDragImage && !safari) {
6568 - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
6569 - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
6570 - if (presto) {
6571 - img.width = img.height = 1;
6572 - cm.display.wrapper.appendChild(img);
6573 - // Force a relayout, or Opera won't use our image for some obscure reason
6574 - img._top = img.offsetTop;
6575 - }
6576 - e.dataTransfer.setDragImage(img, 0, 0);
6577 - if (presto) { img.parentNode.removeChild(img); }
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;
6578 6520 }
6521 + e.dataTransfer.setDragImage(img, 0, 0);
6522 + if (presto) { img.parentNode.removeChild(img); }
6579 6523 }
6524 +}
6580 6525
6581 - function onDragOver(cm, e) {
6582 - var pos = posFromMouse(cm, e);
6583 - if (!pos) { return }
6584 - var frag = document.createDocumentFragment();
6585 - drawSelectionCursor(cm, pos, frag);
6586 - if (!cm.display.dragCursor) {
6587 - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
6588 - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
6589 - }
6590 - removeChildrenAndAdd(cm.display.dragCursor, frag);
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);
6591 6534 }
6535 + removeChildrenAndAdd(cm.display.dragCursor, frag);
6536 +}
6592 6537
6593 - function clearDragCursor(cm) {
6594 - if (cm.display.dragCursor) {
6595 - cm.display.lineSpace.removeChild(cm.display.dragCursor);
6596 - cm.display.dragCursor = null;
6597 - }
6538 +function clearDragCursor(cm) {
6539 + if (cm.display.dragCursor) {
6540 + cm.display.lineSpace.removeChild(cm.display.dragCursor);
6541 + cm.display.dragCursor = null;
6598 6542 }
6543 +}
6599 6544
6600 - // These must be handled carefully, because naively registering a
6601 - // handler for each editor will cause the editors to never be
6602 - // garbage collected.
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.
6603 6548
6604 - function forEachCodeMirror(f) {
6605 - if (!document.getElementsByClassName) { return }
6606 - var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
6607 - for (var i = 0; i < byClass.length; i++) {
6608 - var cm = byClass[i].CodeMirror;
6609 - if (cm) { editors.push(cm); }
6610 - }
6611 - if (editors.length) { editors[0].operation(function () {
6612 - for (var i = 0; i < editors.length; i++) { f(editors[i]); }
6613 - }); }
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); }
6614 6555 }
6556 +}
6615 6557
6616 - var globalsRegistered = false;
6617 - function ensureGlobalHandlers() {
6618 - if (globalsRegistered) { return }
6619 - registerGlobalHandlers();
6620 - globalsRegistered = true;
6621 - }
6622 - function registerGlobalHandlers() {
6623 - // When the window resizes, we need to refresh active editors.
6624 - var resizeTimer;
6625 - on(window, "resize", function () {
6626 - if (resizeTimer == null) { resizeTimer = setTimeout(function () {
6627 - resizeTimer = null;
6628 - forEachCodeMirror(onResize);
6629 - }, 100); }
6630 - });
6631 - // When the window loses focus, we want to show the editor as blurred
6632 - on(window, "blur", function () { return forEachCodeMirror(onBlur); });
6633 - }
6634 - // Called when the window resizes
6635 - function onResize(cm) {
6636 - var d = cm.display;
6637 - // Might be a text scaling operation, clear size caches.
6638 - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
6639 - d.scrollbarsClipped = false;
6640 - cm.setSize();
6641 - }
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 +}
6642 6586
6643 - var keyNames = {
6644 - 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
6645 - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
6646 - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
6647 - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
6648 - 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
6649 - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
6650 - 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
6651 - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
6652 - };
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 +};
6653 6597
6654 - // Number keys
6655 - for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
6656 - // Alphabetic keys
6657 - for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
6658 - // Function keys
6659 - for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
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; }
6660 6604
6661 - var keyMap = {};
6605 +var keyMap = {};
6662 6606
6663 - keyMap.basic = {
6664 - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
6665 - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
6666 - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
6667 - "Tab": "defaultTab", "Shift-Tab": "indentAuto",
6668 - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
6669 - "Esc": "singleSelection"
6670 - };
6671 - // Note that the save and find-related commands aren't defined by
6672 - // default. User code or addons can define them. Unknown commands
6673 - // are simply ignored.
6674 - keyMap.pcDefault = {
6675 - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
6676 - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
6677 - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
6678 - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
6679 - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
6680 - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
6681 - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
6682 - "fallthrough": "basic"
6683 - };
6684 - // Very basic readline/emacs-style bindings, which are standard on Mac.
6685 - keyMap.emacsy = {
6686 - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
6687 - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
6688 - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
6689 - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
6690 - "Ctrl-O": "openLine"
6691 - };
6692 - keyMap.macDefault = {
6693 - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
6694 - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
6695 - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
6696 - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
6697 - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
6698 - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
6699 - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
6700 - "fallthrough": ["basic", "emacsy"]
6701 - };
6702 - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
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;
6703 6647
6704 - // KEYMAP DISPATCH
6648 +// KEYMAP DISPATCH
6705 6649
6706 - function normalizeKeyName(name) {
6707 - var parts = name.split(/-(?!$)/);
6708 - name = parts[parts.length - 1];
6709 - var alt, ctrl, shift, cmd;
6710 - for (var i = 0; i < parts.length - 1; i++) {
6711 - var mod = parts[i];
6712 - if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
6713 - else if (/^a(lt)?$/i.test(mod)) { alt = true; }
6714 - else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
6715 - else if (/^s(hift)?$/i.test(mod)) { shift = true; }
6716 - else { throw new Error("Unrecognized modifier name: " + mod) }
6717 - }
6718 - if (alt) { name = "Alt-" + name; }
6719 - if (ctrl) { name = "Ctrl-" + name; }
6720 - if (cmd) { name = "Cmd-" + name; }
6721 - if (shift) { name = "Shift-" + name; }
6722 - return name
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) }
6723 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 +}
6724 6668
6725 - // This is a kludge to keep keymaps mostly working as raw objects
6726 - // (backwards compatibility) while at the same time support features
6727 - // like normalization and multi-stroke key bindings. It compiles a
6728 - // new normalized keymap, and then updates the old object to reflect
6729 - // this.
6730 - function normalizeKeyMap(keymap) {
6731 - var copy = {};
6732 - for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
6733 - var value = keymap[keyname];
6734 - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
6735 - if (value == "...") { delete keymap[keyname]; continue }
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 }
6736 6680
6737 - var keys = map(keyname.split(" "), normalizeKeyName);
6738 - for (var i = 0; i < keys.length; i++) {
6739 - var val = (void 0), name = (void 0);
6740 - if (i == keys.length - 1) {
6741 - name = keys.join(" ");
6742 - val = value;
6743 - } else {
6744 - name = keys.slice(0, i + 1).join(" ");
6745 - val = "...";
6746 - }
6747 - var prev = copy[name];
6748 - if (!prev) { copy[name] = val; }
6749 - else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
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 = "...";
6750 6690 }
6751 - delete keymap[keyname];
6752 - } }
6753 - for (var prop in copy) { keymap[prop] = copy[prop]; }
6754 - return keymap
6755 - }
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 +}
6756 6700
6757 - function lookupKey(key, map, handle, context) {
6758 - map = getKeyMap(map);
6759 - var found = map.call ? map.call(key, context) : map[key];
6760 - if (found === false) { return "nothing" }
6761 - if (found === "...") { return "multi" }
6762 - if (found != null && handle(found)) { return "handled" }
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" }
6763 6707
6764 - if (map.fallthrough) {
6765 - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
6766 - { return lookupKey(key, map.fallthrough, handle, context) }
6767 - for (var i = 0; i < map.fallthrough.length; i++) {
6768 - var result = lookupKey(key, map.fallthrough[i], handle, context);
6769 - if (result) { return result }
6770 - }
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 }
6771 6714 }
6772 6715 }
6716 +}
6773 6717
6774 - // Modifier key presses don't count as 'real' key presses for the
6775 - // purpose of keymap fallthrough.
6776 - function isModifierKey(value) {
6777 - var name = typeof value == "string" ? value : keyNames[value.keyCode];
6778 - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
6779 - }
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 +}
6780 6724
6781 - function addModifierNames(name, event, noShift) {
6782 - var base = name;
6783 - if (event.altKey && base != "Alt") { name = "Alt-" + name; }
6784 - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
6785 - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
6786 - if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
6787 - return name
6788 - }
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 +}
6789 6733
6790 - // Look up the name of a key as indicated by an event object.
6791 - function keyName(event, noShift) {
6792 - if (presto && event.keyCode == 34 && event["char"]) { return false }
6793 - var name = keyNames[event.keyCode];
6794 - if (name == null || event.altGraphKey) { return false }
6795 - // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
6796 - // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
6797 - if (event.keyCode == 3 && event.code) { name = event.code; }
6798 - return addModifierNames(name, event, noShift)
6799 - }
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 +}
6800 6741
6801 - function getKeyMap(val) {
6802 - return typeof val == "string" ? keyMap[val] : val
6803 - }
6742 +function getKeyMap(val) {
6743 + return typeof val == "string" ? keyMap[val] : val
6744 +}
6804 6745
6805 - // Helper for deleting text near the selection(s), used to implement
6806 - // backspace, delete, and similar functionality.
6807 - function deleteNearSelection(cm, compute) {
6808 - var ranges = cm.doc.sel.ranges, kill = [];
6809 - // Build up a set of ranges to kill first, merging overlapping
6810 - // ranges.
6811 - for (var i = 0; i < ranges.length; i++) {
6812 - var toKill = compute(ranges[i]);
6813 - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
6814 - var replaced = kill.pop();
6815 - if (cmp(replaced.from, toKill.from) < 0) {
6816 - toKill.from = replaced.from;
6817 - break
6818 - }
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
6819 6759 }
6820 - kill.push(toKill);
6821 6760 }
6822 - // Next, remove those actual ranges.
6823 - runInOp(cm, function () {
6824 - for (var i = kill.length - 1; i >= 0; i--)
6825 - { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
6826 - ensureCursorVisible(cm);
6827 - });
6761 + kill.push(toKill);
6828 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 +}
6829 6770
6830 - function moveCharLogically(line, ch, dir) {
6831 - var target = skipExtendingChars(line.text, ch + dir, dir);
6832 - return target < 0 || target > line.text.length ? null : target
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 + }
6833 6804 }
6805 + return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6806 +}
6834 6807
6835 - function moveLogically(line, start, dir) {
6836 - var ch = moveCharLogically(line, start.ch, dir);
6837 - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
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";
6838 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 + }
6839 6824
6840 - function endOfLine(visually, cm, lineObj, lineNo, dir) {
6841 - if (visually) {
6842 - if (cm.doc.direction == "rtl") { dir = -dir; }
6843 - var order = getOrder(lineObj, cm.doc.direction);
6844 - if (order) {
6845 - var part = dir < 0 ? lst(order) : order[0];
6846 - var moveInStorageOrder = (dir < 0) == (part.level == 1);
6847 - var sticky = moveInStorageOrder ? "after" : "before";
6848 - var ch;
6849 - // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
6850 - // it could be that the last bidi part is not on the last visual line,
6851 - // since visual lines contain content order-consecutive chunks.
6852 - // Thus, in rtl, we are looking for the first (content-order) character
6853 - // in the rtl chunk that is on the last line (that is, the same line
6854 - // as the last (content-order) character).
6855 - if (part.level > 0 || cm.doc.direction == "rtl") {
6856 - var prep = prepareMeasureForLine(cm, lineObj);
6857 - ch = dir < 0 ? lineObj.text.length - 1 : 0;
6858 - var targetTop = measureCharPrepared(cm, prep, ch).top;
6859 - ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
6860 - if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
6861 - } else { ch = dir < 0 ? part.to : part.from; }
6862 - return new Pos(lineNo, ch, sticky)
6863 - }
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)
6864 6841 }
6865 - return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
6866 6842 }
6867 6843
6868 - function moveVisually(cm, line, start, dir) {
6869 - var bidi = getOrder(line, cm.doc.direction);
6870 - if (!bidi) { return moveLogically(line, start, dir) }
6871 - if (start.ch >= line.text.length) {
6872 - start.ch = line.text.length;
6873 - start.sticky = "before";
6874 - } else if (start.ch <= 0) {
6875 - start.ch = 0;
6876 - start.sticky = "after";
6877 - }
6878 - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
6879 - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
6880 - // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
6881 - // nothing interesting happens.
6882 - return moveLogically(line, start, dir)
6883 - }
6844 + // Case 3: Could not move within this bidi part in this visual line, so leave
6845 + // the current bidi part
6884 6846
6885 - var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
6886 - var prep;
6887 - var getWrappedLineExtent = function (ch) {
6888 - if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
6889 - prep = prep || prepareMeasureForLine(cm, line);
6890 - return wrappedLineExtentChar(cm, line, prep, ch)
6891 - };
6892 - var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
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"); };
6893 6851
6894 - if (cm.doc.direction == "rtl" || part.level == 1) {
6895 - var moveInStorageOrder = (part.level == 1) == (dir < 0);
6896 - var ch = mv(start, moveInStorageOrder ? 1 : -1);
6897 - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
6898 - // Case 2: We move within an rtl part or in an rtl editor on the same visual line
6899 - var sticky = moveInStorageOrder ? "before" : "after";
6900 - return new Pos(start.line, ch, sticky)
6901 - }
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) }
6902 6859 }
6860 + };
6903 6861
6904 - // Case 3: Could not move within this bidi part in this visual line, so leave
6905 - // the current bidi part
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 }
6906 6865
6907 - var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
6908 - var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
6909 - ? new Pos(start.line, mv(ch, 1), "before")
6910 - : new Pos(start.line, ch, "after"); };
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 + }
6911 6872
6912 - for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
6913 - var part = bidi[partPos];
6914 - var moveInStorageOrder = (dir > 0) == (part.level != 1);
6915 - var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
6916 - if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
6917 - ch = moveInStorageOrder ? part.from : mv(part.to, -1);
6918 - if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
6919 - }
6920 - };
6873 + // Case 4: Nowhere to move
6874 + return null
6875 +}
6921 6876
6922 - // Case 3a: Look for other bidi parts on the same visual line
6923 - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
6924 - if (res) { return res }
6925 -
6926 - // Case 3b: Look for other bidi parts on the next visual line
6927 - var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
6928 - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
6929 - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
6930 - if (res) { return res }
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()}
6931 6891 }
6932 -
6933 - // Case 4: Nowhere to move
6934 - return null
6935 - }
6936 -
6937 - // Commands are parameter-less actions that can be performed on an
6938 - // editor, mostly used for keybindings.
6939 - var commands = {
6940 - selectAll: selectAll,
6941 - singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
6942 - killLine: function (cm) { return deleteNearSelection(cm, function (range) {
6943 - if (range.empty()) {
6944 - var len = getLine(cm.doc, range.head.line).text.length;
6945 - if (range.head.ch == len && range.head.line < cm.lastLine())
6946 - { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
6947 - else
6948 - { return {from: range.head, to: Pos(range.head.line, len)} }
6949 - } else {
6950 - return {from: range.from(), to: range.to()}
6951 - }
6952 - }); },
6953 - deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6954 - from: Pos(range.from().line, 0),
6955 - to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
6956 - }); }); },
6957 - delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
6958 - from: Pos(range.from().line, 0), to: range.from()
6959 - }); }); },
6960 - delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
6961 - var top = cm.charCoords(range.head, "div").top + 5;
6962 - var leftPos = cm.coordsChar({left: 0, top: top}, "div");
6963 - return {from: leftPos, to: range.from()}
6964 - }); },
6965 - delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
6966 - var top = cm.charCoords(range.head, "div").top + 5;
6967 - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
6968 - return {from: range.from(), to: rightPos }
6969 - }); },
6970 - undo: function (cm) { return cm.undo(); },
6971 - redo: function (cm) { return cm.redo(); },
6972 - undoSelection: function (cm) { return cm.undoSelection(); },
6973 - redoSelection: function (cm) { return cm.redoSelection(); },
6974 - goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
6975 - goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
6976 - goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
6977 - {origin: "+move", bias: 1}
6978 - ); },
6979 - goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
6980 - {origin: "+move", bias: 1}
6981 - ); },
6982 - goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
6983 - {origin: "+move", bias: -1}
6984 - ); },
6985 - goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
6986 - var top = cm.cursorCoords(range.head, "div").top + 5;
6987 - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
6988 - }, sel_move); },
6989 - goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
6990 - var top = cm.cursorCoords(range.head, "div").top + 5;
6991 - return cm.coordsChar({left: 0, top: top}, "div")
6992 - }, sel_move); },
6993 - goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
6994 - var top = cm.cursorCoords(range.head, "div").top + 5;
6995 - var pos = cm.coordsChar({left: 0, top: top}, "div");
6996 - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
6997 - return pos
6998 - }, sel_move); },
6999 - goLineUp: function (cm) { return cm.moveV(-1, "line"); },
7000 - goLineDown: function (cm) { return cm.moveV(1, "line"); },
7001 - goPageUp: function (cm) { return cm.moveV(-1, "page"); },
7002 - goPageDown: function (cm) { return cm.moveV(1, "page"); },
7003 - goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
7004 - goCharRight: function (cm) { return cm.moveH(1, "char"); },
7005 - goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
7006 - goColumnRight: function (cm) { return cm.moveH(1, "column"); },
7007 - goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
7008 - goGroupRight: function (cm) { return cm.moveH(1, "group"); },
7009 - goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
7010 - goWordRight: function (cm) { return cm.moveH(1, "word"); },
7011 - delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
7012 - delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
7013 - delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
7014 - delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
7015 - delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
7016 - delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
7017 - indentAuto: function (cm) { return cm.indentSelection("smart"); },
7018 - indentMore: function (cm) { return cm.indentSelection("add"); },
7019 - indentLess: function (cm) { return cm.indentSelection("subtract"); },
7020 - insertTab: function (cm) { return cm.replaceSelection("\t"); },
7021 - insertSoftTab: function (cm) {
7022 - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
7023 - for (var i = 0; i < ranges.length; i++) {
7024 - var pos = ranges[i].from();
7025 - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
7026 - spaces.push(spaceStr(tabSize - col % tabSize));
7027 - }
7028 - cm.replaceSelections(spaces);
7029 - },
7030 - defaultTab: function (cm) {
7031 - if (cm.somethingSelected()) { cm.indentSelection("add"); }
7032 - else { cm.execCommand("insertTab"); }
7033 - },
7034 - // Swap the two chars left and right of each selection's head.
7035 - // Move cursor behind the two swapped characters afterwards.
7036 - //
7037 - // Doesn't consider line feeds a character.
7038 - // Doesn't scan more than one line above to find a character.
7039 - // Doesn't do anything on an empty line.
7040 - // Doesn't do anything with non-empty selections.
7041 - transposeChars: function (cm) { return runInOp(cm, function () {
7042 - var ranges = cm.listSelections(), newSel = [];
7043 - for (var i = 0; i < ranges.length; i++) {
7044 - if (!ranges[i].empty()) { continue }
7045 - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
7046 - if (line) {
7047 - if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
7048 - if (cur.ch > 0) {
7049 - cur = new Pos(cur.line, cur.ch + 1);
7050 - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
7051 - Pos(cur.line, cur.ch - 2), cur, "+transpose");
7052 - } else if (cur.line > cm.doc.first) {
7053 - var prev = getLine(cm.doc, cur.line - 1).text;
7054 - if (prev) {
7055 - cur = new Pos(cur.line, 1);
7056 - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
7057 - prev.charAt(prev.length - 1),
7058 - Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
7059 - }
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");
7060 6999 }
7061 7000 }
7062 - newSel.push(new Range(cur, cur));
7063 7001 }
7064 - cm.setSelections(newSel);
7065 - }); },
7066 - newlineAndIndent: function (cm) { return runInOp(cm, function () {
7067 - var sels = cm.listSelections();
7068 - for (var i = sels.length - 1; i >= 0; i--)
7069 - { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
7070 - sels = cm.listSelections();
7071 - for (var i$1 = 0; i$1 < sels.length; i$1++)
7072 - { cm.indentLine(sels[i$1].from().line, null, true); }
7073 - ensureCursorVisible(cm);
7074 - }); },
7075 - openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
7076 - toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
7077 - };
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 +};
7078 7018
7079 7019
7080 - function lineStart(cm, lineN) {
7081 - var line = getLine(cm.doc, lineN);
7082 - var visual = visualLine(line);
7083 - if (visual != line) { lineN = lineNo(visual); }
7084 - return endOfLine(true, cm, visual, lineN, 1)
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)
7085 7040 }
7086 - function lineEnd(cm, lineN) {
7087 - var line = getLine(cm.doc, lineN);
7088 - var visual = visualLineEnd(line);
7089 - if (visual != line) { lineN = lineNo(visual); }
7090 - return endOfLine(true, cm, line, lineN, -1)
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 }
7091 7049 }
7092 - function lineStartSmart(cm, pos) {
7093 - var start = lineStart(cm, pos.line);
7094 - var line = getLine(cm.doc, start.line);
7095 - var order = getOrder(line, cm.doc.direction);
7096 - if (!order || order[0].level == 0) {
7097 - var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
7098 - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
7099 - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
7100 - }
7101 - return start
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;
7102 7061 }
7062 + return done
7063 +}
7103 7064
7104 - // Run a handler that was bound to a key.
7105 - function doHandleBinding(cm, bound, dropShift) {
7106 - if (typeof bound == "string") {
7107 - bound = commands[bound];
7108 - if (!bound) { return false }
7109 - }
7110 - // Ensure previous input has been read, so that the handler sees a
7111 - // consistent view of the document
7112 - cm.display.input.ensurePolled();
7113 - var prevShift = cm.display.shift, done = false;
7114 - try {
7115 - if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7116 - if (dropShift) { cm.display.shift = false; }
7117 - done = bound(cm) != Pass;
7118 - } finally {
7119 - cm.display.shift = prevShift;
7120 - cm.state.suppressEdits = false;
7121 - }
7122 - return done
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 }
7123 7069 }
7070 + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7071 + || lookupKey(name, cm.options.keyMap, handle, cm)
7072 +}
7124 7073
7125 - function lookupKeyForEditor(cm, name, handle) {
7126 - for (var i = 0; i < cm.state.keyMaps.length; i++) {
7127 - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
7128 - if (result) { return result }
7129 - }
7130 - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
7131 - || lookupKey(name, cm.options.keyMap, handle, cm)
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 }
7132 7093 }
7094 + return dispatchKeyInner(cm, name, e, handle)
7095 +}
7133 7096
7134 - // Note that, despite the name, this function is also used to check
7135 - // for bound mouse clicks.
7097 +function dispatchKeyInner(cm, name, e, handle) {
7098 + var result = lookupKeyForEditor(cm, name, handle);
7136 7099
7137 - var stopSeq = new Delayed;
7100 + if (result == "multi")
7101 + { cm.state.keySeq = name; }
7102 + if (result == "handled")
7103 + { signalLater(cm, "keyHandled", cm, name, e); }
7138 7104
7139 - function dispatchKey(cm, name, e, handle) {
7140 - var seq = cm.state.keySeq;
7141 - if (seq) {
7142 - if (isModifierKey(name)) { return "handled" }
7143 - if (/\'$/.test(name))
7144 - { cm.state.keySeq = null; }
7145 - else
7146 - { stopSeq.set(50, function () {
7147 - if (cm.state.keySeq == seq) {
7148 - cm.state.keySeq = null;
7149 - cm.display.input.reset();
7150 - }
7151 - }); }
7152 - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
7153 - }
7154 - return dispatchKeyInner(cm, name, e, handle)
7105 + if (result == "handled" || result == "multi") {
7106 + e_preventDefault(e);
7107 + restartBlink(cm);
7155 7108 }
7156 7109
7157 - function dispatchKeyInner(cm, name, e, handle) {
7158 - var result = lookupKeyForEditor(cm, name, handle);
7110 + return !!result
7111 +}
7159 7112
7160 - if (result == "multi")
7161 - { cm.state.keySeq = name; }
7162 - if (result == "handled")
7163 - { signalLater(cm, "keyHandled", cm, name, e); }
7113 +// Handle a key from the keydown event.
7114 +function handleKeyBinding(cm, e) {
7115 + var name = keyName(e, true);
7116 + if (!name) { return false }
7164 7117
7165 - if (result == "handled" || result == "multi") {
7166 - e_preventDefault(e);
7167 - restartBlink(cm);
7168 - }
7169 -
7170 - return !!result
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); })
7171 7129 }
7130 +}
7172 7131
7173 - // Handle a key from the keydown event.
7174 - function handleKeyBinding(cm, e) {
7175 - var name = keyName(e, true);
7176 - if (!name) { return false }
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 +}
7177 7136
7178 - if (e.shiftKey && !cm.state.keySeq) {
7179 - // First try to resolve full name (including 'Shift-'). Failing
7180 - // that, see if there is a cursor-motion command (starting with
7181 - // 'go') bound to the keyname without 'Shift-'.
7182 - return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
7183 - || dispatchKey(cm, name, e, function (b) {
7184 - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
7185 - { return doHandleBinding(cm, b) }
7186 - })
7187 - } else {
7188 - return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
7189 - }
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"); }
7190 7152 }
7191 7153
7192 - // Handle a key from the keypress event
7193 - function handleCharBinding(cm, e, ch) {
7194 - return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
7195 - }
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 +}
7196 7158
7197 - var lastStoppedKey = null;
7198 - function onKeyDown(e) {
7199 - var cm = this;
7200 - if (e.target && e.target != cm.display.input.getField()) { return }
7201 - cm.curOp.focus = activeElt();
7202 - if (signalDOMEvent(cm, e)) { return }
7203 - // IE does strange things with escape.
7204 - if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
7205 - var code = e.keyCode;
7206 - cm.display.shift = code == 16 || e.shiftKey;
7207 - var handled = handleKeyBinding(cm, e);
7208 - if (presto) {
7209 - lastStoppedKey = handled ? code : null;
7210 - // Opera has no cut event... we try to at least catch the key combo
7211 - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
7212 - { cm.replaceSelection("", null, "cut"); }
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);
7213 7168 }
7214 - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
7215 - { document.execCommand("cut"); }
7216 -
7217 - // Turn mouse into crosshair when Alt is held on Mac.
7218 - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
7219 - { showCrossHair(cm); }
7220 7169 }
7170 + on(document, "keyup", up);
7171 + on(document, "mouseover", up);
7172 +}
7221 7173
7222 - function showCrossHair(cm) {
7223 - var lineDiv = cm.display.lineDiv;
7224 - addClass(lineDiv, "CodeMirror-crosshair");
7174 +function onKeyUp(e) {
7175 + if (e.keyCode == 16) { this.doc.sel.shift = false; }
7176 + signalDOMEvent(this, e);
7177 +}
7225 7178
7226 - function up(e) {
7227 - if (e.keyCode == 18 || !e.altKey) {
7228 - rmClass(lineDiv, "CodeMirror-crosshair");
7229 - off(document, "keyup", up);
7230 - off(document, "mouseover", up);
7231 - }
7232 - }
7233 - on(document, "keyup", up);
7234 - on(document, "mouseover", up);
7235 - }
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 +}
7236 7191
7237 - function onKeyUp(e) {
7238 - if (e.keyCode == 16) { this.doc.sel.shift = false; }
7239 - signalDOMEvent(this, e);
7240 - }
7192 +var DOUBLECLICK_DELAY = 400;
7241 7193
7242 - function onKeyPress(e) {
7243 - var cm = this;
7244 - if (e.target && e.target != cm.display.input.getField()) { return }
7245 - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
7246 - var keyCode = e.keyCode, charCode = e.charCode;
7247 - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
7248 - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
7249 - var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
7250 - // Some browsers fire keypress events for backspace
7251 - if (ch == "\x08") { return }
7252 - if (handleCharBinding(cm, e, ch)) { return }
7253 - cm.display.input.onKeyPress(e);
7254 - }
7194 +var PastClick = function(time, pos, button) {
7195 + this.time = time;
7196 + this.pos = pos;
7197 + this.button = button;
7198 +};
7255 7199
7256 - var DOUBLECLICK_DELAY = 400;
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 +};
7257 7204
7258 - var PastClick = function(time, pos, button) {
7259 - this.time = time;
7260 - this.pos = pos;
7261 - this.button = button;
7262 - };
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 +}
7263 7222
7264 - PastClick.prototype.compare = function (time, pos, button) {
7265 - return this.time + DOUBLECLICK_DELAY > time &&
7266 - cmp(pos, this.pos) == 0 && button == this.button
7267 - };
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;
7268 7233
7269 - var lastClick, lastDoubleClick;
7270 - function clickRepeat(pos, button) {
7271 - var now = +new Date;
7272 - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
7273 - lastClick = lastDoubleClick = null;
7274 - return "triple"
7275 - } else if (lastClick && lastClick.compare(now, pos, button)) {
7276 - lastDoubleClick = new PastClick(now, pos, button);
7277 - lastClick = null;
7278 - return "double"
7279 - } else {
7280 - lastClick = new PastClick(now, pos, button);
7281 - lastDoubleClick = null;
7282 - return "single"
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);
7283 7240 }
7241 + return
7284 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();
7285 7246
7286 - // A mouse down can be a single click, double click, triple click,
7287 - // start of selection drag, start of text drag, new cursor
7288 - // (ctrl-click), rectangle drag (alt-drag), or xwin
7289 - // middle-click-paste. Or it might be a click on something we should
7290 - // not interfere with, such as a scrollbar or widget.
7291 - function onMouseDown(e) {
7292 - var cm = this, display = cm.display;
7293 - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
7294 - display.input.ensurePolled();
7295 - display.shift = e.shiftKey;
7247 + // #3261: make sure, that we're not starting a second selection
7248 + if (button == 1 && cm.state.selectingText)
7249 + { cm.state.selectingText(e); }
7296 7250
7297 - if (eventInWidget(display, e)) {
7298 - if (!webkit) {
7299 - // Briefly turn off draggability, to allow widgets to do
7300 - // normal dragging things.
7301 - display.scroller.draggable = false;
7302 - setTimeout(function () { return display.scroller.draggable = true; }, 100);
7303 - }
7304 - return
7305 - }
7306 - if (clickInGutter(cm, e)) { return }
7307 - var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
7308 - window.focus();
7251 + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
7309 7252
7310 - // #3261: make sure, that we're not starting a second selection
7311 - if (button == 1 && cm.state.selectingText)
7312 - { cm.state.selectingText(e); }
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 +}
7313 7264
7314 - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
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;
7315 7270
7316 - if (button == 1) {
7317 - if (pos) { leftButtonDown(cm, pos, repeat, e); }
7318 - else if (e_target(e) == display.scroller) { e_preventDefault(e); }
7319 - } else if (button == 2) {
7320 - if (pos) { extendSelection(cm.doc, pos); }
7321 - setTimeout(function () { return display.input.focus(); }, 20);
7322 - } else if (button == 3) {
7323 - if (captureRightClick) { cm.display.input.onContextMenu(e); }
7324 - else { delayBlurEvent(cm); }
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;
7325 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";
7326 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 +}
7327 7297
7328 - function handleMappedButton(cm, button, pos, repeat, event) {
7329 - var name = "Click";
7330 - if (repeat == "double") { name = "Double" + name; }
7331 - else if (repeat == "triple") { name = "Triple" + name; }
7332 - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
7298 +function leftButtonDown(cm, pos, repeat, event) {
7299 + if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
7300 + else { cm.curOp.focus = activeElt(); }
7333 7301
7334 - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
7335 - if (typeof bound == "string") { bound = commands[bound]; }
7336 - if (!bound) { return false }
7337 - var done = false;
7338 - try {
7339 - if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
7340 - done = bound(cm, pos) != Pass;
7341 - } finally {
7342 - cm.state.suppressEdits = false;
7343 - }
7344 - return done
7345 - })
7346 - }
7302 + var behavior = configureMouse(cm, repeat, event);
7347 7303
7348 - function configureMouse(cm, repeat, event) {
7349 - var option = cm.getOption("configureMouse");
7350 - var value = option ? option(cm, repeat, event) : {};
7351 - if (value.unit == null) {
7352 - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
7353 - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
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(); }
7354 7334 }
7355 - if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
7356 - if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
7357 - if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
7358 - return value
7359 - }
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);
7360 7350
7361 - function leftButtonDown(cm, pos, repeat, event) {
7362 - if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
7363 - else { cm.curOp.focus = activeElt(); }
7351 + delayBlurEvent(cm);
7352 + setTimeout(function () { return display.input.focus(); }, 20);
7353 +}
7364 7354
7365 - var behavior = configureMouse(cm, repeat, event);
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 +}
7366 7362
7367 - var sel = cm.doc.sel, contained;
7368 - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
7369 - repeat == "single" && (contained = sel.contains(pos)) > -1 &&
7370 - (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
7371 - (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
7372 - { leftButtonStartDrag(cm, event, pos, behavior); }
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 7373 else
7374 - { leftButtonSelect(cm, event, pos, behavior); }
7374 + { ourRange = new Range(start, start); }
7375 + } else {
7376 + ourRange = doc.sel.primary();
7377 + ourIndex = doc.sel.primIndex;
7375 7378 }
7376 7379
7377 - // Start a text drag. When it ends, see if any dragging actually
7378 - // happen, and treat as a click if it didn't.
7379 - function leftButtonStartDrag(cm, event, pos, behavior) {
7380 - var display = cm.display, moved = false;
7381 - var dragEnd = operation(cm, function (e) {
7382 - if (webkit) { display.scroller.draggable = false; }
7383 - cm.state.draggingText = false;
7384 - if (cm.state.delayingBlurEvent) {
7385 - if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
7386 - else { delayBlurEvent(cm); }
7387 - }
7388 - off(display.wrapper.ownerDocument, "mouseup", dragEnd);
7389 - off(display.wrapper.ownerDocument, "mousemove", mouseMove);
7390 - off(display.scroller, "dragstart", dragStart);
7391 - off(display.scroller, "drop", dragEnd);
7392 - if (!moved) {
7393 - e_preventDefault(e);
7394 - if (!behavior.addNew)
7395 - { extendSelection(cm.doc, pos, null, null, behavior.extend); }
7396 - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
7397 - if ((webkit && !safari) || ie && ie_version == 9)
7398 - { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
7399 - else
7400 - { display.input.focus(); }
7401 - }
7402 - });
7403 - var mouseMove = function(e2) {
7404 - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
7405 - };
7406 - var dragStart = function () { return moved = true; };
7407 - // Let the drag handler handle this.
7408 - if (webkit) { display.scroller.draggable = true; }
7409 - cm.state.draggingText = dragEnd;
7410 - dragEnd.copy = !behavior.moveOnDrag;
7411 - on(display.wrapper.ownerDocument, "mouseup", dragEnd);
7412 - on(display.wrapper.ownerDocument, "mousemove", mouseMove);
7413 - on(display.scroller, "dragstart", dragStart);
7414 - on(display.scroller, "drop", dragEnd);
7415 -
7416 - cm.state.delayingBlurEvent = true;
7417 - setTimeout(function () { return display.input.focus(); }, 20);
7418 - // IE's approach to draggable
7419 - if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
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; }
7420 7390 }
7421 7391
7422 - function rangeForUnit(cm, pos, unit) {
7423 - if (unit == "char") { return new Range(pos, pos) }
7424 - if (unit == "word") { return cm.findWordAt(pos) }
7425 - if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
7426 - var result = unit(cm, pos);
7427 - return new Range(result.from, result.to)
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);
7428 7406 }
7429 7407
7430 - // Normal selection, as opposed to text dragging.
7431 - function leftButtonSelect(cm, event, start, behavior) {
7432 - if (ie) { delayBlurEvent(cm); }
7433 - var display = cm.display, doc = cm.doc;
7434 - e_preventDefault(event);
7408 + var lastPos = start;
7409 + function extendTo(pos) {
7410 + if (cmp(lastPos, pos) == 0) { return }
7411 + lastPos = pos;
7435 7412
7436 - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
7437 - if (behavior.addNew && !behavior.extend) {
7438 - ourIndex = doc.sel.contains(start);
7439 - if (ourIndex > -1)
7440 - { ourRange = ranges[ourIndex]; }
7441 - else
7442 - { ourRange = new Range(start, start); }
7443 - } else {
7444 - ourRange = doc.sel.primary();
7445 - ourIndex = doc.sel.primIndex;
7446 - }
7447 -
7448 7413 if (behavior.unit == "rectangle") {
7449 - if (!behavior.addNew) { ourRange = new Range(start, start); }
7450 - start = posFromMouse(cm, event, true, true);
7451 - ourIndex = -1;
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);
7452 7430 } else {
7453 - var range = rangeForUnit(cm, start, behavior.unit);
7454 - if (behavior.extend)
7455 - { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
7456 - else
7457 - { ourRange = range; }
7458 - }
7459 -
7460 - if (!behavior.addNew) {
7461 - ourIndex = 0;
7462 - setSelection(doc, new Selection([ourRange], 0), sel_mouse);
7463 - startSel = doc.sel;
7464 - } else if (ourIndex == -1) {
7465 - ourIndex = ranges.length;
7466 - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
7467 - {scroll: false, origin: "*mouse"});
7468 - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
7469 - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
7470 - {scroll: false, origin: "*mouse"});
7471 - startSel = doc.sel;
7472 - } else {
7473 - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
7474 - }
7475 -
7476 - var lastPos = start;
7477 - function extendTo(pos) {
7478 - if (cmp(lastPos, pos) == 0) { return }
7479 - lastPos = pos;
7480 -
7481 - if (behavior.unit == "rectangle") {
7482 - var ranges = [], tabSize = cm.options.tabSize;
7483 - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
7484 - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
7485 - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
7486 - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
7487 - line <= end; line++) {
7488 - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
7489 - if (left == right)
7490 - { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
7491 - else if (text.length > leftPos)
7492 - { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
7493 - }
7494 - if (!ranges.length) { ranges.push(new Range(start, start)); }
7495 - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
7496 - {origin: "*mouse", scroll: false});
7497 - cm.scrollIntoView(pos);
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);
7498 7437 } else {
7499 - var oldRange = ourRange;
7500 - var range = rangeForUnit(cm, pos, behavior.unit);
7501 - var anchor = oldRange.anchor, head;
7502 - if (cmp(range.anchor, anchor) > 0) {
7503 - head = range.head;
7504 - anchor = minPos(oldRange.from(), range.anchor);
7505 - } else {
7506 - head = range.anchor;
7507 - anchor = maxPos(oldRange.to(), range.head);
7508 - }
7509 - var ranges$1 = startSel.ranges.slice(0);
7510 - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
7511 - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
7438 + head = range$$1.anchor;
7439 + anchor = maxPos(oldRange.to(), range$$1.head);
7512 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);
7513 7444 }
7445 + }
7514 7446
7515 - var editorSize = display.wrapper.getBoundingClientRect();
7516 - // Used to ensure timeout re-tries don't fire when another extend
7517 - // happened in the meantime (clearTimeout isn't reliable -- at
7518 - // least on Chrome, the timeouts still happen even when cleared,
7519 - // if the clear happens after their scheduled firing time).
7520 - var counter = 0;
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;
7521 7453
7522 - function extend(e) {
7523 - var curCount = ++counter;
7524 - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
7525 - if (!cur) { return }
7526 - if (cmp(cur, lastPos) != 0) {
7527 - cm.curOp.focus = activeElt();
7528 - extendTo(cur);
7529 - var visible = visibleLines(display, doc);
7530 - if (cur.line >= visible.to || cur.line < visible.from)
7531 - { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
7532 - } else {
7533 - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
7534 - if (outside) { setTimeout(operation(cm, function () {
7535 - if (counter != curCount) { return }
7536 - display.scroller.scrollTop += outside;
7537 - extend(e);
7538 - }), 50); }
7539 - }
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); }
7540 7471 }
7472 + }
7541 7473
7542 - function done(e) {
7543 - cm.state.selectingText = false;
7544 - counter = Infinity;
7545 - // If e is null or undefined we interpret this as someone trying
7546 - // to explicitly cancel the selection rather than the user
7547 - // letting go of the mouse button.
7548 - if (e) {
7549 - e_preventDefault(e);
7550 - display.input.focus();
7551 - }
7552 - off(display.wrapper.ownerDocument, "mousemove", move);
7553 - off(display.wrapper.ownerDocument, "mouseup", up);
7554 - doc.history.lastSelOrigin = null;
7555 - }
7556 -
7557 - var move = operation(cm, function (e) {
7558 - if (e.buttons === 0 || !e_button(e)) { done(e); }
7559 - else { extend(e); }
7560 - });
7561 - var up = operation(cm, done);
7562 - cm.state.selectingText = up;
7563 - on(display.wrapper.ownerDocument, "mousemove", move);
7564 - on(display.wrapper.ownerDocument, "mouseup", up);
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;
7565 7482 }
7566 7483
7567 - // Used when mouse-selecting to adjust the anchor to the proper side
7568 - // of a bidi jump depending on the visual position of the head.
7569 - function bidiSimplify(cm, range) {
7570 - var anchor = range.anchor;
7571 - var head = range.head;
7572 - var anchorLine = getLine(cm.doc, anchor.line);
7573 - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
7574 - var order = getOrder(anchorLine);
7575 - if (!order) { return range }
7576 - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
7577 - if (part.from != anchor.ch && part.to != anchor.ch) { return range }
7578 - var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
7579 - if (boundary == 0 || boundary == order.length) { return range }
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 +}
7580 7493
7581 - // Compute the relative visual position of the head compared to the
7582 - // anchor (<0 is to the left, >0 to the right)
7583 - var leftSide;
7584 - if (head.line != anchor.line) {
7585 - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
7586 - } else {
7587 - var headIndex = getBidiPartAt(order, head.ch, head.sticky);
7588 - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
7589 - if (headIndex == boundary - 1 || headIndex == boundary)
7590 - { leftSide = dir < 0; }
7591 - else
7592 - { leftSide = dir > 0; }
7593 - }
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 }
7594 7507
7595 - var usePart = order[boundary + (leftSide ? -1 : 0)];
7596 - var from = leftSide == (usePart.level == 1);
7597 - var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
7598 - return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
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; }
7599 7520 }
7600 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 +}
7601 7527
7602 - // Determines whether an event happened in the gutter, and fires the
7603 - // handlers for the corresponding event.
7604 - function gutterEvent(cm, e, type, prevent) {
7605 - var mX, mY;
7606 - if (e.touches) {
7607 - mX = e.touches[0].clientX;
7608 - mY = e.touches[0].clientY;
7609 - } else {
7610 - try { mX = e.clientX; mY = e.clientY; }
7611 - catch(e$1) { return false }
7612 - }
7613 - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
7614 - if (prevent) { e_preventDefault(e); }
7615 7528
7616 - var display = cm.display;
7617 - var lineBox = display.lineDiv.getBoundingClientRect();
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); }
7618 7542
7619 - if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
7620 - mY -= lineBox.top - display.viewOffset;
7543 + var display = cm.display;
7544 + var lineBox = display.lineDiv.getBoundingClientRect();
7621 7545
7622 - for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
7623 - var g = display.gutters.childNodes[i];
7624 - if (g && g.getBoundingClientRect().right >= mX) {
7625 - var line = lineAtHeight(cm.doc, mY);
7626 - var gutter = cm.display.gutterSpecs[i];
7627 - signal(cm, type, cm, line, gutter.className, e);
7628 - return e_defaultPrevented(e)
7629 - }
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)
7630 7556 }
7631 7557 }
7558 +}
7632 7559
7633 - function clickInGutter(cm, e) {
7634 - return gutterEvent(cm, e, "gutterClick", true)
7635 - }
7560 +function clickInGutter(cm, e) {
7561 + return gutterEvent(cm, e, "gutterClick", true)
7562 +}
7636 7563
7637 - // CONTEXT MENU HANDLING
7564 +// CONTEXT MENU HANDLING
7638 7565
7639 - // To make the context menu work, we need to briefly unhide the
7640 - // textarea (making it as unobtrusive as possible) to let the
7641 - // right-click take effect on it.
7642 - function onContextMenu(cm, e) {
7643 - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
7644 - if (signalDOMEvent(cm, e, "contextmenu")) { return }
7645 - if (!captureRightClick) { cm.display.input.onContextMenu(e); }
7646 - }
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 +}
7647 7574
7648 - function contextMenuInGutter(cm, e) {
7649 - if (!hasHandler(cm, "gutterContextMenu")) { return false }
7650 - return gutterEvent(cm, e, "gutterContextMenu", false)
7651 - }
7575 +function contextMenuInGutter(cm, e) {
7576 + if (!hasHandler(cm, "gutterContextMenu")) { return false }
7577 + return gutterEvent(cm, e, "gutterContextMenu", false)
7578 +}
7652 7579
7653 - function themeChanged(cm) {
7654 - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
7655 - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
7656 - clearCaches(cm);
7657 - }
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 +}
7658 7585
7659 - var Init = {toString: function(){return "CodeMirror.Init"}};
7586 +var Init = {toString: function(){return "CodeMirror.Init"}};
7660 7587
7661 - var defaults = {};
7662 - var optionHandlers = {};
7588 +var defaults = {};
7589 +var optionHandlers = {};
7663 7590
7664 - function defineOptions(CodeMirror) {
7665 - var optionHandlers = CodeMirror.optionHandlers;
7591 +function defineOptions(CodeMirror) {
7592 + var optionHandlers = CodeMirror.optionHandlers;
7666 7593
7667 - function option(name, deflt, handle, notOnInit) {
7668 - CodeMirror.defaults[name] = deflt;
7669 - if (handle) { optionHandlers[name] =
7670 - notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
7671 - }
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 + }
7672 7599
7673 - CodeMirror.defineOption = option;
7600 + CodeMirror.defineOption = option;
7674 7601
7675 - // Passed to option handlers when there is no old value.
7676 - CodeMirror.Init = Init;
7602 + // Passed to option handlers when there is no old value.
7603 + CodeMirror.Init = Init;
7677 7604
7678 - // These two are, on init, called from the constructor because they
7679 - // have to be initialized before the editor can start at all.
7680 - option("value", "", function (cm, val) { return cm.setValue(val); }, true);
7681 - option("mode", null, function (cm, val) {
7682 - cm.doc.modeOption = val;
7683 - loadMode(cm);
7684 - }, true);
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);
7685 7612
7686 - option("indentUnit", 2, loadMode, true);
7687 - option("indentWithTabs", false);
7688 - option("smartIndent", true);
7689 - option("tabSize", 4, function (cm) {
7690 - resetModeState(cm);
7691 - clearCaches(cm);
7692 - regChange(cm);
7693 - }, true);
7694 -
7695 - option("lineSeparator", null, function (cm, val) {
7696 - cm.doc.lineSep = val;
7697 - if (!val) { return }
7698 - var newBreaks = [], lineNo = cm.doc.first;
7699 - cm.doc.iter(function (line) {
7700 - for (var pos = 0;;) {
7701 - var found = line.text.indexOf(val, pos);
7702 - if (found == -1) { break }
7703 - pos = found + val.length;
7704 - newBreaks.push(Pos(lineNo, found));
7705 - }
7706 - lineNo++;
7707 - });
7708 - for (var i = newBreaks.length - 1; i >= 0; i--)
7709 - { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
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++;
7710 7633 });
7711 - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
7712 - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
7713 - if (old != Init) { cm.refresh(); }
7714 - });
7715 - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
7716 - option("electricChars", true);
7717 - option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
7718 - throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
7719 - }, true);
7720 - option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
7721 - option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
7722 - option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
7723 - option("rtlMoveVisually", !windows);
7724 - option("wholeLineUpdateBefore", true);
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);
7725 7649
7726 - option("theme", "default", function (cm) {
7727 - themeChanged(cm);
7728 - updateGutters(cm);
7729 - }, true);
7730 - option("keyMap", "default", function (cm, val, old) {
7731 - var next = getKeyMap(val);
7732 - var prev = old != Init && getKeyMap(old);
7733 - if (prev && prev.detach) { prev.detach(cm, next); }
7734 - if (next.attach) { next.attach(cm, prev || null); }
7735 - });
7736 - option("extraKeys", null);
7737 - option("configureMouse", null);
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);
7738 7662
7739 - option("lineWrapping", false, wrappingChanged, true);
7740 - option("gutters", [], function (cm, val) {
7741 - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
7742 - updateGutters(cm);
7743 - }, true);
7744 - option("fixedGutter", true, function (cm, val) {
7745 - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
7746 - cm.refresh();
7747 - }, true);
7748 - option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
7749 - option("scrollbarStyle", "native", function (cm) {
7750 - initScrollbars(cm);
7751 - updateScrollbars(cm);
7752 - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
7753 - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
7754 - }, true);
7755 - option("lineNumbers", false, function (cm, val) {
7756 - cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
7757 - updateGutters(cm);
7758 - }, true);
7759 - option("firstLineNumber", 1, updateGutters, true);
7760 - option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
7761 - option("showCursorWhenSelecting", false, updateSelection, true);
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);
7762 7686
7763 - option("resetSelectionOnContextMenu", true);
7764 - option("lineWiseCopyCut", true);
7765 - option("pasteLinesPerSelection", true);
7766 - option("selectionsMayTouch", false);
7687 + option("resetSelectionOnContextMenu", true);
7688 + option("lineWiseCopyCut", true);
7689 + option("pasteLinesPerSelection", true);
7767 7690
7768 - option("readOnly", false, function (cm, val) {
7769 - if (val == "nocursor") {
7770 - onBlur(cm);
7771 - cm.display.input.blur();
7772 - }
7773 - cm.display.input.readOnlyChanged(val);
7774 - });
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);
7775 7701
7776 - option("screenReaderLabel", null, function (cm, val) {
7777 - val = (val === '') ? null : val;
7778 - cm.display.input.screenReaderLabelChanged(val);
7779 - });
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 + });
7780 7718
7781 - option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
7782 - option("dragDrop", true, dragDropChanged);
7783 - option("allowDropFileTypes", null);
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 +}
7784 7723
7785 - option("cursorBlinkRate", 530);
7786 - option("cursorScrollMargin", 0);
7787 - option("cursorHeight", 1, updateSelection, true);
7788 - option("singleCursorHeightPerLine", true, updateSelection, true);
7789 - option("workTime", 100);
7790 - option("workDelay", 100);
7791 - option("flattenSpans", true, resetModeState, true);
7792 - option("addModeClass", false, resetModeState, true);
7793 - option("pollInterval", 100);
7794 - option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
7795 - option("historyEventDelay", 1250);
7796 - option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
7797 - option("maxHighlightLength", 10000, resetModeState, true);
7798 - option("moveInputWithCursor", true, function (cm, val) {
7799 - if (!val) { cm.display.input.resetPosition(); }
7800 - });
7724 +function guttersChanged(cm) {
7725 + updateGutters(cm);
7726 + regChange(cm);
7727 + alignHorizontally(cm);
7728 +}
7801 7729
7802 - option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
7803 - option("autofocus", null);
7804 - option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
7805 - option("phrases", null);
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);
7806 7740 }
7741 +}
7807 7742
7808 - function dragDropChanged(cm, value, old) {
7809 - var wasOn = old && old != Init;
7810 - if (!value != !wasOn) {
7811 - var funcs = cm.display.dragFunctions;
7812 - var toggle = value ? on : off;
7813 - toggle(cm.display.scroller, "dragstart", funcs.start);
7814 - toggle(cm.display.scroller, "dragenter", funcs.enter);
7815 - toggle(cm.display.scroller, "dragover", funcs.over);
7816 - toggle(cm.display.scroller, "dragleave", funcs.leave);
7817 - toggle(cm.display.scroller, "drop", funcs.drop);
7818 - }
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);
7819 7751 }
7752 + estimateLineHeights(cm);
7753 + regChange(cm);
7754 + clearCaches(cm);
7755 + setTimeout(function () { return updateScrollbars(cm); }, 100);
7756 +}
7820 7757
7821 - function wrappingChanged(cm) {
7822 - if (cm.options.lineWrapping) {
7823 - addClass(cm.display.wrapper, "CodeMirror-wrap");
7824 - cm.display.sizer.style.minWidth = "";
7825 - cm.display.sizerWidth = null;
7826 - } else {
7827 - rmClass(cm.display.wrapper, "CodeMirror-wrap");
7828 - findMaxLine(cm);
7829 - }
7830 - estimateLineHeights(cm);
7831 - regChange(cm);
7832 - clearCaches(cm);
7833 - setTimeout(function () { return updateScrollbars(cm); }, 100);
7834 - }
7758 +// A CodeMirror instance represents an editor. This is the object
7759 +// that user code is usually dealing with.
7835 7760
7836 - // A CodeMirror instance represents an editor. This is the object
7837 - // that user code is usually dealing with.
7761 +function CodeMirror$1(place, options) {
7762 + var this$1 = this;
7838 7763
7839 - function CodeMirror(place, options) {
7840 - var this$1 = this;
7764 + if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
7841 7765
7842 - if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
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);
7843 7770
7844 - this.options = options = options ? copyObj(options) : {};
7845 - // Determine effective options based on given values and defaults.
7846 - copyObj(defaults, options, false);
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;
7847 7774
7848 - var doc = options.value;
7849 - if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
7850 - else if (options.mode) { doc.modeOption = options.mode; }
7851 - this.doc = doc;
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);
7852 7783
7853 - var input = new CodeMirror.inputStyles[options.inputStyle](this);
7854 - var display = this.display = new Display(place, doc, input, options);
7855 - display.wrapper.CodeMirror = this;
7856 - themeChanged(this);
7857 - if (options.lineWrapping)
7858 - { this.display.wrapper.className += " CodeMirror-wrap"; }
7859 - initScrollbars(this);
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 + };
7860 7799
7861 - this.state = {
7862 - keyMaps: [], // stores maps added by addKeyMap
7863 - overlays: [], // highlighting overlays, as added by addOverlay
7864 - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
7865 - overwrite: false,
7866 - delayingBlurEvent: false,
7867 - focused: false,
7868 - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
7869 - pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
7870 - selectingText: false,
7871 - draggingText: false,
7872 - highlight: new Delayed(), // stores highlight worker timeout
7873 - keySeq: null, // Unfinished key sequence
7874 - specialChars: null
7875 - };
7800 + if (options.autofocus && !mobile) { display.input.focus(); }
7876 7801
7877 - if (options.autofocus && !mobile) { display.input.focus(); }
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); }
7878 7805
7879 - // Override magic textarea content restore that IE sometimes does
7880 - // on our hidden textarea on reload
7881 - if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
7806 + registerEventHandlers(this);
7807 + ensureGlobalHandlers();
7882 7808
7883 - registerEventHandlers(this);
7884 - ensureGlobalHandlers();
7809 + startOperation(this);
7810 + this.curOp.forceUpdate = true;
7811 + attachDoc(this, doc);
7885 7812
7886 - startOperation(this);
7887 - this.curOp.forceUpdate = true;
7888 - attachDoc(this, doc);
7813 + if ((options.autofocus && !mobile) || this.hasFocus())
7814 + { setTimeout(bind(onFocus, this), 20); }
7815 + else
7816 + { onBlur(this); }
7889 7817
7890 - if ((options.autofocus && !mobile) || this.hasFocus())
7891 - { setTimeout(function () {
7892 - if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
7893 - }, 20); }
7894 - else
7895 - { onBlur(this); }
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 +}
7896 7830
7897 - for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
7898 - { optionHandlers[opt](this, options[opt], Init); } }
7899 - maybeUpdateLineNumberWidth(this);
7900 - if (options.finishInit) { options.finishInit(this); }
7901 - for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
7902 - endOperation(this);
7903 - // Suppress optimizelegibility in Webkit, since it breaks text
7904 - // measuring on line wrapping boundaries.
7905 - if (webkit && options.lineWrapping &&
7906 - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
7907 - { display.lineDiv.style.textRendering = "auto"; }
7908 - }
7831 +// The default configuration options.
7832 +CodeMirror$1.defaults = defaults;
7833 +// Functions to run when options are changed.
7834 +CodeMirror$1.optionHandlers = optionHandlers;
7909 7835
7910 - // The default configuration options.
7911 - CodeMirror.defaults = defaults;
7912 - // Functions to run when options are changed.
7913 - CodeMirror.optionHandlers = optionHandlers;
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); }); }
7914 7856
7915 - // Attach the necessary event handlers when initializing the editor
7916 - function registerEventHandlers(cm) {
7917 - var d = cm.display;
7918 - on(d.scroller, "mousedown", operation(cm, onMouseDown));
7919 - // Older IE's will not fire a second mousedown for a double click
7920 - if (ie && ie_version < 11)
7921 - { on(d.scroller, "dblclick", operation(cm, function (e) {
7922 - if (signalDOMEvent(cm, e)) { return }
7923 - var pos = posFromMouse(cm, e);
7924 - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
7925 - e_preventDefault(e);
7926 - var word = cm.findWordAt(pos);
7927 - extendSelection(cm.doc, word.anchor, word.head);
7928 - })); }
7929 - else
7930 - { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
7931 - // Some browsers fire contextmenu *after* opening the menu, at
7932 - // which point we can't mess with it anymore. Context menu is
7933 - // handled in onMouseDown for these browsers.
7934 - on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
7935 - on(d.input.getField(), "contextmenu", function (e) {
7936 - if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
7937 - });
7938 -
7939 - // Used to suppress mouse event handling when a touch happens
7940 - var touchFinished, prevTouch = {end: 0};
7941 - function finishTouch() {
7942 - if (d.activeTouch) {
7943 - touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
7944 - prevTouch = d.activeTouch;
7945 - prevTouch.end = +new Date;
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;
7946 7886 }
7947 7887 }
7948 - function isMouseLikeTouchEvent(e) {
7949 - if (e.touches.length != 1) { return false }
7950 - var touch = e.touches[0];
7951 - return touch.radiusX <= 1 && touch.radiusY <= 1
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);
7952 7906 }
7953 - function farAway(touch, other) {
7954 - if (other.left == null) { return true }
7955 - var dx = other.left - touch.left, dy = other.top - touch.top;
7956 - return dx * dx + dy * dy > 20 * 20
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);
7957 7918 }
7958 - on(d.scroller, "touchstart", function (e) {
7959 - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
7960 - d.input.ensurePolled();
7961 - clearTimeout(touchFinished);
7962 - var now = +new Date;
7963 - d.activeTouch = {start: now, moved: false,
7964 - prev: now - prevTouch.end <= 300 ? prevTouch : null};
7965 - if (e.touches.length == 1) {
7966 - d.activeTouch.left = e.touches[0].pageX;
7967 - d.activeTouch.top = e.touches[0].pageY;
7968 - }
7969 - }
7970 - });
7971 - on(d.scroller, "touchmove", function () {
7972 - if (d.activeTouch) { d.activeTouch.moved = true; }
7973 - });
7974 - on(d.scroller, "touchend", function (e) {
7975 - var touch = d.activeTouch;
7976 - if (touch && !eventInWidget(d, e) && touch.left != null &&
7977 - !touch.moved && new Date - touch.start < 300) {
7978 - var pos = cm.coordsChar(d.activeTouch, "page"), range;
7979 - if (!touch.prev || farAway(touch, touch.prev)) // Single tap
7980 - { range = new Range(pos, pos); }
7981 - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
7982 - { range = cm.findWordAt(pos); }
7983 - else // Triple tap
7984 - { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
7985 - cm.setSelection(range.anchor, range.head);
7986 - cm.focus();
7987 - e_preventDefault(e);
7988 - }
7989 - finishTouch();
7990 - });
7991 - on(d.scroller, "touchcancel", finishTouch);
7919 + });
7992 7920
7993 - // Sync scrolling between fake scrollbars and real scrollable
7994 - // area, ensure viewport is updated when scrolling.
7995 - on(d.scroller, "scroll", function () {
7996 - if (d.scroller.clientHeight) {
7997 - updateScrollTop(cm, d.scroller.scrollTop);
7998 - setScrollLeft(cm, d.scroller.scrollLeft, true);
7999 - signal(cm, "scroll", cm);
8000 - }
8001 - });
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); });
8002 7924
8003 - // Listen to wheel events in order to try and update the viewport on time.
8004 - on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
8005 - on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
7925 + // Prevent wrapper from ever scrolling
7926 + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
8006 7927
8007 - // Prevent wrapper from ever scrolling
8008 - on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
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 + };
8009 7935
8010 - d.dragFunctions = {
8011 - enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
8012 - over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
8013 - start: function (e) { return onDragStart(cm, e); },
8014 - drop: operation(cm, onDrop),
8015 - leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
8016 - };
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 +}
8017 7943
8018 - var inp = d.input.getField();
8019 - on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
8020 - on(inp, "keydown", operation(cm, onKeyDown));
8021 - on(inp, "keypress", operation(cm, onKeyPress));
8022 - on(inp, "focus", function (e) { return onFocus(cm, e); });
8023 - on(inp, "blur", function (e) { return onBlur(cm, e); });
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; }
8024 7960 }
8025 7961
8026 - var initHooks = [];
8027 - CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
8028 -
8029 - // Indent the given line. The how parameter can be "smart",
8030 - // "add"/null, "subtract", or "prev". When aggressive is false
8031 - // (typically set to true for forced single-line indents), empty
8032 - // lines are not indented, and places where the mode returns Pass
8033 - // are left alone.
8034 - function indentLine(cm, n, how, aggressive) {
8035 - var doc = cm.doc, state;
8036 - if (how == null) { how = "add"; }
8037 - if (how == "smart") {
8038 - // Fall back to "prev" when the mode doesn't have an indentation
8039 - // method.
8040 - if (!doc.mode.indent) { how = "prev"; }
8041 - else { state = getContextBefore(cm, n).state; }
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";
8042 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);
8043 7987
8044 - var tabSize = cm.options.tabSize;
8045 - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
8046 - if (line.stateAfter) { line.stateAfter = null; }
8047 - var curSpaceString = line.text.match(/^\s*/)[0], indentation;
8048 - if (!aggressive && !/\S/.test(line.text)) {
8049 - indentation = 0;
8050 - how = "not";
8051 - } else if (how == "smart") {
8052 - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
8053 - if (indentation == Pass || indentation > 150) {
8054 - if (!aggressive) { return }
8055 - how = "prev";
8056 - }
8057 - }
8058 - if (how == "prev") {
8059 - if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
8060 - else { indentation = 0; }
8061 - } else if (how == "add") {
8062 - indentation = curSpace + cm.options.indentUnit;
8063 - } else if (how == "subtract") {
8064 - indentation = curSpace - cm.options.indentUnit;
8065 - } else if (typeof how == "number") {
8066 - indentation = curSpace + how;
8067 - }
8068 - indentation = Math.max(0, indentation);
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); }
8069 7992
8070 - var indentString = "", pos = 0;
8071 - if (cm.options.indentWithTabs)
8072 - { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
8073 - if (pos < indentation) { indentString += spaceStr(indentation - pos); }
8074 -
8075 - if (indentString != curSpaceString) {
8076 - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
8077 - line.stateAfter = null;
8078 - return true
8079 - } else {
8080 - // Ensure that, if the cursor was in the whitespace at the start
8081 - // of the line, it is moved to the end of that space.
8082 - for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
8083 - var range = doc.sel.ranges[i$1];
8084 - if (range.head.line == n && range.head.ch < curSpaceString.length) {
8085 - var pos$1 = Pos(n, curSpaceString.length);
8086 - replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
8087 - break
8088 - }
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
8089 8006 }
8090 8007 }
8091 8008 }
8009 +}
8092 8010
8093 - // This will be set to a {lineWise: bool, text: [string]} object, so
8094 - // that, when pasting, we know what kind of selections the copied
8095 - // text was made out of.
8096 - var lastCopied = null;
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;
8097 8015
8098 - function setLastCopied(newLastCopied) {
8099 - lastCopied = newLastCopied;
8100 - }
8016 +function setLastCopied(newLastCopied) {
8017 + lastCopied = newLastCopied;
8018 +}
8101 8019
8102 - function applyTextInput(cm, inserted, deleted, sel, origin) {
8103 - var doc = cm.doc;
8104 - cm.display.shift = false;
8105 - if (!sel) { sel = doc.sel; }
8020 +function applyTextInput(cm, inserted, deleted, sel, origin) {
8021 + var doc = cm.doc;
8022 + cm.display.shift = false;
8023 + if (!sel) { sel = doc.sel; }
8106 8024
8107 - var recent = +new Date - 200;
8108 - var paste = origin == "paste" || cm.state.pasteIncoming > recent;
8109 - var textLines = splitLinesAuto(inserted), multiPaste = null;
8110 - // When pasting N lines into N selections, insert one line per selection
8111 - if (paste && sel.ranges.length > 1) {
8112 - if (lastCopied && lastCopied.text.join("\n") == inserted) {
8113 - if (sel.ranges.length % lastCopied.text.length == 0) {
8114 - multiPaste = [];
8115 - for (var i = 0; i < lastCopied.text.length; i++)
8116 - { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
8117 - }
8118 - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
8119 - multiPaste = map(textLines, function (l) { return [l]; });
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])); }
8120 8034 }
8035 + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
8036 + multiPaste = map(textLines, function (l) { return [l]; });
8121 8037 }
8038 + }
8122 8039
8123 - var updateInput = cm.curOp.updateInput;
8124 - // Normal behavior is to insert the new text into every selection
8125 - for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
8126 - var range = sel.ranges[i$1];
8127 - var from = range.from(), to = range.to();
8128 - if (range.empty()) {
8129 - if (deleted && deleted > 0) // Handle deletion
8130 - { from = Pos(from.line, from.ch - deleted); }
8131 - else if (cm.state.overwrite && !paste) // Handle overwrite
8132 - { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
8133 - else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
8134 - { from = to = Pos(from.line, 0); }
8135 - }
8136 - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
8137 - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
8138 - makeChange(cm.doc, changeEvent);
8139 - signalLater(cm, "inputRead", cm, changeEvent);
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); }
8140 8052 }
8141 - if (inserted && !paste)
8142 - { triggerElectric(cm, inserted); }
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); }
8143 8061
8144 - ensureCursorVisible(cm);
8145 - if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
8146 - cm.curOp.typing = true;
8147 - cm.state.pasteIncoming = cm.state.cutIncoming = -1;
8148 - }
8062 + ensureCursorVisible(cm);
8063 + cm.curOp.updateInput = updateInput;
8064 + cm.curOp.typing = true;
8065 + cm.state.pasteIncoming = cm.state.cutIncoming = false;
8066 +}
8149 8067
8150 - function handlePaste(e, cm) {
8151 - var pasted = e.clipboardData && e.clipboardData.getData("Text");
8152 - if (pasted) {
8153 - e.preventDefault();
8154 - if (!cm.isReadOnly() && !cm.options.disableInput)
8155 - { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
8156 - return true
8157 - }
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
8158 8075 }
8076 +}
8159 8077
8160 - function triggerElectric(cm, inserted) {
8161 - // When an 'electric' character is inserted, immediately trigger a reindent
8162 - if (!cm.options.electricChars || !cm.options.smartIndent) { return }
8163 - var sel = cm.doc.sel;
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;
8164 8082
8165 - for (var i = sel.ranges.length - 1; i >= 0; i--) {
8166 - var range = sel.ranges[i];
8167 - if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
8168 - var mode = cm.getModeAt(range.head);
8169 - var indented = false;
8170 - if (mode.electricChars) {
8171 - for (var j = 0; j < mode.electricChars.length; j++)
8172 - { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
8173 - indented = indentLine(cm, range.head.line, "smart");
8174 - break
8175 - } }
8176 - } else if (mode.electricInput) {
8177 - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
8178 - { indented = indentLine(cm, range.head.line, "smart"); }
8179 - }
8180 - if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
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"); }
8181 8097 }
8098 + if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
8182 8099 }
8100 +}
8183 8101
8184 - function copyableRanges(cm) {
8185 - var text = [], ranges = [];
8186 - for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
8187 - var line = cm.doc.sel.ranges[i].head.line;
8188 - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
8189 - ranges.push(lineRange);
8190 - text.push(cm.getRange(lineRange.anchor, lineRange.head));
8191 - }
8192 - return {text: text, ranges: ranges}
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));
8193 8109 }
8110 + return {text: text, ranges: ranges}
8111 +}
8194 8112
8195 - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
8196 - field.setAttribute("autocorrect", autocorrect ? "" : "off");
8197 - field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
8198 - field.setAttribute("spellcheck", !!spellcheck);
8199 - }
8113 +function disableBrowserMagic(field, spellcheck) {
8114 + field.setAttribute("autocorrect", "off");
8115 + field.setAttribute("autocapitalize", "off");
8116 + field.setAttribute("spellcheck", !!spellcheck);
8117 +}
8200 8118
8201 - function hiddenTextarea() {
8202 - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
8203 - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
8204 - // The textarea is kept positioned near the cursor to prevent the
8205 - // fact that it'll be scrolled into view on input from scrolling
8206 - // our fake cursor out of view. On webkit, when wrap=off, paste is
8207 - // very slow. So make the area wide instead.
8208 - if (webkit) { te.style.width = "1000px"; }
8209 - else { te.setAttribute("wrap", "off"); }
8210 - // If border: 0; -- iOS fails to open keyboard (issue #1287)
8211 - if (ios) { te.style.border = "1px solid black"; }
8212 - disableBrowserMagic(te);
8213 - return div
8214 - }
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 +}
8215 8133
8216 - // The publicly visible API. Note that methodOp(f) means
8217 - // 'wrap f in an operation, performed on its `this` parameter'.
8134 +// The publicly visible API. Note that methodOp(f) means
8135 +// 'wrap f in an operation, performed on its `this` parameter'.
8218 8136
8219 - // This is not the complete set of editor methods. Most of the
8220 - // methods defined on the Doc type are also injected into
8221 - // CodeMirror.prototype, for backwards compatibility and
8222 - // convenience.
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.
8223 8141
8224 - function addEditorMethods(CodeMirror) {
8225 - var optionHandlers = CodeMirror.optionHandlers;
8142 +var addEditorMethods = function(CodeMirror) {
8143 + var optionHandlers = CodeMirror.optionHandlers;
8226 8144
8227 - var helpers = CodeMirror.helpers = {};
8145 + var helpers = CodeMirror.helpers = {};
8228 8146
8229 - CodeMirror.prototype = {
8230 - constructor: CodeMirror,
8231 - focus: function(){window.focus(); this.display.input.focus();},
8147 + CodeMirror.prototype = {
8148 + constructor: CodeMirror,
8149 + focus: function(){window.focus(); this.display.input.focus();},
8232 8150
8233 - setOption: function(option, value) {
8234 - var options = this.options, old = options[option];
8235 - if (options[option] == value && option != "mode") { return }
8236 - options[option] = value;
8237 - if (optionHandlers.hasOwnProperty(option))
8238 - { operation(this, optionHandlers[option])(this, value, old); }
8239 - signal(this, "optionChange", this, option);
8240 - },
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 + },
8241 8159
8242 - getOption: function(option) {return this.options[option]},
8243 - getDoc: function() {return this.doc},
8160 + getOption: function(option) {return this.options[option]},
8161 + getDoc: function() {return this.doc},
8244 8162
8245 - addKeyMap: function(map, bottom) {
8246 - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
8247 - },
8248 - removeKeyMap: function(map) {
8249 - var maps = this.state.keyMaps;
8250 - for (var i = 0; i < maps.length; ++i)
8251 - { if (maps[i] == map || maps[i].name == map) {
8252 - maps.splice(i, 1);
8253 - return true
8254 - } }
8255 - },
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 + },
8256 8174
8257 - addOverlay: methodOp(function(spec, options) {
8258 - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
8259 - if (mode.startState) { throw new Error("Overlays may not be stateful.") }
8260 - insertSorted(this.state.overlays,
8261 - {mode: mode, modeSpec: spec, opaque: options && options.opaque,
8262 - priority: (options && options.priority) || 0},
8263 - function (overlay) { return overlay.priority; });
8264 - this.state.modeGen++;
8265 - regChange(this);
8266 - }),
8267 - removeOverlay: methodOp(function(spec) {
8268 - var overlays = this.state.overlays;
8269 - for (var i = 0; i < overlays.length; ++i) {
8270 - var cur = overlays[i].modeSpec;
8271 - if (cur == spec || typeof spec == "string" && cur.name == spec) {
8272 - overlays.splice(i, 1);
8273 - this.state.modeGen++;
8274 - regChange(this);
8275 - return
8276 - }
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
8277 8196 }
8278 - }),
8197 + }
8198 + }),
8279 8199
8280 - indentLine: methodOp(function(n, dir, aggressive) {
8281 - if (typeof dir != "string" && typeof dir != "number") {
8282 - if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
8283 - else { dir = dir ? "add" : "subtract"; }
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); }
8284 8226 }
8285 - if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
8286 - }),
8287 - indentSelection: methodOp(function(how) {
8288 - var ranges = this.doc.sel.ranges, end = -1;
8289 - for (var i = 0; i < ranges.length; i++) {
8290 - var range = ranges[i];
8291 - if (!range.empty()) {
8292 - var from = range.from(), to = range.to();
8293 - var start = Math.max(end, from.line);
8294 - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
8295 - for (var j = start; j < end; ++j)
8296 - { indentLine(this, j, how); }
8297 - var newRanges = this.doc.sel.ranges;
8298 - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
8299 - { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
8300 - } else if (range.head.line > end) {
8301 - indentLine(this, range.head.line, how, true);
8302 - end = range.head.line;
8303 - if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
8304 - }
8305 - }
8306 - }),
8227 + }
8228 + }),
8307 8229
8308 - // Fetch the parser token for a given character. Useful for hacks
8309 - // that want to inspect the mode state (say, for completion).
8310 - getTokenAt: function(pos, precise) {
8311 - return takeToken(this, pos, precise)
8312 - },
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 + },
8313 8235
8314 - getLineTokens: function(line, precise) {
8315 - return takeToken(this, Pos(line), precise, true)
8316 - },
8236 + getLineTokens: function(line, precise) {
8237 + return takeToken(this, Pos(line), precise, true)
8238 + },
8317 8239
8318 - getTokenTypeAt: function(pos) {
8319 - pos = clipPos(this.doc, pos);
8320 - var styles = getLineStyles(this, getLine(this.doc, pos.line));
8321 - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
8322 - var type;
8323 - if (ch == 0) { type = styles[2]; }
8324 - else { for (;;) {
8325 - var mid = (before + after) >> 1;
8326 - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
8327 - else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
8328 - else { type = styles[mid * 2 + 2]; break }
8329 - } }
8330 - var cut = type ? type.indexOf("overlay ") : -1;
8331 - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
8332 - },
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 + },
8333 8255
8334 - getModeAt: function(pos) {
8335 - var mode = this.doc.mode;
8336 - if (!mode.innerMode) { return mode }
8337 - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
8338 - },
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 + },
8339 8261
8340 - getHelper: function(pos, type) {
8341 - return this.getHelpers(pos, type)[0]
8342 - },
8262 + getHelper: function(pos, type) {
8263 + return this.getHelpers(pos, type)[0]
8264 + },
8343 8265
8344 - getHelpers: function(pos, type) {
8345 - var found = [];
8346 - if (!helpers.hasOwnProperty(type)) { return found }
8347 - var help = helpers[type], mode = this.getModeAt(pos);
8348 - if (typeof mode[type] == "string") {
8349 - if (help[mode[type]]) { found.push(help[mode[type]]); }
8350 - } else if (mode[type]) {
8351 - for (var i = 0; i < mode[type].length; i++) {
8352 - var val = help[mode[type][i]];
8353 - if (val) { found.push(val); }
8354 - }
8355 - } else if (mode.helperType && help[mode.helperType]) {
8356 - found.push(help[mode.helperType]);
8357 - } else if (help[mode.name]) {
8358 - found.push(help[mode.name]);
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); }
8359 8278 }
8360 - for (var i$1 = 0; i$1 < help._global.length; i$1++) {
8361 - var cur = help._global[i$1];
8362 - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
8363 - { found.push(cur.val); }
8364 - }
8365 - return found
8366 - },
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 + },
8367 8291
8368 - getStateAfter: function(line, precise) {
8369 - var doc = this.doc;
8370 - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
8371 - return getContextBefore(this, line + 1, precise).state
8372 - },
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 + },
8373 8297
8374 - cursorCoords: function(start, mode) {
8375 - var pos, range = this.doc.sel.primary();
8376 - if (start == null) { pos = range.head; }
8377 - else if (typeof start == "object") { pos = clipPos(this.doc, start); }
8378 - else { pos = start ? range.from() : range.to(); }
8379 - return cursorCoords(this, pos, mode || "page")
8380 - },
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 + },
8381 8305
8382 - charCoords: function(pos, mode) {
8383 - return charCoords(this, clipPos(this.doc, pos), mode || "page")
8384 - },
8306 + charCoords: function(pos, mode) {
8307 + return charCoords(this, clipPos(this.doc, pos), mode || "page")
8308 + },
8385 8309
8386 - coordsChar: function(coords, mode) {
8387 - coords = fromCoordSystem(this, coords, mode || "page");
8388 - return coordsChar(this, coords.left, coords.top)
8389 - },
8310 + coordsChar: function(coords, mode) {
8311 + coords = fromCoordSystem(this, coords, mode || "page");
8312 + return coordsChar(this, coords.left, coords.top)
8313 + },
8390 8314
8391 - lineAtHeight: function(height, mode) {
8392 - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
8393 - return lineAtHeight(this.doc, height + this.display.viewOffset)
8394 - },
8395 - heightAtLine: function(line, mode, includeWidgets) {
8396 - var end = false, lineObj;
8397 - if (typeof line == "number") {
8398 - var last = this.doc.first + this.doc.size - 1;
8399 - if (line < this.doc.first) { line = this.doc.first; }
8400 - else if (line > last) { line = last; end = true; }
8401 - lineObj = getLine(this.doc, line);
8402 - } else {
8403 - lineObj = line;
8404 - }
8405 - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
8406 - (end ? this.doc.height - heightAtLine(lineObj) : 0)
8407 - },
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 + },
8408 8332
8409 - defaultTextHeight: function() { return textHeight(this.display) },
8410 - defaultCharWidth: function() { return charWidth(this.display) },
8333 + defaultTextHeight: function() { return textHeight(this.display) },
8334 + defaultCharWidth: function() { return charWidth(this.display) },
8411 8335
8412 - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8336 + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
8413 8337
8414 - addWidget: function(pos, node, scroll, vert, horiz) {
8415 - var display = this.display;
8416 - pos = cursorCoords(this, clipPos(this.doc, pos));
8417 - var top = pos.bottom, left = pos.left;
8418 - node.style.position = "absolute";
8419 - node.setAttribute("cm-ignore-events", "true");
8420 - this.display.input.setUneditable(node);
8421 - display.sizer.appendChild(node);
8422 - if (vert == "over") {
8423 - top = pos.top;
8424 - } else if (vert == "above" || vert == "near") {
8425 - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
8426 - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
8427 - // Default to positioning above (if specified and possible); otherwise default to positioning below
8428 - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
8429 - { top = pos.top - node.offsetHeight; }
8430 - else if (pos.bottom + node.offsetHeight <= vspace)
8431 - { top = pos.bottom; }
8432 - if (left + node.offsetWidth > hspace)
8433 - { left = hspace - node.offsetWidth; }
8434 - }
8435 - node.style.top = top + "px";
8436 - node.style.left = node.style.right = "";
8437 - if (horiz == "right") {
8438 - left = display.sizer.clientWidth - node.offsetWidth;
8439 - node.style.right = "0px";
8440 - } else {
8441 - if (horiz == "left") { left = 0; }
8442 - else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
8443 - node.style.left = left + "px";
8444 - }
8445 - if (scroll)
8446 - { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
8447 - },
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 + },
8448 8372
8449 - triggerOnKeyDown: methodOp(onKeyDown),
8450 - triggerOnKeyPress: methodOp(onKeyPress),
8451 - triggerOnKeyUp: onKeyUp,
8452 - triggerOnMouseDown: methodOp(onMouseDown),
8373 + triggerOnKeyDown: methodOp(onKeyDown),
8374 + triggerOnKeyPress: methodOp(onKeyPress),
8375 + triggerOnKeyUp: onKeyUp,
8376 + triggerOnMouseDown: methodOp(onMouseDown),
8453 8377
8454 - execCommand: function(cmd) {
8455 - if (commands.hasOwnProperty(cmd))
8456 - { return commands[cmd].call(null, this) }
8457 - },
8378 + execCommand: function(cmd) {
8379 + if (commands.hasOwnProperty(cmd))
8380 + { return commands[cmd].call(null, this) }
8381 + },
8458 8382
8459 - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8383 + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
8460 8384
8461 - findPosH: function(from, amount, unit, visually) {
8462 - var dir = 1;
8463 - if (amount < 0) { dir = -1; amount = -amount; }
8464 - var cur = clipPos(this.doc, from);
8465 - for (var i = 0; i < amount; ++i) {
8466 - cur = findPosH(this.doc, cur, dir, unit, visually);
8467 - if (cur.hitSide) { break }
8468 - }
8469 - return cur
8470 - },
8385 + findPosH: function(from, amount, unit, visually) {
8386 + var this$1 = this;
8471 8387
8472 - moveH: methodOp(function(dir, unit) {
8473 - var this$1 = this;
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 + },
8474 8397
8475 - this.extendSelectionsBy(function (range) {
8476 - if (this$1.display.shift || this$1.doc.extend || range.empty())
8477 - { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
8478 - else
8479 - { return dir < 0 ? range.from() : range.to() }
8480 - }, sel_move);
8481 - }),
8398 + moveH: methodOp(function(dir, unit) {
8399 + var this$1 = this;
8482 8400
8483 - deleteH: methodOp(function(dir, unit) {
8484 - var sel = this.doc.sel, doc = this.doc;
8485 - if (sel.somethingSelected())
8486 - { doc.replaceSelection("", null, "+delete"); }
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) }
8487 8404 else
8488 - { deleteNearSelection(this, function (range) {
8489 - var other = findPosH(doc, range.head, dir, unit, false);
8490 - return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
8491 - }); }
8492 - }),
8405 + { return dir < 0 ? range$$1.from() : range$$1.to() }
8406 + }, sel_move);
8407 + }),
8493 8408
8494 - findPosV: function(from, amount, unit, goalColumn) {
8495 - var dir = 1, x = goalColumn;
8496 - if (amount < 0) { dir = -1; amount = -amount; }
8497 - var cur = clipPos(this.doc, from);
8498 - for (var i = 0; i < amount; ++i) {
8499 - var coords = cursorCoords(this, cur, "div");
8500 - if (x == null) { x = coords.left; }
8501 - else { coords.left = x; }
8502 - cur = findPosV(this, coords, dir, unit);
8503 - if (cur.hitSide) { break }
8504 - }
8505 - return cur
8506 - },
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 + }),
8507 8419
8508 - moveV: methodOp(function(dir, unit) {
8509 - var this$1 = this;
8420 + findPosV: function(from, amount, unit, goalColumn) {
8421 + var this$1 = this;
8510 8422
8511 - var doc = this.doc, goals = [];
8512 - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
8513 - doc.extendSelectionsBy(function (range) {
8514 - if (collapse)
8515 - { return dir < 0 ? range.from() : range.to() }
8516 - var headPos = cursorCoords(this$1, range.head, "div");
8517 - if (range.goalColumn != null) { headPos.left = range.goalColumn; }
8518 - goals.push(headPos.left);
8519 - var pos = findPosV(this$1, headPos, dir, unit);
8520 - if (unit == "page" && range == doc.sel.primary())
8521 - { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
8522 - return pos
8523 - }, sel_move);
8524 - if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
8525 - { doc.sel.ranges[i].goalColumn = goals[i]; } }
8526 - }),
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 + },
8527 8435
8528 - // Find the word at the given position (as returned by coordsChar).
8529 - findWordAt: function(pos) {
8530 - var doc = this.doc, line = getLine(doc, pos.line).text;
8531 - var start = pos.ch, end = pos.ch;
8532 - if (line) {
8533 - var helper = this.getHelper(pos, "wordChars");
8534 - if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
8535 - var startChar = line.charAt(start);
8536 - var check = isWordChar(startChar, helper)
8537 - ? function (ch) { return isWordChar(ch, helper); }
8538 - : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
8539 - : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
8540 - while (start > 0 && check(line.charAt(start - 1))) { --start; }
8541 - while (end < line.length && check(line.charAt(end))) { ++end; }
8542 - }
8543 - return new Range(Pos(pos.line, start), Pos(pos.line, end))
8544 - },
8436 + moveV: methodOp(function(dir, unit) {
8437 + var this$1 = this;
8545 8438
8546 - toggleOverwrite: function(value) {
8547 - if (value != null && value == this.state.overwrite) { return }
8548 - if (this.state.overwrite = !this.state.overwrite)
8549 - { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
8550 - else
8551 - { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
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 + }),
8552 8455
8553 - signal(this, "overwriteToggle", this, this.state.overwrite);
8554 - },
8555 - hasFocus: function() { return this.display.input.getField() == activeElt() },
8556 - isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
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 + },
8557 8473
8558 - scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
8559 - getScrollInfo: function() {
8560 - var scroller = this.display.scroller;
8561 - return {left: scroller.scrollLeft, top: scroller.scrollTop,
8562 - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
8563 - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
8564 - clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
8565 - },
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"); }
8566 8480
8567 - scrollIntoView: methodOp(function(range, margin) {
8568 - if (range == null) {
8569 - range = {from: this.doc.sel.primary().head, to: null};
8570 - if (margin == null) { margin = this.options.cursorScrollMargin; }
8571 - } else if (typeof range == "number") {
8572 - range = {from: Pos(range, 0), to: null};
8573 - } else if (range.from == null) {
8574 - range = {from: range, to: null};
8575 - }
8576 - if (!range.to) { range.to = range.from; }
8577 - range.margin = margin || 0;
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) },
8578 8485
8579 - if (range.from.line != null) {
8580 - scrollToRange(this, range);
8581 - } else {
8582 - scrollToCoordsRange(this, range.from, range.to, range.margin);
8583 - }
8584 - }),
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 + },
8585 8494
8586 - setSize: methodOp(function(width, height) {
8587 - var this$1 = this;
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;
8588 8506
8589 - var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
8590 - if (width != null) { this.display.wrapper.style.width = interpret(width); }
8591 - if (height != null) { this.display.wrapper.style.height = interpret(height); }
8592 - if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
8593 - var lineNo = this.display.viewFrom;
8594 - this.doc.iter(lineNo, this.display.viewTo, function (line) {
8595 - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
8596 - { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
8597 - ++lineNo;
8598 - });
8599 - this.curOp.forceUpdate = true;
8600 - signal(this, "refresh", this);
8601 - }),
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 + }),
8602 8513
8603 - operation: function(f){return runInOp(this, f)},
8604 - startOperation: function(){return startOperation(this)},
8605 - endOperation: function(){return endOperation(this)},
8514 + setSize: methodOp(function(width, height) {
8515 + var this$1 = this;
8606 8516
8607 - refresh: methodOp(function() {
8608 - var oldHeight = this.display.cachedTextHeight;
8609 - regChange(this);
8610 - this.curOp.forceUpdate = true;
8611 - clearCaches(this);
8612 - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
8613 - updateGutterSpace(this.display);
8614 - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
8615 - { estimateLineHeights(this); }
8616 - signal(this, "refresh", this);
8617 - }),
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 + }),
8618 8530
8619 - swapDoc: methodOp(function(doc) {
8620 - var old = this.doc;
8621 - old.cm = null;
8622 - // Cancel the current text selection if any (#5821)
8623 - if (this.state.selectingText) { this.state.selectingText(); }
8624 - attachDoc(this, doc);
8625 - clearCaches(this);
8626 - this.display.input.reset();
8627 - scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
8628 - this.curOp.forceScroll = true;
8629 - signalLater(this, "swapDoc", this, old);
8630 - return old
8631 - }),
8531 + operation: function(f){return runInOp(this, f)},
8532 + startOperation: function(){return startOperation(this)},
8533 + endOperation: function(){return endOperation(this)},
8632 8534
8633 - phrase: function(phraseText) {
8634 - var phrases = this.options.phrases;
8635 - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
8636 - },
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 + }),
8637 8546
8638 - getInputField: function(){return this.display.input.getField()},
8639 - getWrapperElement: function(){return this.display.wrapper},
8640 - getScrollerElement: function(){return this.display.scroller},
8641 - getGutterElement: function(){return this.display.gutters}
8642 - };
8643 - eventMixin(CodeMirror);
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 + }),
8644 8558
8645 - CodeMirror.registerHelper = function(type, name, value) {
8646 - if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
8647 - helpers[type][name] = value;
8648 - };
8649 - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
8650 - CodeMirror.registerHelper(type, name, value);
8651 - helpers[type]._global.push({pred: predicate, val: value});
8652 - };
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)
8653 8594 }
8654 -
8655 - // Used for horizontal relative motion. Dir is -1 or 1 (left or
8656 - // right), unit can be "codepoint", "char", "column" (like char, but
8657 - // doesn't cross line boundaries), "word" (across next word), or
8658 - // "group" (to the start of next group of word or
8659 - // non-word-non-whitespace chars). The visually param controls
8660 - // whether, in right-to-left text, direction 1 means to move towards
8661 - // the next index in the string, or towards the character to the right
8662 - // of the current position. The resulting position will have a
8663 - // hitSide=true property if it reached the end of the document.
8664 - function findPosH(doc, pos, dir, unit, visually) {
8665 - var oldPos = pos;
8666 - var origDir = dir;
8667 - var lineObj = getLine(doc, pos.line);
8668 - var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
8669 - function findNextLine() {
8670 - var l = pos.line + lineDir;
8671 - if (l < doc.first || l >= doc.first + doc.size) { return false }
8672 - pos = new Pos(l, pos.ch, pos.sticky);
8673 - return lineObj = getLine(doc, l)
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);
8674 8601 }
8675 - function moveOnce(boundToLine) {
8676 - var next;
8677 - if (unit == "codepoint") {
8678 - var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1));
8679 - if (isNaN(ch)) { next = null; }
8680 - else { next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (ch >= 0xD800 && ch < 0xDC00 ? 2 : 1))),
8681 - -dir); }
8682 - } else if (visually) {
8683 - next = moveVisually(doc.cm, lineObj, pos, dir);
8684 - } else {
8685 - next = moveLogically(lineObj, pos, dir);
8686 - }
8687 - if (next == null) {
8688 - if (!boundToLine && findNextLine())
8689 - { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
8690 - else
8691 - { return false }
8692 - } else {
8693 - pos = next;
8694 - }
8695 - return true
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;
8696 8609 }
8610 + return true
8611 + }
8697 8612
8698 - if (unit == "char" || unit == "codepoint") {
8699 - moveOnce();
8700 - } else if (unit == "column") {
8701 - moveOnce(true);
8702 - } else if (unit == "word" || unit == "group") {
8703 - var sawType = null, group = unit == "group";
8704 - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
8705 - for (var first = true;; first = false) {
8706 - if (dir < 0 && !moveOnce(!first)) { break }
8707 - var cur = lineObj.text.charAt(pos.ch) || "\n";
8708 - var type = isWordChar(cur, helper) ? "w"
8709 - : group && cur == "\n" ? "n"
8710 - : !group || /\s/.test(cur) ? null
8711 - : "p";
8712 - if (group && !first && !type) { type = "s"; }
8713 - if (sawType && sawType != type) {
8714 - if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
8715 - break
8716 - }
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 + }
8717 8632
8718 - if (type) { sawType = type; }
8719 - if (dir > 0 && !moveOnce(!first)) { break }
8720 - }
8633 + if (type) { sawType = type; }
8634 + if (dir > 0 && !moveOnce(!first)) { break }
8721 8635 }
8722 - var result = skipAtomic(doc, pos, oldPos, origDir, true);
8723 - if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8724 - return result
8725 8636 }
8637 + var result = skipAtomic(doc, pos, oldPos, origDir, true);
8638 + if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
8639 + return result
8640 +}
8726 8641
8727 - // For relative vertical movement. Dir may be -1 or 1. Unit can be
8728 - // "page" or "line". The resulting position will have a hitSide=true
8729 - // property if it reached the end of the document.
8730 - function findPosV(cm, pos, dir, unit) {
8731 - var doc = cm.doc, x = pos.left, y;
8732 - if (unit == "page") {
8733 - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
8734 - var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
8735 - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
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;
8736 8651
8737 - } else if (unit == "line") {
8738 - y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8739 - }
8740 - var target;
8741 - for (;;) {
8742 - target = coordsChar(cm, x, y);
8743 - if (!target.outside) { break }
8744 - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
8745 - y += dir * 5;
8746 - }
8747 - return target
8652 + } else if (unit == "line") {
8653 + y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
8748 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 +}
8749 8664
8750 - // CONTENTEDITABLE INPUT STYLE
8665 +// CONTENTEDITABLE INPUT STYLE
8751 8666
8752 - var ContentEditableInput = function(cm) {
8753 - this.cm = cm;
8754 - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
8755 - this.polling = new Delayed();
8756 - this.composing = null;
8757 - this.gracePeriod = false;
8758 - this.readDOMTimeout = null;
8759 - };
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 +};
8760 8675
8761 - ContentEditableInput.prototype.init = function (display) {
8762 - var this$1 = this;
8676 +ContentEditableInput.prototype.init = function (display) {
8677 + var this$1 = this;
8763 8678
8764 - var input = this, cm = input.cm;
8765 - var div = input.div = display.lineDiv;
8766 - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
8679 + var input = this, cm = input.cm;
8680 + var div = input.div = display.lineDiv;
8681 + disableBrowserMagic(div, cm.options.spellcheck);
8767 8682
8768 - function belongsToInput(e) {
8769 - for (var t = e.target; t; t = t.parentNode) {
8770 - if (t == div) { return true }
8771 - if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
8772 - }
8773 - return false
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;
8774 8699 }
8700 + });
8775 8701
8776 - on(div, "paste", function (e) {
8777 - if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
8778 - // IE doesn't fire input events, so we schedule a read for the pasted content in this way
8779 - if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
8780 - });
8702 + on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8781 8703
8782 - on(div, "compositionstart", function (e) {
8783 - this$1.composing = {data: e.data, done: false};
8784 - });
8785 - on(div, "compositionupdate", function (e) {
8786 - if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
8787 - });
8788 - on(div, "compositionend", function (e) {
8789 - if (this$1.composing) {
8790 - if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
8791 - this$1.composing.done = true;
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 + });
8792 8723 }
8793 - });
8794 -
8795 - on(div, "touchstart", function () { return input.forceCompositionEnd(); });
8796 -
8797 - on(div, "input", function () {
8798 - if (!this$1.composing) { this$1.readFromDOMSoon(); }
8799 - });
8800 -
8801 - function onCopyCut(e) {
8802 - if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
8803 - if (cm.somethingSelected()) {
8804 - setLastCopied({lineWise: false, text: cm.getSelections()});
8805 - if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
8806 - } else if (!cm.options.lineWiseCopyCut) {
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();
8807 8732 return
8808 - } else {
8809 - var ranges = copyableRanges(cm);
8810 - setLastCopied({lineWise: true, text: ranges.text});
8811 - if (e.type == "cut") {
8812 - cm.operation(function () {
8813 - cm.setSelections(ranges.ranges, 0, sel_dontScroll);
8814 - cm.replaceSelection("", null, "cut");
8815 - });
8816 - }
8817 8733 }
8818 - if (e.clipboardData) {
8819 - e.clipboardData.clearData();
8820 - var content = lastCopied.text.join("\n");
8821 - // iOS exposes the clipboard API, but seems to discard content inserted into it
8822 - e.clipboardData.setData("Text", content);
8823 - if (e.clipboardData.getData("Text") == content) {
8824 - e.preventDefault();
8825 - return
8826 - }
8827 - }
8828 - // Old-fashioned briefly-focus-a-textarea hack
8829 - var kludge = hiddenTextarea(), te = kludge.firstChild;
8830 - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
8831 - te.value = lastCopied.text.join("\n");
8832 - var hadFocus = document.activeElement;
8833 - selectInput(te);
8834 - setTimeout(function () {
8835 - cm.display.lineSpace.removeChild(kludge);
8836 - hadFocus.focus();
8837 - if (hadFocus == div) { input.showPrimarySelection(); }
8838 - }, 50);
8839 8734 }
8840 - on(div, "copy", onCopyCut);
8841 - on(div, "cut", onCopyCut);
8842 - };
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 +};
8843 8750
8844 - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
8845 - // Label for screenreaders, accessibility
8846 - if(label) {
8847 - this.div.setAttribute('aria-label', label);
8848 - } else {
8849 - this.div.removeAttribute('aria-label');
8850 - }
8851 - };
8751 +ContentEditableInput.prototype.prepareSelection = function () {
8752 + var result = prepareSelection(this.cm, false);
8753 + result.focus = this.cm.state.focused;
8754 + return result
8755 +};
8852 8756
8853 - ContentEditableInput.prototype.prepareSelection = function () {
8854 - var result = prepareSelection(this.cm, false);
8855 - result.focus = document.activeElement == this.div;
8856 - return result
8857 - };
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 +};
8858 8762
8859 - ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
8860 - if (!info || !this.cm.display.view.length) { return }
8861 - if (info.focus || takeFocus) { this.showPrimarySelection(); }
8862 - this.showMultipleSelections(info);
8863 - };
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();
8864 8766
8865 - ContentEditableInput.prototype.getSelection = function () {
8866 - return this.cm.display.wrapper.ownerDocument.getSelection()
8867 - };
8767 + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8768 + sel.removeAllRanges();
8769 + return
8770 + }
8868 8771
8869 - ContentEditableInput.prototype.showPrimarySelection = function () {
8870 - var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
8871 - var from = prim.from(), to = prim.to();
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 }
8872 8778
8873 - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
8874 - sel.removeAllRanges();
8875 - return
8876 - }
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 + }
8877 8788
8878 - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
8879 - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
8880 - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
8881 - cmp(minPos(curAnchor, curFocus), from) == 0 &&
8882 - cmp(maxPos(curAnchor, curFocus), to) == 0)
8883 - { return }
8789 + if (!start || !end) {
8790 + sel.removeAllRanges();
8791 + return
8792 + }
8884 8793
8885 - var view = cm.display.view;
8886 - var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
8887 - {node: view[0].measure.map[2], offset: 0};
8888 - var end = to.line < cm.display.viewTo && posToDOM(cm, to);
8889 - if (!end) {
8890 - var measure = view[view.length - 1].measure;
8891 - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
8892 - end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
8893 - }
8894 -
8895 - if (!start || !end) {
8896 - sel.removeAllRanges();
8897 - return
8898 - }
8899 -
8900 - var old = sel.rangeCount && sel.getRangeAt(0), rng;
8901 - try { rng = range(start.node, start.offset, end.offset, end.node); }
8902 - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
8903 - if (rng) {
8904 - if (!gecko && cm.state.focused) {
8905 - sel.collapse(start.node, start.offset);
8906 - if (!rng.collapsed) {
8907 - sel.removeAllRanges();
8908 - sel.addRange(rng);
8909 - }
8910 - } else {
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) {
8911 8801 sel.removeAllRanges();
8912 8802 sel.addRange(rng);
8913 8803 }
8914 - if (old && sel.anchorNode == null) { sel.addRange(old); }
8915 - else if (gecko) { this.startGracePeriod(); }
8804 + } else {
8805 + sel.removeAllRanges();
8806 + sel.addRange(rng);
8916 8807 }
8917 - this.rememberSelection();
8918 - };
8808 + if (old && sel.anchorNode == null) { sel.addRange(old); }
8809 + else if (gecko) { this.startGracePeriod(); }
8810 + }
8811 + this.rememberSelection();
8812 +};
8919 8813
8920 - ContentEditableInput.prototype.startGracePeriod = function () {
8921 - var this$1 = this;
8814 +ContentEditableInput.prototype.startGracePeriod = function () {
8815 + var this$1 = this;
8922 8816
8923 - clearTimeout(this.gracePeriod);
8924 - this.gracePeriod = setTimeout(function () {
8925 - this$1.gracePeriod = false;
8926 - if (this$1.selectionChanged())
8927 - { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
8928 - }, 20);
8929 - };
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 +};
8930 8824
8931 - ContentEditableInput.prototype.showMultipleSelections = function (info) {
8932 - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
8933 - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
8934 - };
8825 +ContentEditableInput.prototype.showMultipleSelections = function (info) {
8826 + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
8827 + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
8828 +};
8935 8829
8936 - ContentEditableInput.prototype.rememberSelection = function () {
8937 - var sel = this.getSelection();
8938 - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
8939 - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
8940 - };
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 +};
8941 8835
8942 - ContentEditableInput.prototype.selectionInEditor = function () {
8943 - var sel = this.getSelection();
8944 - if (!sel.rangeCount) { return false }
8945 - var node = sel.getRangeAt(0).commonAncestorContainer;
8946 - return contains(this.div, node)
8947 - };
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 +};
8948 8842
8949 - ContentEditableInput.prototype.focus = function () {
8950 - if (this.cm.options.readOnly != "nocursor") {
8951 - if (!this.selectionInEditor() || document.activeElement != this.div)
8952 - { this.showSelection(this.prepareSelection(), true); }
8953 - this.div.focus();
8954 - }
8955 - };
8956 - ContentEditableInput.prototype.blur = function () { this.div.blur(); };
8957 - ContentEditableInput.prototype.getField = function () { return this.div };
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 };
8958 8852
8959 - ContentEditableInput.prototype.supportsTouch = function () { return true };
8853 +ContentEditableInput.prototype.supportsTouch = function () { return true };
8960 8854
8961 - ContentEditableInput.prototype.receivedFocus = function () {
8962 - var input = this;
8963 - if (this.selectionInEditor())
8964 - { this.pollSelection(); }
8965 - else
8966 - { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
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; }); }
8967 8861
8968 - function poll() {
8969 - if (input.cm.state.focused) {
8970 - input.pollSelection();
8971 - input.polling.set(input.cm.options.pollInterval, poll);
8972 - }
8862 + function poll() {
8863 + if (input.cm.state.focused) {
8864 + input.pollSelection();
8865 + input.polling.set(input.cm.options.pollInterval, poll);
8973 8866 }
8974 - this.polling.set(this.cm.options.pollInterval, poll);
8975 - };
8867 + }
8868 + this.polling.set(this.cm.options.pollInterval, poll);
8869 +};
8976 8870
8977 - ContentEditableInput.prototype.selectionChanged = function () {
8978 - var sel = this.getSelection();
8979 - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
8980 - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
8981 - };
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 +};
8982 8876
8983 - ContentEditableInput.prototype.pollSelection = function () {
8984 - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
8985 - var sel = this.getSelection(), cm = this.cm;
8986 - // On Android Chrome (version 56, at least), backspacing into an
8987 - // uneditable block element will put the cursor in that element,
8988 - // and then, because it's not editable, hide the virtual keyboard.
8989 - // Because Android doesn't allow us to actually detect backspace
8990 - // presses in a sane way, this code checks for when that happens
8991 - // and simulates a backspace press in this case.
8992 - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
8993 - this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
8994 - this.blur();
8995 - this.focus();
8996 - return
8997 - }
8998 - if (this.composing) { return }
8999 - this.rememberSelection();
9000 - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
9001 - var head = domToPos(cm, sel.focusNode, sel.focusOffset);
9002 - if (anchor && head) { runInOp(cm, function () {
9003 - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
9004 - if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
9005 - }); }
9006 - };
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 +};
9007 8901
9008 - ContentEditableInput.prototype.pollContent = function () {
9009 - if (this.readDOMTimeout != null) {
9010 - clearTimeout(this.readDOMTimeout);
9011 - this.readDOMTimeout = null;
9012 - }
8902 +ContentEditableInput.prototype.pollContent = function () {
8903 + if (this.readDOMTimeout != null) {
8904 + clearTimeout(this.readDOMTimeout);
8905 + this.readDOMTimeout = null;
8906 + }
9013 8907
9014 - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
9015 - var from = sel.from(), to = sel.to();
9016 - if (from.ch == 0 && from.line > cm.firstLine())
9017 - { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
9018 - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
9019 - { to = Pos(to.line + 1, 0); }
9020 - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
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 }
9021 8915
9022 - var fromIndex, fromLine, fromNode;
9023 - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
9024 - fromLine = lineNo(display.view[0].line);
9025 - fromNode = display.view[0].node;
9026 - } else {
9027 - fromLine = lineNo(display.view[fromIndex].line);
9028 - fromNode = display.view[fromIndex - 1].node.nextSibling;
9029 - }
9030 - var toIndex = findViewIndex(cm, to.line);
9031 - var toLine, toNode;
9032 - if (toIndex == display.view.length - 1) {
9033 - toLine = display.viewTo - 1;
9034 - toNode = display.lineDiv.lastChild;
9035 - } else {
9036 - toLine = lineNo(display.view[toIndex + 1].line) - 1;
9037 - toNode = display.view[toIndex + 1].node.previousSibling;
9038 - }
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 + }
9039 8933
9040 - if (!fromNode) { return false }
9041 - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
9042 - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
9043 - while (newText.length > 1 && oldText.length > 1) {
9044 - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
9045 - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
9046 - else { break }
9047 - }
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 + }
9048 8942
9049 - var cutFront = 0, cutEnd = 0;
9050 - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
9051 - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
9052 - { ++cutFront; }
9053 - var newBot = lst(newText), oldBot = lst(oldText);
9054 - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
9055 - oldBot.length - (oldText.length == 1 ? cutFront : 0));
9056 - while (cutEnd < maxCutEnd &&
9057 - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
9058 - { ++cutEnd; }
9059 - // Try to move start of change to start of selection if ambiguous
9060 - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
9061 - while (cutFront && cutFront > from.ch &&
9062 - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
9063 - cutFront--;
9064 - cutEnd++;
9065 - }
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++;
9066 8959 }
8960 + }
9067 8961
9068 - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
9069 - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
8962 + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
8963 + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
9070 8964
9071 - var chFrom = Pos(fromLine, cutFront);
9072 - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
9073 - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
9074 - replaceRange(cm.doc, newText, chFrom, chTo, "+input");
9075 - return true
9076 - }
9077 - };
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 +};
9078 8972
9079 - ContentEditableInput.prototype.ensurePolled = function () {
9080 - this.forceCompositionEnd();
9081 - };
9082 - ContentEditableInput.prototype.reset = function () {
9083 - this.forceCompositionEnd();
9084 - };
9085 - ContentEditableInput.prototype.forceCompositionEnd = function () {
9086 - if (!this.composing) { return }
9087 - clearTimeout(this.readDOMTimeout);
9088 - this.composing = null;
9089 - this.updateFromDOM();
9090 - this.div.blur();
9091 - this.div.focus();
9092 - };
9093 - ContentEditableInput.prototype.readFromDOMSoon = function () {
9094 - var this$1 = this;
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;
9095 8989
9096 - if (this.readDOMTimeout != null) { return }
9097 - this.readDOMTimeout = setTimeout(function () {
9098 - this$1.readDOMTimeout = null;
9099 - if (this$1.composing) {
9100 - if (this$1.composing.done) { this$1.composing = null; }
9101 - else { return }
9102 - }
9103 - this$1.updateFromDOM();
9104 - }, 80);
9105 - };
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 +};
9106 9000
9107 - ContentEditableInput.prototype.updateFromDOM = function () {
9108 - var this$1 = this;
9001 +ContentEditableInput.prototype.updateFromDOM = function () {
9002 + var this$1 = this;
9109 9003
9110 - if (this.cm.isReadOnly() || !this.pollContent())
9111 - { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
9112 - };
9004 + if (this.cm.isReadOnly() || !this.pollContent())
9005 + { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
9006 +};
9113 9007
9114 - ContentEditableInput.prototype.setUneditable = function (node) {
9115 - node.contentEditable = "false";
9116 - };
9008 +ContentEditableInput.prototype.setUneditable = function (node) {
9009 + node.contentEditable = "false";
9010 +};
9117 9011
9118 - ContentEditableInput.prototype.onKeyPress = function (e) {
9119 - if (e.charCode == 0 || this.composing) { return }
9120 - e.preventDefault();
9121 - if (!this.cm.isReadOnly())
9122 - { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
9123 - };
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 +};
9124 9018
9125 - ContentEditableInput.prototype.readOnlyChanged = function (val) {
9126 - this.div.contentEditable = String(val != "nocursor");
9127 - };
9019 +ContentEditableInput.prototype.readOnlyChanged = function (val) {
9020 + this.div.contentEditable = String(val != "nocursor");
9021 +};
9128 9022
9129 - ContentEditableInput.prototype.onContextMenu = function () {};
9130 - ContentEditableInput.prototype.resetPosition = function () {};
9023 +ContentEditableInput.prototype.onContextMenu = function () {};
9024 +ContentEditableInput.prototype.resetPosition = function () {};
9131 9025
9132 - ContentEditableInput.prototype.needsContentAttribute = true;
9026 +ContentEditableInput.prototype.needsContentAttribute = true;
9133 9027
9134 - function posToDOM(cm, pos) {
9135 - var view = findViewForLine(cm, pos.line);
9136 - if (!view || view.hidden) { return null }
9137 - var line = getLine(cm.doc, pos.line);
9138 - var info = mapFromLineView(view, line, pos.line);
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);
9139 9033
9140 - var order = getOrder(line, cm.doc.direction), side = "left";
9141 - if (order) {
9142 - var partPos = getBidiPartAt(order, pos.ch);
9143 - side = partPos % 2 ? "right" : "left";
9144 - }
9145 - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9146 - result.offset = result.collapse == "right" ? result.end : result.start;
9147 - return result
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";
9148 9038 }
9039 + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
9040 + result.offset = result.collapse == "right" ? result.end : result.start;
9041 + return result
9042 +}
9149 9043
9150 - function isInGutter(node) {
9151 - for (var scan = node; scan; scan = scan.parentNode)
9152 - { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
9153 - return false
9154 - }
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 +}
9155 9049
9156 - function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9050 +function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
9157 9051
9158 - function domTextBetween(cm, from, to, fromLine, toLine) {
9159 - var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
9160 - function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
9161 - function close() {
9162 - if (closing) {
9163 - text += lineSep;
9164 - if (extraLinebreak) { text += lineSep; }
9165 - closing = extraLinebreak = false;
9166 - }
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;
9167 9059 }
9168 - function addText(str) {
9169 - if (str) {
9170 - close();
9171 - text += str;
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
9172 9073 }
9173 - }
9174 - function walk(node) {
9175 - if (node.nodeType == 1) {
9176 - var cmText = node.getAttribute("cm-text");
9177 - if (cmText) {
9178 - addText(cmText);
9179 - return
9180 - }
9181 - var markerID = node.getAttribute("cm-marker"), range;
9182 - if (markerID) {
9183 - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
9184 - if (found.length && (range = found[0].find(0)))
9185 - { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
9186 - return
9187 - }
9188 - if (node.getAttribute("contenteditable") == "false") { return }
9189 - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
9190 - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
9191 -
9192 - if (isBlock) { close(); }
9193 - for (var i = 0; i < node.childNodes.length; i++)
9194 - { walk(node.childNodes[i]); }
9195 -
9196 - if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
9197 - if (isBlock) { closing = true; }
9198 - } else if (node.nodeType == 3) {
9199 - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
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
9200 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);
9201 9089 }
9202 - for (;;) {
9203 - walk(from);
9204 - if (from == to) { break }
9205 - from = from.nextSibling;
9206 - extraLinebreak = false;
9207 - }
9208 - return text
9209 9090 }
9091 + for (;;) {
9092 + walk(from);
9093 + if (from == to) { break }
9094 + from = from.nextSibling;
9095 + }
9096 + return text
9097 +}
9210 9098
9211 - function domToPos(cm, node, offset) {
9212 - var lineNode;
9213 - if (node == cm.display.lineDiv) {
9214 - lineNode = cm.display.lineDiv.childNodes[offset];
9215 - if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
9216 - node = null; offset = 0;
9217 - } else {
9218 - for (lineNode = node;; lineNode = lineNode.parentNode) {
9219 - if (!lineNode || lineNode == cm.display.lineDiv) { return null }
9220 - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
9221 - }
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 }
9222 9109 }
9223 - for (var i = 0; i < cm.display.view.length; i++) {
9224 - var lineView = cm.display.view[i];
9225 - if (lineView.node == lineNode)
9226 - { return locateNodeInLineView(lineView, node, offset) }
9227 - }
9228 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 +}
9229 9117
9230 - function locateNodeInLineView(lineView, node, offset) {
9231 - var wrapper = lineView.text.firstChild, bad = false;
9232 - if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
9233 - if (node == wrapper) {
9234 - bad = true;
9235 - node = wrapper.childNodes[offset];
9236 - offset = 0;
9237 - if (!node) {
9238 - var line = lineView.rest ? lst(lineView.rest) : lineView.line;
9239 - return badPos(Pos(lineNo(line), line.text.length), bad)
9240 - }
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)
9241 9128 }
9129 + }
9242 9130
9243 - var textNode = node.nodeType == 3 ? node : null, topNode = node;
9244 - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
9245 - textNode = node.firstChild;
9246 - if (offset) { offset = textNode.nodeValue.length; }
9247 - }
9248 - while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
9249 - var measure = lineView.measure, maps = measure.maps;
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;
9250 9138
9251 - function find(textNode, topNode, offset) {
9252 - for (var i = -1; i < (maps ? maps.length : 0); i++) {
9253 - var map = i < 0 ? measure.map : maps[i];
9254 - for (var j = 0; j < map.length; j += 3) {
9255 - var curNode = map[j + 2];
9256 - if (curNode == textNode || curNode == topNode) {
9257 - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
9258 - var ch = map[j] + offset;
9259 - if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
9260 - return Pos(line, ch)
9261 - }
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)
9262 9149 }
9263 9150 }
9264 9151 }
9265 - var found = find(textNode, topNode, offset);
9266 - if (found) { return badPos(found, bad) }
9152 + }
9153 + var found = find(textNode, topNode, offset);
9154 + if (found) { return badPos(found, bad) }
9267 9155
9268 - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
9269 - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
9270 - found = find(after, after.firstChild, 0);
9271 - if (found)
9272 - { return badPos(Pos(found.line, found.ch - dist), bad) }
9273 - else
9274 - { dist += after.textContent.length; }
9275 - }
9276 - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
9277 - found = find(before, before.firstChild, -1);
9278 - if (found)
9279 - { return badPos(Pos(found.line, found.ch + dist$1), bad) }
9280 - else
9281 - { dist$1 += before.textContent.length; }
9282 - }
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; }
9283 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 +}
9284 9172
9285 - // TEXTAREA INPUT STYLE
9173 +// TEXTAREA INPUT STYLE
9286 9174
9287 - var TextareaInput = function(cm) {
9288 - this.cm = cm;
9289 - // See input.poll and input.reset
9290 - this.prevInput = "";
9175 +var TextareaInput = function(cm) {
9176 + this.cm = cm;
9177 + // See input.poll and input.reset
9178 + this.prevInput = "";
9291 9179
9292 - // Flag that indicates whether we expect input to appear real soon
9293 - // now (after some event like 'keypress' or 'input') and are
9294 - // polling intensively.
9295 - this.pollingFast = false;
9296 - // Self-resetting timeout for the poller
9297 - this.polling = new Delayed();
9298 - // Used to work around IE issue with selection being forgotten when focus moves away from textarea
9299 - this.hasSelection = false;
9300 - this.composing = null;
9301 - };
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 +};
9302 9190
9303 - TextareaInput.prototype.init = function (display) {
9304 - var this$1 = this;
9191 +TextareaInput.prototype.init = function (display) {
9192 + var this$1 = this;
9305 9193
9306 - var input = this, cm = this.cm;
9307 - this.createField(display);
9308 - var te = this.textarea;
9194 + var input = this, cm = this.cm;
9309 9195
9310 - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
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);
9311 9202
9312 - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
9313 - if (ios) { te.style.width = "0px"; }
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"; }
9314 9205
9315 - on(te, "input", function () {
9316 - if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9317 - input.poll();
9318 - });
9206 + on(te, "input", function () {
9207 + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
9208 + input.poll();
9209 + });
9319 9210
9320 - on(te, "paste", function (e) {
9321 - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9211 + on(te, "paste", function (e) {
9212 + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
9322 9213
9323 - cm.state.pasteIncoming = +new Date;
9324 - input.fastPoll();
9325 - });
9214 + cm.state.pasteIncoming = true;
9215 + input.fastPoll();
9216 + });
9326 9217
9327 - function prepareCopyCut(e) {
9328 - if (signalDOMEvent(cm, e)) { return }
9329 - if (cm.somethingSelected()) {
9330 - setLastCopied({lineWise: false, text: cm.getSelections()});
9331 - } else if (!cm.options.lineWiseCopyCut) {
9332 - return
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);
9333 9229 } else {
9334 - var ranges = copyableRanges(cm);
9335 - setLastCopied({lineWise: true, text: ranges.text});
9336 - if (e.type == "cut") {
9337 - cm.setSelections(ranges.ranges, null, sel_dontScroll);
9338 - } else {
9339 - input.prevInput = "";
9340 - te.value = ranges.text.join("\n");
9341 - selectInput(te);
9342 - }
9230 + input.prevInput = "";
9231 + te.value = ranges.text.join("\n");
9232 + selectInput(te);
9343 9233 }
9344 - if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
9345 9234 }
9346 - on(te, "cut", prepareCopyCut);
9347 - on(te, "copy", prepareCopyCut);
9235 + if (e.type == "cut") { cm.state.cutIncoming = true; }
9236 + }
9237 + on(te, "cut", prepareCopyCut);
9238 + on(te, "copy", prepareCopyCut);
9348 9239
9349 - on(display.scroller, "paste", function (e) {
9350 - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
9351 - if (!te.dispatchEvent) {
9352 - cm.state.pasteIncoming = +new Date;
9353 - input.focus();
9354 - return
9355 - }
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 + });
9356 9245
9357 - // Pass the `paste` event to the textarea so it's handled by its event listener.
9358 - var event = new Event("paste");
9359 - event.clipboardData = e.clipboardData;
9360 - te.dispatchEvent(event);
9361 - });
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 + });
9362 9250
9363 - // Prevent normal selection in the editor (we handle our own)
9364 - on(display.lineSpace, "selectstart", function (e) {
9365 - if (!eventInWidget(display, e)) { e_preventDefault(e); }
9366 - });
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 +};
9367 9267
9368 - on(te, "compositionstart", function () {
9369 - var start = cm.getCursor("from");
9370 - if (input.composing) { input.composing.range.clear(); }
9371 - input.composing = {
9372 - start: start,
9373 - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
9374 - };
9375 - });
9376 - on(te, "compositionend", function () {
9377 - if (input.composing) {
9378 - input.poll();
9379 - input.composing.range.clear();
9380 - input.composing = null;
9381 - }
9382 - });
9383 - };
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);
9384 9272
9385 - TextareaInput.prototype.createField = function (_display) {
9386 - // Wraps and hides input textarea
9387 - this.wrapper = hiddenTextarea();
9388 - // The semihidden textarea that is focused when the editor is
9389 - // focused, and receives input.
9390 - this.textarea = this.wrapper.firstChild;
9391 - };
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 + }
9392 9282
9393 - TextareaInput.prototype.screenReaderLabelChanged = function (label) {
9394 - // Label for screenreaders, accessibility
9395 - if(label) {
9396 - this.textarea.setAttribute('aria-label', label);
9397 - } else {
9398 - this.textarea.removeAttribute('aria-label');
9399 - }
9400 - };
9283 + return result
9284 +};
9401 9285
9402 - TextareaInput.prototype.prepareSelection = function () {
9403 - // Redraw the selection and/or cursor
9404 - var cm = this.cm, display = cm.display, doc = cm.doc;
9405 - var result = prepareSelection(cm);
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 +};
9406 9295
9407 - // Move the hidden textarea near the cursor to prevent scrolling artifacts
9408 - if (cm.options.moveInputWithCursor) {
9409 - var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
9410 - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
9411 - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
9412 - headPos.top + lineOff.top - wrapOff.top));
9413 - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
9414 - headPos.left + lineOff.left - wrapOff.left));
9415 - }
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 +};
9416 9312
9417 - return result
9418 - };
9313 +TextareaInput.prototype.getField = function () { return this.textarea };
9419 9314
9420 - TextareaInput.prototype.showSelection = function (drawn) {
9421 - var cm = this.cm, display = cm.display;
9422 - removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
9423 - removeChildrenAndAdd(display.selectionDiv, drawn.selection);
9424 - if (drawn.teTop != null) {
9425 - this.wrapper.style.top = drawn.teTop + "px";
9426 - this.wrapper.style.left = drawn.teLeft + "px";
9427 - }
9428 - };
9315 +TextareaInput.prototype.supportsTouch = function () { return false };
9429 9316
9430 - // Reset the input to correspond to the selection (or to be empty,
9431 - // when not typing and nothing is selected)
9432 - TextareaInput.prototype.reset = function (typing) {
9433 - if (this.contextMenuPending || this.composing) { return }
9434 - var cm = this.cm;
9435 - if (cm.somethingSelected()) {
9436 - this.prevInput = "";
9437 - var content = cm.getSelection();
9438 - this.textarea.value = content;
9439 - if (cm.state.focused) { selectInput(this.textarea); }
9440 - if (ie && ie_version >= 9) { this.hasSelection = content; }
9441 - } else if (!typing) {
9442 - this.prevInput = this.textarea.value = "";
9443 - if (ie && ie_version >= 9) { this.hasSelection = null; }
9444 - }
9445 - };
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 +};
9446 9323
9447 - TextareaInput.prototype.getField = function () { return this.textarea };
9324 +TextareaInput.prototype.blur = function () { this.textarea.blur(); };
9448 9325
9449 - TextareaInput.prototype.supportsTouch = function () { return false };
9326 +TextareaInput.prototype.resetPosition = function () {
9327 + this.wrapper.style.top = this.wrapper.style.left = 0;
9328 +};
9450 9329
9451 - TextareaInput.prototype.focus = function () {
9452 - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
9453 - try { this.textarea.focus(); }
9454 - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
9455 - }
9456 - };
9330 +TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
9457 9331
9458 - TextareaInput.prototype.blur = function () { this.textarea.blur(); };
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;
9459 9336
9460 - TextareaInput.prototype.resetPosition = function () {
9461 - this.wrapper.style.top = this.wrapper.style.left = 0;
9462 - };
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 +};
9463 9343
9464 - TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
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 +};
9465 9357
9466 - // Poll for input changes, using the normal rate of polling. This
9467 - // runs as long as the editor is focused.
9468 - TextareaInput.prototype.slowPoll = function () {
9469 - var this$1 = this;
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;
9470 9366
9471 - if (this.pollingFast) { return }
9472 - this.polling.set(this.cm.options.pollInterval, function () {
9473 - this$1.poll();
9474 - if (this$1.cm.state.focused) { this$1.slowPoll(); }
9475 - });
9476 - };
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 }
9477 9376
9478 - // When an event has just come in that is likely to add or change
9479 - // something in the input textarea, we poll faster, to ensure that
9480 - // the change appears on the screen quickly.
9481 - TextareaInput.prototype.fastPoll = function () {
9482 - var missed = false, input = this;
9483 - input.pollingFast = true;
9484 - function p() {
9485 - var changed = input.poll();
9486 - if (!changed && !missed) {missed = true; input.polling.set(60, p);}
9487 - else {input.pollingFast = false; input.slowPoll();}
9488 - }
9489 - input.polling.set(20, p);
9490 - };
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 + }
9491 9388
9492 - // Read input from the textarea, and update the document to match.
9493 - // When something is selected, it is present in the textarea, and
9494 - // selected (unless it is huge, in which case a placeholder is
9495 - // used). When nothing is selected, the cursor sits after previously
9496 - // seen text (can be empty), which is stored in prevInput (we must
9497 - // not reset the textarea when typing, because that breaks IME).
9498 - TextareaInput.prototype.poll = function () {
9499 - var this$1 = this;
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; }
9500 9397
9501 - var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
9502 - // Since this is called a *lot*, try to bail out as cheaply as
9503 - // possible when it is clear that nothing happened. hasSelection
9504 - // will be the case when there is a lot of text in the textarea,
9505 - // in which case reading its value would be expensive.
9506 - if (this.contextMenuPending || !cm.state.focused ||
9507 - (hasSelection(input) && !prevInput && !this.composing) ||
9508 - cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
9509 - { return false }
9398 + runInOp(cm, function () {
9399 + applyTextInput(cm, text.slice(same), prevInput.length - same,
9400 + null, this$1.composing ? "*compose" : null);
9510 9401
9511 - var text = input.value;
9512 - // If nothing changed, bail.
9513 - if (text == prevInput && !cm.somethingSelected()) { return false }
9514 - // Work around nonsensical selection resetting in IE9/10, and
9515 - // inexplicable appearance of private area unicode characters on
9516 - // some key combos in Mac (#2689).
9517 - if (ie && ie_version >= 9 && this.hasSelection === text ||
9518 - mac && /[\uf700-\uf7ff]/.test(text)) {
9519 - cm.display.input.reset();
9520 - return false
9521 - }
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; }
9522 9405
9523 - if (cm.doc.sel == cm.display.selForContextMenu) {
9524 - var first = text.charCodeAt(0);
9525 - if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
9526 - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
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"});
9527 9410 }
9528 - // Find the part of the input that is actually new
9529 - var same = 0, l = Math.min(prevInput.length, text.length);
9530 - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
9411 + });
9412 + return true
9413 +};
9531 9414
9532 - runInOp(cm, function () {
9533 - applyTextInput(cm, text.slice(same), prevInput.length - same,
9534 - null, this$1.composing ? "*compose" : null);
9415 +TextareaInput.prototype.ensurePolled = function () {
9416 + if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9417 +};
9535 9418
9536 - // Don't leave long text in the textarea, since it makes further polling slow
9537 - if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
9538 - else { this$1.prevInput = text; }
9419 +TextareaInput.prototype.onKeyPress = function () {
9420 + if (ie && ie_version >= 9) { this.hasSelection = null; }
9421 + this.fastPoll();
9422 +};
9539 9423
9540 - if (this$1.composing) {
9541 - this$1.composing.range.clear();
9542 - this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
9543 - {className: "CodeMirror-composing"});
9544 - }
9545 - });
9546 - return true
9547 - };
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.
9548 9428
9549 - TextareaInput.prototype.ensurePolled = function () {
9550 - if (this.pollingFast && this.poll()) { this.pollingFast = false; }
9551 - };
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); }
9552 9434
9553 - TextareaInput.prototype.onKeyPress = function () {
9554 - if (ie && ie_version >= 9) { this.hasSelection = null; }
9555 - this.fastPoll();
9556 - };
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);
9557 9449
9558 - TextareaInput.prototype.onContextMenu = function (e) {
9559 - var input = this, cm = input.cm, display = cm.display, te = input.textarea;
9560 - if (input.contextMenuPending) { input.contextMenuPending(); }
9561 - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
9562 - if (!pos || presto) { return } // Opera is difficult.
9563 -
9564 - // Reset the current text selection only if the click is done outside of the selection
9565 - // and 'resetSelectionOnContextMenu' option is true.
9566 - var reset = cm.options.resetSelectionOnContextMenu;
9567 - if (reset && cm.doc.sel.contains(pos) == -1)
9568 - { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
9569 -
9570 - var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
9571 - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
9572 - input.wrapper.style.cssText = "position: static";
9573 - 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);";
9574 - var oldScrollY;
9575 - if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
9576 - display.input.focus();
9577 - if (webkit) { window.scrollTo(null, oldScrollY); }
9578 - display.input.reset();
9579 - // Adds "Select all" to context menu in FF
9580 - if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
9581 - input.contextMenuPending = rehide;
9582 - display.selForContextMenu = cm.doc.sel;
9583 - clearTimeout(display.detectingSelectAll);
9584 -
9585 - // Select-all will be greyed out if there's nothing to select, so
9586 - // this adds a zero-width space so that we can later check whether
9587 - // it got selected.
9588 - function prepareSelectAllHack() {
9589 - if (te.selectionStart != null) {
9590 - var selected = cm.somethingSelected();
9591 - var extval = "\u200b" + (selected ? te.value : "");
9592 - te.value = "\u21da"; // Used to catch context-menu undo
9593 - te.value = extval;
9594 - input.prevInput = selected ? "" : "\u200b";
9595 - te.selectionStart = 1; te.selectionEnd = extval.length;
9596 - // Re-set this, in case some other handler touched the
9597 - // selection in the meantime.
9598 - display.selForContextMenu = cm.doc.sel;
9599 - }
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;
9600 9464 }
9601 - function rehide() {
9602 - if (input.contextMenuPending != rehide) { return }
9603 - input.contextMenuPending = false;
9604 - input.wrapper.style.cssText = oldWrapperCSS;
9605 - te.style.cssText = oldCSS;
9606 - if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
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); }
9607 9471
9608 - // Try to detect the user choosing select-all
9609 - if (te.selectionStart != null) {
9610 - if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
9611 - var i = 0, poll = function () {
9612 - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
9613 - te.selectionEnd > 0 && input.prevInput == "\u200b") {
9614 - operation(cm, selectAll)(cm);
9615 - } else if (i++ < 10) {
9616 - display.detectingSelectAll = setTimeout(poll, 500);
9617 - } else {
9618 - display.selForContextMenu = null;
9619 - display.input.reset();
9620 - }
9621 - };
9622 - display.detectingSelectAll = setTimeout(poll, 200);
9623 - }
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);
9624 9487 }
9488 + }
9625 9489
9626 - if (ie && ie_version >= 9) { prepareSelectAllHack(); }
9627 - if (captureRightClick) {
9628 - e_stop(e);
9629 - var mouseup = function () {
9630 - off(window, "mouseup", mouseup);
9631 - setTimeout(rehide, 20);
9632 - };
9633 - on(window, "mouseup", mouseup);
9634 - } else {
9635 - setTimeout(rehide, 50);
9636 - }
9637 - };
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 +};
9638 9502
9639 - TextareaInput.prototype.readOnlyChanged = function (val) {
9640 - if (!val) { this.reset(); }
9641 - this.textarea.disabled = val == "nocursor";
9642 - this.textarea.readOnly = !!val;
9643 - };
9503 +TextareaInput.prototype.readOnlyChanged = function (val) {
9504 + if (!val) { this.reset(); }
9505 + this.textarea.disabled = val == "nocursor";
9506 +};
9644 9507
9645 - TextareaInput.prototype.setUneditable = function () {};
9508 +TextareaInput.prototype.setUneditable = function () {};
9646 9509
9647 - TextareaInput.prototype.needsContentAttribute = false;
9510 +TextareaInput.prototype.needsContentAttribute = false;
9648 9511
9649 - function fromTextArea(textarea, options) {
9650 - options = options ? copyObj(options) : {};
9651 - options.value = textarea.value;
9652 - if (!options.tabindex && textarea.tabIndex)
9653 - { options.tabindex = textarea.tabIndex; }
9654 - if (!options.placeholder && textarea.placeholder)
9655 - { options.placeholder = textarea.placeholder; }
9656 - // Set autofocus to true if this textarea is focused, or if it has
9657 - // autofocus and no other element is focused.
9658 - if (options.autofocus == null) {
9659 - var hasFocus = activeElt();
9660 - options.autofocus = hasFocus == textarea ||
9661 - textarea.getAttribute("autofocus") != null && hasFocus == document.body;
9662 - }
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 + }
9663 9526
9664 - function save() {textarea.value = cm.getValue();}
9527 + function save() {textarea.value = cm.getValue();}
9665 9528
9666 - var realSubmit;
9667 - if (textarea.form) {
9668 - on(textarea.form, "submit", save);
9669 - // Deplorable hack to make the submit method do the right thing.
9670 - if (!options.leaveSubmitMethodAlone) {
9671 - var form = textarea.form;
9672 - realSubmit = form.submit;
9673 - try {
9674 - var wrappedSubmit = form.submit = function () {
9675 - save();
9676 - form.submit = realSubmit;
9677 - form.submit();
9678 - form.submit = wrappedSubmit;
9679 - };
9680 - } catch(e) {}
9681 - }
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) {}
9682 9544 }
9545 + }
9683 9546
9684 - options.finishInit = function (cm) {
9685 - cm.save = save;
9686 - cm.getTextArea = function () { return textarea; };
9687 - cm.toTextArea = function () {
9688 - cm.toTextArea = isNaN; // Prevent this from being ran twice
9689 - save();
9690 - textarea.parentNode.removeChild(cm.getWrapperElement());
9691 - textarea.style.display = "";
9692 - if (textarea.form) {
9693 - off(textarea.form, "submit", save);
9694 - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
9695 - { textarea.form.submit = realSubmit; }
9696 - }
9697 - };
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 + }
9698 9560 };
9561 + };
9699 9562
9700 - textarea.style.display = "none";
9701 - var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
9702 - options);
9703 - return cm
9704 - }
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 +}
9705 9568
9706 - function addLegacyProps(CodeMirror) {
9707 - CodeMirror.off = off;
9708 - CodeMirror.on = on;
9709 - CodeMirror.wheelEventPixels = wheelEventPixels;
9710 - CodeMirror.Doc = Doc;
9711 - CodeMirror.splitLines = splitLinesAuto;
9712 - CodeMirror.countColumn = countColumn;
9713 - CodeMirror.findColumn = findColumn;
9714 - CodeMirror.isWordChar = isWordCharBasic;
9715 - CodeMirror.Pass = Pass;
9716 - CodeMirror.signal = signal;
9717 - CodeMirror.Line = Line;
9718 - CodeMirror.changeEnd = changeEnd;
9719 - CodeMirror.scrollbarModel = scrollbarModel;
9720 - CodeMirror.Pos = Pos;
9721 - CodeMirror.cmpPos = cmp;
9722 - CodeMirror.modes = modes;
9723 - CodeMirror.mimeModes = mimeModes;
9724 - CodeMirror.resolveMode = resolveMode;
9725 - CodeMirror.getMode = getMode;
9726 - CodeMirror.modeExtensions = modeExtensions;
9727 - CodeMirror.extendMode = extendMode;
9728 - CodeMirror.copyState = copyState;
9729 - CodeMirror.startState = startState;
9730 - CodeMirror.innerMode = innerMode;
9731 - CodeMirror.commands = commands;
9732 - CodeMirror.keyMap = keyMap;
9733 - CodeMirror.keyName = keyName;
9734 - CodeMirror.isModifierKey = isModifierKey;
9735 - CodeMirror.lookupKey = lookupKey;
9736 - CodeMirror.normalizeKeyMap = normalizeKeyMap;
9737 - CodeMirror.StringStream = StringStream;
9738 - CodeMirror.SharedTextMarker = SharedTextMarker;
9739 - CodeMirror.TextMarker = TextMarker;
9740 - CodeMirror.LineWidget = LineWidget;
9741 - CodeMirror.e_preventDefault = e_preventDefault;
9742 - CodeMirror.e_stopPropagation = e_stopPropagation;
9743 - CodeMirror.e_stop = e_stop;
9744 - CodeMirror.addClass = addClass;
9745 - CodeMirror.contains = contains;
9746 - CodeMirror.rmClass = rmClass;
9747 - CodeMirror.keyNames = keyNames;
9748 - }
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 +}
9749 9612
9750 - // EDITOR CONSTRUCTOR
9613 +// EDITOR CONSTRUCTOR
9751 9614
9752 - defineOptions(CodeMirror);
9615 +defineOptions(CodeMirror$1);
9753 9616
9754 - addEditorMethods(CodeMirror);
9617 +addEditorMethods(CodeMirror$1);
9755 9618
9756 - // Set up methods on CodeMirror's prototype to redirect to the editor's document.
9757 - var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
9758 - for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
9759 - { CodeMirror.prototype[prop] = (function(method) {
9760 - return function() {return method.apply(this.doc, arguments)}
9761 - })(Doc.prototype[prop]); } }
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]); } }
9762 9625
9763 - eventMixin(Doc);
9764 - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9626 +eventMixin(Doc);
9765 9627
9766 - // Extra arguments are stored as the mode's dependencies, which is
9767 - // used by (legacy) mechanisms like loadmode.js to automatically
9768 - // load a mode. (Preferred mechanism is the require/define calls.)
9769 - CodeMirror.defineMode = function(name/*, mode, …*/) {
9770 - if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
9771 - defineMode.apply(this, arguments);
9772 - };
9628 +// INPUT HANDLING
9773 9629
9774 - CodeMirror.defineMIME = defineMIME;
9630 +CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
9775 9631
9776 - // Minimal default mode.
9777 - CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9778 - CodeMirror.defineMIME("text/plain", "null");
9632 +// MODE DEFINITION AND QUERYING
9779 9633
9780 - // EXTENSIONS
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 +};
9781 9641
9782 - CodeMirror.defineExtension = function (name, func) {
9783 - CodeMirror.prototype[name] = func;
9784 - };
9785 - CodeMirror.defineDocExtension = function (name, func) {
9786 - Doc.prototype[name] = func;
9787 - };
9642 +CodeMirror$1.defineMIME = defineMIME;
9788 9643
9789 - CodeMirror.fromTextArea = fromTextArea;
9644 +// Minimal default mode.
9645 +CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
9646 +CodeMirror$1.defineMIME("text/plain", "null");
9790 9647
9791 - addLegacyProps(CodeMirror);
9648 +// EXTENSIONS
9792 9649
9793 - CodeMirror.version = "5.58.3";
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 +};
9794 9656
9795 - return CodeMirror;
9657 +CodeMirror$1.fromTextArea = fromTextArea;
9658 +
9659 +addLegacyProps(CodeMirror$1);
9660 +
9661 +CodeMirror$1.version = "5.32.0";
9662 +
9663 +return CodeMirror$1;
9796 9664
9797 9665 })));