You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9884 lines
393 KiB

2 months ago
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/LICENSE
  3. // This is CodeMirror (https://codemirror.net/5), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent;
  16. var platform = navigator.platform;
  17. var gecko = /gecko\/\d/i.test(userAgent);
  18. var ie_upto10 = /MSIE \d/.test(userAgent);
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  20. var edge = /Edge\/(\d+)/.exec(userAgent);
  21. var ie = ie_upto10 || ie_11up || edge;
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  23. var webkit = !edge && /WebKit\//.test(userAgent);
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  25. var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
  26. var chrome_version = chrome && +chrome[1];
  27. var presto = /Opera\//.test(userAgent);
  28. var safari = /Apple Computer/.test(navigator.vendor);
  29. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  30. var phantom = /PhantomJS/.test(userAgent);
  31. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  32. var android = /Android/.test(userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  35. var mac = ios || /Mac/.test(platform);
  36. var chromeOS = /\bCrOS\b/.test(userAgent);
  37. var windows = /win/i.test(platform);
  38. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  39. if (presto_version) { presto_version = Number(presto_version[1]); }
  40. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  41. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  42. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  43. var captureRightClick = gecko || (ie && ie_version >= 9);
  44. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  45. var rmClass = function(node, cls) {
  46. var current = node.className;
  47. var match = classTest(cls).exec(current);
  48. if (match) {
  49. var after = current.slice(match.index + match[0].length);
  50. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  51. }
  52. };
  53. function removeChildren(e) {
  54. for (var count = e.childNodes.length; count > 0; --count)
  55. { e.removeChild(e.firstChild); }
  56. return e
  57. }
  58. function removeChildrenAndAdd(parent, e) {
  59. return removeChildren(parent).appendChild(e)
  60. }
  61. function elt(tag, content, className, style) {
  62. var e = document.createElement(tag);
  63. if (className) { e.className = className; }
  64. if (style) { e.style.cssText = style; }
  65. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  66. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  67. return e
  68. }
  69. // wrapper for elt, which removes the elt from the accessibility tree
  70. function eltP(tag, content, className, style) {
  71. var e = elt(tag, content, className, style);
  72. e.setAttribute("role", "presentation");
  73. return e
  74. }
  75. var range;
  76. if (document.createRange) { range = function(node, start, end, endNode) {
  77. var r = document.createRange();
  78. r.setEnd(endNode || node, end);
  79. r.setStart(node, start);
  80. return r
  81. }; }
  82. else { range = function(node, start, end) {
  83. var r = document.body.createTextRange();
  84. try { r.moveToElementText(node.parentNode); }
  85. catch(e) { return r }
  86. r.collapse(true);
  87. r.moveEnd("character", end);
  88. r.moveStart("character", start);
  89. return r
  90. }; }
  91. function contains(parent, child) {
  92. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  93. { child = child.parentNode; }
  94. if (parent.contains)
  95. { return parent.contains(child) }
  96. do {
  97. if (child.nodeType == 11) { child = child.host; }
  98. if (child == parent) { return true }
  99. } while (child = child.parentNode)
  100. }
  101. function activeElt(rootNode) {
  102. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  103. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  104. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  105. var doc = rootNode.ownerDocument || rootNode;
  106. var activeElement;
  107. try {
  108. activeElement = rootNode.activeElement;
  109. } catch(e) {
  110. activeElement = doc.body || null;
  111. }
  112. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  113. { activeElement = activeElement.shadowRoot.activeElement; }
  114. return activeElement
  115. }
  116. function addClass(node, cls) {
  117. var current = node.className;
  118. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  119. }
  120. function joinClasses(a, b) {
  121. var as = a.split(" ");
  122. for (var i = 0; i < as.length; i++)
  123. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  124. return b
  125. }
  126. var selectInput = function(node) { node.select(); };
  127. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  128. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  129. else if (ie) // Suppress mysterious IE10 errors
  130. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  131. function doc(cm) { return cm.display.wrapper.ownerDocument }
  132. function root(cm) {
  133. return rootNode(cm.display.wrapper)
  134. }
  135. function rootNode(element) {
  136. // Detect modern browsers (2017+).
  137. return element.getRootNode ? element.getRootNode() : element.ownerDocument
  138. }
  139. function win(cm) { return doc(cm).defaultView }
  140. function bind(f) {
  141. var args = Array.prototype.slice.call(arguments, 1);
  142. return function(){return f.apply(null, args)}
  143. }
  144. function copyObj(obj, target, overwrite) {
  145. if (!target) { target = {}; }
  146. for (var prop in obj)
  147. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  148. { target[prop] = obj[prop]; } }
  149. return target
  150. }
  151. // Counts the column offset in a string, taking tabs into account.
  152. // Used mostly to find indentation.
  153. function countColumn(string, end, tabSize, startIndex, startValue) {
  154. if (end == null) {
  155. end = string.search(/[^\s\u00a0]/);
  156. if (end == -1) { end = string.length; }
  157. }
  158. for (var i = startIndex || 0, n = startValue || 0;;) {
  159. var nextTab = string.indexOf("\t", i);
  160. if (nextTab < 0 || nextTab >= end)
  161. { return n + (end - i) }
  162. n += nextTab - i;
  163. n += tabSize - (n % tabSize);
  164. i = nextTab + 1;
  165. }
  166. }
  167. var Delayed = function() {
  168. this.id = null;
  169. this.f = null;
  170. this.time = 0;
  171. this.handler = bind(this.onTimeout, this);
  172. };
  173. Delayed.prototype.onTimeout = function (self) {
  174. self.id = 0;
  175. if (self.time <= +new Date) {
  176. self.f();
  177. } else {
  178. setTimeout(self.handler, self.time - +new Date);
  179. }
  180. };
  181. Delayed.prototype.set = function (ms, f) {
  182. this.f = f;
  183. var time = +new Date + ms;
  184. if (!this.id || time < this.time) {
  185. clearTimeout(this.id);
  186. this.id = setTimeout(this.handler, ms);
  187. this.time = time;
  188. }
  189. };
  190. function indexOf(array, elt) {
  191. for (var i = 0; i < array.length; ++i)
  192. { if (array[i] == elt) { return i } }
  193. return -1
  194. }
  195. // Number of pixels added to scroller and sizer to hide scrollbar
  196. var scrollerGap = 50;
  197. // Returned or thrown by various protocols to signal 'I'm not
  198. // handling this'.
  199. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  200. // Reused option objects for setSelection & friends
  201. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  202. // The inverse of countColumn -- find the offset that corresponds to
  203. // a particular column.
  204. function findColumn(string, goal, tabSize) {
  205. for (var pos = 0, col = 0;;) {
  206. var nextTab = string.indexOf("\t", pos);
  207. if (nextTab == -1) { nextTab = string.length; }
  208. var skipped = nextTab - pos;
  209. if (nextTab == string.length || col + skipped >= goal)
  210. { return pos + Math.min(skipped, goal - col) }
  211. col += nextTab - pos;
  212. col += tabSize - (col % tabSize);
  213. pos = nextTab + 1;
  214. if (col >= goal) { return pos }
  215. }
  216. }
  217. var spaceStrs = [""];
  218. function spaceStr(n) {
  219. while (spaceStrs.length <= n)
  220. { spaceStrs.push(lst(spaceStrs) + " "); }
  221. return spaceStrs[n]
  222. }
  223. function lst(arr) { return arr[arr.length-1] }
  224. function map(array, f) {
  225. var out = [];
  226. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  227. return out
  228. }
  229. function insertSorted(array, value, score) {
  230. var pos = 0, priority = score(value);
  231. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  232. array.splice(pos, 0, value);
  233. }
  234. function nothing() {}
  235. function createObj(base, props) {
  236. var inst;
  237. if (Object.create) {
  238. inst = Object.create(base);
  239. } else {
  240. nothing.prototype = base;
  241. inst = new nothing();
  242. }
  243. if (props) { copyObj(props, inst); }
  244. return inst
  245. }
  246. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  247. function isWordCharBasic(ch) {
  248. return /\w/.test(ch) || ch > "\x80" &&
  249. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  250. }
  251. function isWordChar(ch, helper) {
  252. if (!helper) { return isWordCharBasic(ch) }
  253. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  254. return helper.test(ch)
  255. }
  256. function isEmpty(obj) {
  257. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  258. return true
  259. }
  260. // Extending unicode characters. A series of a non-extending char +
  261. // any number of extending chars is treated as a single unit as far
  262. // as editing and measuring is concerned. This is not fully correct,
  263. // since some scripts/fonts/browsers also treat other configurations
  264. // of code points as a group.
  265. 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]/;
  266. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  267. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  268. function skipExtendingChars(str, pos, dir) {
  269. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  270. return pos
  271. }
  272. // Returns the value from the range [`from`; `to`] that satisfies
  273. // `pred` and is closest to `from`. Assumes that at least `to`
  274. // satisfies `pred`. Supports `from` being greater than `to`.
  275. function findFirst(pred, from, to) {
  276. // At any point we are certain `to` satisfies `pred`, don't know
  277. // whether `from` does.
  278. var dir = from > to ? -1 : 1;
  279. for (;;) {
  280. if (from == to) { return from }
  281. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  282. if (mid == from) { return pred(mid) ? from : to }
  283. if (pred(mid)) { to = mid; }
  284. else { from = mid + dir; }
  285. }
  286. }
  287. // BIDI HELPERS
  288. function iterateBidiSections(order, from, to, f) {
  289. if (!order) { return f(from, to, "ltr", 0) }
  290. var found = false;
  291. for (var i = 0; i < order.length; ++i) {
  292. var part = order[i];
  293. if (part.from < to && part.to > from || from == to && part.to == from) {
  294. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  295. found = true;
  296. }
  297. }
  298. if (!found) { f(from, to, "ltr"); }
  299. }
  300. var bidiOther = null;
  301. function getBidiPartAt(order, ch, sticky) {
  302. var found;
  303. bidiOther = null;
  304. for (var i = 0; i < order.length; ++i) {
  305. var cur = order[i];
  306. if (cur.from < ch && cur.to > ch) { return i }
  307. if (cur.to == ch) {
  308. if (cur.from != cur.to && sticky == "before") { found = i; }
  309. else { bidiOther = i; }
  310. }
  311. if (cur.from == ch) {
  312. if (cur.from != cur.to && sticky != "before") { found = i; }
  313. else { bidiOther = i; }
  314. }
  315. }
  316. return found != null ? found : bidiOther
  317. }
  318. // Bidirectional ordering algorithm
  319. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  320. // that this (partially) implements.
  321. // One-char codes used for character types:
  322. // L (L): Left-to-Right
  323. // R (R): Right-to-Left
  324. // r (AL): Right-to-Left Arabic
  325. // 1 (EN): European Number
  326. // + (ES): European Number Separator
  327. // % (ET): European Number Terminator
  328. // n (AN): Arabic Number
  329. // , (CS): Common Number Separator
  330. // m (NSM): Non-Spacing Mark
  331. // b (BN): Boundary Neutral
  332. // s (B): Paragraph Separator
  333. // t (S): Segment Separator
  334. // w (WS): Whitespace
  335. // N (ON): Other Neutrals
  336. // Returns null if characters are ordered as they appear
  337. // (left-to-right), or an array of sections ({from, to, level}
  338. // objects) in the order in which they occur visually.
  339. var bidiOrdering = (function() {
  340. // Character types for codepoints 0 to 0xff
  341. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  342. // Character types for codepoints 0x600 to 0x6f9
  343. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  344. function charType(code) {
  345. if (code <= 0xf7) { return lowTypes.charAt(code) }
  346. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  347. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  348. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  349. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  350. else if (code == 0x200c) { return "b" }
  351. else { return "L" }
  352. }
  353. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  354. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  355. function BidiSpan(level, from, to) {
  356. this.level = level;
  357. this.from = from; this.to = to;
  358. }
  359. return function(str, direction) {
  360. var outerType = direction == "ltr" ? "L" : "R";
  361. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  362. var len = str.length, types = [];
  363. for (var i = 0; i < len; ++i)
  364. { types.push(charType(str.charCodeAt(i))); }
  365. // W1. Examine each non-spacing mark (NSM) in the level run, and
  366. // change the type of the NSM to the type of the previous
  367. // character. If the NSM is at the start of the level run, it will
  368. // get the type of sor.
  369. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  370. var type = types[i$1];
  371. if (type == "m") { types[i$1] = prev; }
  372. else { prev = type; }
  373. }
  374. // W2. Search backwards from each instance of a European number
  375. // until the first strong type (R, L, AL, or sor) is found. If an
  376. // AL is found, change the type of the European number to Arabic
  377. // number.
  378. // W3. Change all ALs to R.
  379. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  380. var type$1 = types[i$2];
  381. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  382. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  383. }
  384. // W4. A single European separator between two European numbers
  385. // changes to a European number. A single common separator between
  386. // two numbers of the same type changes to that type.
  387. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  388. var type$2 = types[i$3];
  389. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  390. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  391. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  392. prev$1 = type$2;
  393. }
  394. // W5. A sequence of European terminators adjacent to European
  395. // numbers changes to all European numbers.
  396. // W6. Otherwise, separators and terminators change to Other
  397. // Neutral.
  398. for (var i$4 = 0; i$4 < len; ++i$4) {
  399. var type$3 = types[i$4];
  400. if (type$3 == ",") { types[i$4] = "N"; }
  401. else if (type$3 == "%") {
  402. var end = (void 0);
  403. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  404. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  405. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  406. i$4 = end - 1;
  407. }
  408. }
  409. // W7. Search backwards from each instance of a European number
  410. // until the first strong type (R, L, or sor) is found. If an L is
  411. // found, then change the type of the European number to L.
  412. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  413. var type$4 = types[i$5];
  414. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  415. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  416. }
  417. // N1. A sequence of neutrals takes the direction of the
  418. // surrounding strong text if the text on both sides has the same
  419. // direction. European and Arabic numbers act as if they were R in
  420. // terms of their influence on neutrals. Start-of-level-run (sor)
  421. // and end-of-level-run (eor) are used at level run boundaries.
  422. // N2. Any remaining neutrals take the embedding direction.
  423. for (var i$6 = 0; i$6 < len; ++i$6) {
  424. if (isNeutral.test(types[i$6])) {
  425. var end$1 = (void 0);
  426. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  427. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  428. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  429. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  430. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  431. i$6 = end$1 - 1;
  432. }
  433. }
  434. // Here we depart from the documented algorithm, in order to avoid
  435. // building up an actual levels array. Since there are only three
  436. // levels (0, 1, 2) in an implementation that doesn't take
  437. // explicit embedding into account, we can build up the order on
  438. // the fly, without following the level-based algorithm.
  439. var order = [], m;
  440. for (var i$7 = 0; i$7 < len;) {
  441. if (countsAsLeft.test(types[i$7])) {
  442. var start = i$7;
  443. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  444. order.push(new BidiSpan(0, start, i$7));
  445. } else {
  446. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  447. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  448. for (var j$2 = pos; j$2 < i$7;) {
  449. if (countsAsNum.test(types[j$2])) {
  450. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  451. var nstart = j$2;
  452. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  453. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  454. at += isRTL;
  455. pos = j$2;
  456. } else { ++j$2; }
  457. }
  458. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  459. }
  460. }
  461. if (direction == "ltr") {
  462. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  463. order[0].from = m[0].length;
  464. order.unshift(new BidiSpan(0, 0, m[0].length));
  465. }
  466. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  467. lst(order).to -= m[0].length;
  468. order.push(new BidiSpan(0, len - m[0].length, len));
  469. }
  470. }
  471. return direction == "rtl" ? order.reverse() : order
  472. }
  473. })();
  474. // Get the bidi ordering for the given line (and cache it). Returns
  475. // false for lines that are fully left-to-right, and an array of
  476. // BidiSpan objects otherwise.
  477. function getOrder(line, direction) {
  478. var order = line.order;
  479. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  480. return order
  481. }
  482. // EVENT HANDLING
  483. // Lightweight event framework. on/off also work on DOM nodes,
  484. // registering native DOM handlers.
  485. var noHandlers = [];
  486. var on = function(emitter, type, f) {
  487. if (emitter.addEventListener) {
  488. emitter.addEventListener(type, f, false);
  489. } else if (emitter.attachEvent) {
  490. emitter.attachEvent("on" + type, f);
  491. } else {
  492. var map = emitter._handlers || (emitter._handlers = {});
  493. map[type] = (map[type] || noHandlers).concat(f);
  494. }
  495. };
  496. function getHandlers(emitter, type) {
  497. return emitter._handlers && emitter._handlers[type] || noHandlers
  498. }
  499. function off(emitter, type, f) {
  500. if (emitter.removeEventListener) {
  501. emitter.removeEventListener(type, f, false);
  502. } else if (emitter.detachEvent) {
  503. emitter.detachEvent("on" + type, f);
  504. } else {
  505. var map = emitter._handlers, arr = map && map[type];
  506. if (arr) {
  507. var index = indexOf(arr, f);
  508. if (index > -1)
  509. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  510. }
  511. }
  512. }
  513. function signal(emitter, type /*, values...*/) {
  514. var handlers = getHandlers(emitter, type);
  515. if (!handlers.length) { return }
  516. var args = Array.prototype.slice.call(arguments, 2);
  517. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  518. }
  519. // The DOM events that CodeMirror handles can be overridden by
  520. // registering a (non-DOM) handler on the editor for the event name,
  521. // and preventDefault-ing the event in that handler.
  522. function signalDOMEvent(cm, e, override) {
  523. if (typeof e == "string")
  524. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  525. signal(cm, override || e.type, cm, e);
  526. return e_defaultPrevented(e) || e.codemirrorIgnore
  527. }
  528. function signalCursorActivity(cm) {
  529. var arr = cm._handlers && cm._handlers.cursorActivity;
  530. if (!arr) { return }
  531. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  532. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  533. { set.push(arr[i]); } }
  534. }
  535. function hasHandler(emitter, type) {
  536. return getHandlers(emitter, type).length > 0
  537. }
  538. // Add on and off methods to a constructor's prototype, to make
  539. // registering events on such objects more convenient.
  540. function eventMixin(ctor) {
  541. ctor.prototype.on = function(type, f) {on(this, type, f);};
  542. ctor.prototype.off = function(type, f) {off(this, type, f);};
  543. }
  544. // Due to the fact that we still support jurassic IE versions, some
  545. // compatibility wrappers are needed.
  546. function e_preventDefault(e) {
  547. if (e.preventDefault) { e.preventDefault(); }
  548. else { e.returnValue = false; }
  549. }
  550. function e_stopPropagation(e) {
  551. if (e.stopPropagation) { e.stopPropagation(); }
  552. else { e.cancelBubble = true; }
  553. }
  554. function e_defaultPrevented(e) {
  555. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  556. }
  557. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  558. function e_target(e) {return e.target || e.srcElement}
  559. function e_button(e) {
  560. var b = e.which;
  561. if (b == null) {
  562. if (e.button & 1) { b = 1; }
  563. else if (e.button & 2) { b = 3; }
  564. else if (e.button & 4) { b = 2; }
  565. }
  566. if (mac && e.ctrlKey && b == 1) { b = 3; }
  567. return b
  568. }
  569. // Detect drag-and-drop
  570. var dragAndDrop = function() {
  571. // There is *some* kind of drag-and-drop support in IE6-8, but I
  572. // couldn't get it to work yet.
  573. if (ie && ie_version < 9) { return false }
  574. var div = elt('div');
  575. return "draggable" in div || "dragDrop" in div
  576. }();
  577. var zwspSupported;
  578. function zeroWidthElement(measure) {
  579. if (zwspSupported == null) {
  580. var test = elt("span", "\u200b");
  581. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  582. if (measure.firstChild.offsetHeight != 0)
  583. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  584. }
  585. var node = zwspSupported ? elt("span", "\u200b") :
  586. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  587. node.setAttribute("cm-text", "");
  588. return node
  589. }
  590. // Feature-detect IE's crummy client rect reporting for bidi text
  591. var badBidiRects;
  592. function hasBadBidiRects(measure) {
  593. if (badBidiRects != null) { return badBidiRects }
  594. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  595. var r0 = range(txt, 0, 1).getBoundingClientRect();
  596. var r1 = range(txt, 1, 2).getBoundingClientRect();
  597. removeChildren(measure);
  598. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  599. return badBidiRects = (r1.right - r0.right < 3)
  600. }
  601. // See if "".split is the broken IE version, if so, provide an
  602. // alternative way to split lines.
  603. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  604. var pos = 0, result = [], l = string.length;
  605. while (pos <= l) {
  606. var nl = string.indexOf("\n", pos);
  607. if (nl == -1) { nl = string.length; }
  608. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  609. var rt = line.indexOf("\r");
  610. if (rt != -1) {
  611. result.push(line.slice(0, rt));
  612. pos += rt + 1;
  613. } else {
  614. result.push(line);
  615. pos = nl + 1;
  616. }
  617. }
  618. return result
  619. } : function (string) { return string.split(/\r\n?|\n/); };
  620. var hasSelection = window.getSelection ? function (te) {
  621. try { return te.selectionStart != te.selectionEnd }
  622. catch(e) { return false }
  623. } : function (te) {
  624. var range;
  625. try {range = te.ownerDocument.selection.createRange();}
  626. catch(e) {}
  627. if (!range || range.parentElement() != te) { return false }
  628. return range.compareEndPoints("StartToEnd", range) != 0
  629. };
  630. var hasCopyEvent = (function () {
  631. var e = elt("div");
  632. if ("oncopy" in e) { return true }
  633. e.setAttribute("oncopy", "return;");
  634. return typeof e.oncopy == "function"
  635. })();
  636. var badZoomedRects = null;
  637. function hasBadZoomedRects(measure) {
  638. if (badZoomedRects != null) { return badZoomedRects }
  639. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  640. var normal = node.getBoundingClientRect();
  641. var fromRange = range(node, 0, 1).getBoundingClientRect();
  642. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  643. }
  644. // Known modes, by name and by MIME
  645. var modes = {}, mimeModes = {};
  646. // Extra arguments are stored as the mode's dependencies, which is
  647. // used by (legacy) mechanisms like loadmode.js to automatically
  648. // load a mode. (Preferred mechanism is the require/define calls.)
  649. function defineMode(name, mode) {
  650. if (arguments.length > 2)
  651. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  652. modes[name] = mode;
  653. }
  654. function defineMIME(mime, spec) {
  655. mimeModes[mime] = spec;
  656. }
  657. // Given a MIME type, a {name, ...options} config object, or a name
  658. // string, return a mode config object.
  659. function resolveMode(spec) {
  660. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  661. spec = mimeModes[spec];
  662. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  663. var found = mimeModes[spec.name];
  664. if (typeof found == "string") { found = {name: found}; }
  665. spec = createObj(found, spec);
  666. spec.name = found.name;
  667. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  668. return resolveMode("application/xml")
  669. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  670. return resolveMode("application/json")
  671. }
  672. if (typeof spec == "string") { return {name: spec} }
  673. else { return spec || {name: "null"} }
  674. }
  675. // Given a mode spec (anything that resolveMode accepts), find and
  676. // initialize an actual mode object.
  677. function getMode(options, spec) {
  678. spec = resolveMode(spec);
  679. var mfactory = modes[spec.name];
  680. if (!mfactory) { return getMode(options, "text/plain") }
  681. var modeObj = mfactory(options, spec);
  682. if (modeExtensions.hasOwnProperty(spec.name)) {
  683. var exts = modeExtensions[spec.name];
  684. for (var prop in exts) {
  685. if (!exts.hasOwnProperty(prop)) { continue }
  686. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  687. modeObj[prop] = exts[prop];
  688. }
  689. }
  690. modeObj.name = spec.name;
  691. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  692. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  693. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  694. return modeObj
  695. }
  696. // This can be used to attach properties to mode objects from
  697. // outside the actual mode definition.
  698. var modeExtensions = {};
  699. function extendMode(mode, properties) {
  700. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  701. copyObj(properties, exts);
  702. }
  703. function copyState(mode, state) {
  704. if (state === true) { return state }
  705. if (mode.copyState) { return mode.copyState(state) }
  706. var nstate = {};
  707. for (var n in state) {
  708. var val = state[n];
  709. if (val instanceof Array) { val = val.concat([]); }
  710. nstate[n] = val;
  711. }
  712. return nstate
  713. }
  714. // Given a mode and a state (for that mode), find the inner mode and
  715. // state at the position that the state refers to.
  716. function innerMode(mode, state) {
  717. var info;
  718. while (mode.innerMode) {
  719. info = mode.innerMode(state);
  720. if (!info || info.mode == mode) { break }
  721. state = info.state;
  722. mode = info.mode;
  723. }
  724. return info || {mode: mode, state: state}
  725. }
  726. function startState(mode, a1, a2) {
  727. return mode.startState ? mode.startState(a1, a2) : true
  728. }
  729. // STRING STREAM
  730. // Fed to the mode parsers, provides helper functions to make
  731. // parsers more succinct.
  732. var StringStream = function(string, tabSize, lineOracle) {
  733. this.pos = this.start = 0;
  734. this.string = string;
  735. this.tabSize = tabSize || 8;
  736. this.lastColumnPos = this.lastColumnValue = 0;
  737. this.lineStart = 0;
  738. this.lineOracle = lineOracle;
  739. };
  740. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  741. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  742. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  743. StringStream.prototype.next = function () {
  744. if (this.pos < this.string.length)
  745. { return this.string.charAt(this.pos++) }
  746. };
  747. StringStream.prototype.eat = function (match) {
  748. var ch = this.string.charAt(this.pos);
  749. var ok;
  750. if (typeof match == "string") { ok = ch == match; }
  751. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  752. if (ok) {++this.pos; return ch}
  753. };
  754. StringStream.prototype.eatWhile = function (match) {
  755. var start = this.pos;
  756. while (this.eat(match)){}
  757. return this.pos > start
  758. };
  759. StringStream.prototype.eatSpace = function () {
  760. var start = this.pos;
  761. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  762. return this.pos > start
  763. };
  764. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  765. StringStream.prototype.skipTo = function (ch) {
  766. var found = this.string.indexOf(ch, this.pos);
  767. if (found > -1) {this.pos = found; return true}
  768. };
  769. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  770. StringStream.prototype.column = function () {
  771. if (this.lastColumnPos < this.start) {
  772. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  773. this.lastColumnPos = this.start;
  774. }
  775. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  776. };
  777. StringStream.prototype.indentation = function () {
  778. return countColumn(this.string, null, this.tabSize) -
  779. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  780. };
  781. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  782. if (typeof pattern == "string") {
  783. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  784. var substr = this.string.substr(this.pos, pattern.length);
  785. if (cased(substr) == cased(pattern)) {
  786. if (consume !== false) { this.pos += pattern.length; }
  787. return true
  788. }
  789. } else {
  790. var match = this.string.slice(this.pos).match(pattern);
  791. if (match && match.index > 0) { return null }
  792. if (match && consume !== false) { this.pos += match[0].length; }
  793. return match
  794. }
  795. };
  796. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  797. StringStream.prototype.hideFirstChars = function (n, inner) {
  798. this.lineStart += n;
  799. try { return inner() }
  800. finally { this.lineStart -= n; }
  801. };
  802. StringStream.prototype.lookAhead = function (n) {
  803. var oracle = this.lineOracle;
  804. return oracle && oracle.lookAhead(n)
  805. };
  806. StringStream.prototype.baseToken = function () {
  807. var oracle = this.lineOracle;
  808. return oracle && oracle.baseToken(this.pos)
  809. };
  810. // Find the line object corresponding to the given line number.
  811. function getLine(doc, n) {
  812. n -= doc.first;
  813. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  814. var chunk = doc;
  815. while (!chunk.lines) {
  816. for (var i = 0;; ++i) {
  817. var child = chunk.children[i], sz = child.chunkSize();
  818. if (n < sz) { chunk = child; break }
  819. n -= sz;
  820. }
  821. }
  822. return chunk.lines[n]
  823. }
  824. // Get the part of a document between two positions, as an array of
  825. // strings.
  826. function getBetween(doc, start, end) {
  827. var out = [], n = start.line;
  828. doc.iter(start.line, end.line + 1, function (line) {
  829. var text = line.text;
  830. if (n == end.line) { text = text.slice(0, end.ch); }
  831. if (n == start.line) { text = text.slice(start.ch); }
  832. out.push(text);
  833. ++n;
  834. });
  835. return out
  836. }
  837. // Get the lines between from and to, as array of strings.
  838. function getLines(doc, from, to) {
  839. var out = [];
  840. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  841. return out
  842. }
  843. // Update the height of a line, propagating the height change
  844. // upwards to parent nodes.
  845. function updateLineHeight(line, height) {
  846. var diff = height - line.height;
  847. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  848. }
  849. // Given a line object, find its line number by walking up through
  850. // its parent links.
  851. function lineNo(line) {
  852. if (line.parent == null) { return null }
  853. var cur = line.parent, no = indexOf(cur.lines, line);
  854. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  855. for (var i = 0;; ++i) {
  856. if (chunk.children[i] == cur) { break }
  857. no += chunk.children[i].chunkSize();
  858. }
  859. }
  860. return no + cur.first
  861. }
  862. // Find the line at the given vertical position, using the height
  863. // information in the document tree.
  864. function lineAtHeight(chunk, h) {
  865. var n = chunk.first;
  866. outer: do {
  867. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  868. var child = chunk.children[i$1], ch = child.height;
  869. if (h < ch) { chunk = child; continue outer }
  870. h -= ch;
  871. n += child.chunkSize();
  872. }
  873. return n
  874. } while (!chunk.lines)
  875. var i = 0;
  876. for (; i < chunk.lines.length; ++i) {
  877. var line = chunk.lines[i], lh = line.height;
  878. if (h < lh) { break }
  879. h -= lh;
  880. }
  881. return n + i
  882. }
  883. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  884. function lineNumberFor(options, i) {
  885. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  886. }
  887. // A Pos instance represents a position within the text.
  888. function Pos(line, ch, sticky) {
  889. if ( sticky === void 0 ) sticky = null;
  890. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  891. this.line = line;
  892. this.ch = ch;
  893. this.sticky = sticky;
  894. }
  895. // Compare two positions, return 0 if they are the same, a negative
  896. // number when a is less, and a positive number otherwise.
  897. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  898. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  899. function copyPos(x) {return Pos(x.line, x.ch)}
  900. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  901. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  902. // Most of the external API clips given positions to make sure they
  903. // actually exist within the document.
  904. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  905. function clipPos(doc, pos) {
  906. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  907. var last = doc.first + doc.size - 1;
  908. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  909. return clipToLen(pos, getLine(doc, pos.line).text.length)
  910. }
  911. function clipToLen(pos, linelen) {
  912. var ch = pos.ch;
  913. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  914. else if (ch < 0) { return Pos(pos.line, 0) }
  915. else { return pos }
  916. }
  917. function clipPosArray(doc, array) {
  918. var out = [];
  919. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  920. return out
  921. }
  922. var SavedContext = function(state, lookAhead) {
  923. this.state = state;
  924. this.lookAhead = lookAhead;
  925. };
  926. var Context = function(doc, state, line, lookAhead) {
  927. this.state = state;
  928. this.doc = doc;
  929. this.line = line;
  930. this.maxLookAhead = lookAhead || 0;
  931. this.baseTokens = null;
  932. this.baseTokenPos = 1;
  933. };
  934. Context.prototype.lookAhead = function (n) {
  935. var line = this.doc.getLine(this.line + n);
  936. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  937. return line
  938. };
  939. Context.prototype.baseToken = function (n) {
  940. if (!this.baseTokens) { return null }
  941. while (this.baseTokens[this.baseTokenPos] <= n)
  942. { this.baseTokenPos += 2; }
  943. var type = this.baseTokens[this.baseTokenPos + 1];
  944. return {type: type && type.replace(/( |^)overlay .*/, ""),
  945. size: this.baseTokens[this.baseTokenPos] - n}
  946. };
  947. Context.prototype.nextLine = function () {
  948. this.line++;
  949. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  950. };
  951. Context.fromSaved = function (doc, saved, line) {
  952. if (saved instanceof SavedContext)
  953. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  954. else
  955. { return new Context(doc, copyState(doc.mode, saved), line) }
  956. };
  957. Context.prototype.save = function (copy) {
  958. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  959. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  960. };
  961. // Compute a style array (an array starting with a mode generation
  962. // -- for invalidation -- followed by pairs of end positions and
  963. // style strings), which is used to highlight the tokens on the
  964. // line.
  965. function highlightLine(cm, line, context, forceToEnd) {
  966. // A styles array always starts with a number identifying the
  967. // mode/overlays that it is based on (for easy invalidation).
  968. var st = [cm.state.modeGen], lineClasses = {};
  969. // Compute the base array of styles
  970. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  971. lineClasses, forceToEnd);
  972. var state = context.state;
  973. // Run overlays, adjust style array.
  974. var loop = function ( o ) {
  975. context.baseTokens = st;
  976. var overlay = cm.state.overlays[o], i = 1, at = 0;
  977. context.state = true;
  978. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  979. var start = i;
  980. // Ensure there's a token end at the current position, and that i points at it
  981. while (at < end) {
  982. var i_end = st[i];
  983. if (i_end > end)
  984. { st.splice(i, 1, end, st[i+1], i_end); }
  985. i += 2;
  986. at = Math.min(end, i_end);
  987. }
  988. if (!style) { return }
  989. if (overlay.opaque) {
  990. st.splice(start, i - start, end, "overlay " + style);
  991. i = start + 2;
  992. } else {
  993. for (; start < i; start += 2) {
  994. var cur = st[start+1];
  995. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  996. }
  997. }
  998. }, lineClasses);
  999. context.state = state;
  1000. context.baseTokens = null;
  1001. context.baseTokenPos = 1;
  1002. };
  1003. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1004. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1005. }
  1006. function getLineStyles(cm, line, updateFrontier) {
  1007. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1008. var context = getContextBefore(cm, lineNo(line));
  1009. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1010. var result = highlightLine(cm, line, context);
  1011. if (resetState) { context.state = resetState; }
  1012. line.stateAfter = context.save(!resetState);
  1013. line.styles = result.styles;
  1014. if (result.classes) { line.styleClasses = result.classes; }
  1015. else if (line.styleClasses) { line.styleClasses = null; }
  1016. if (updateFrontier === cm.doc.highlightFrontier)
  1017. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1018. }
  1019. return line.styles
  1020. }
  1021. function getContextBefore(cm, n, precise) {
  1022. var doc = cm.doc, display = cm.display;
  1023. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1024. var start = findStartLine(cm, n, precise);
  1025. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1026. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1027. doc.iter(start, n, function (line) {
  1028. processLine(cm, line.text, context);
  1029. var pos = context.line;
  1030. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1031. context.nextLine();
  1032. });
  1033. if (precise) { doc.modeFrontier = context.line; }
  1034. return context
  1035. }
  1036. // Lightweight form of highlight -- proceed over this line and
  1037. // update state, but don't save a style array. Used for lines that
  1038. // aren't currently visible.
  1039. function processLine(cm, text, context, startAt) {
  1040. var mode = cm.doc.mode;
  1041. var stream = new StringStream(text, cm.options.tabSize, context);
  1042. stream.start = stream.pos = startAt || 0;
  1043. if (text == "") { callBlankLine(mode, context.state); }
  1044. while (!stream.eol()) {
  1045. readToken(mode, stream, context.state);
  1046. stream.start = stream.pos;
  1047. }
  1048. }
  1049. function callBlankLine(mode, state) {
  1050. if (mode.blankLine) { return mode.blankLine(state) }
  1051. if (!mode.innerMode) { return }
  1052. var inner = innerMode(mode, state);
  1053. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1054. }
  1055. function readToken(mode, stream, state, inner) {
  1056. for (var i = 0; i < 10; i++) {
  1057. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1058. var style = mode.token(stream, state);
  1059. if (stream.pos > stream.start) { return style }
  1060. }
  1061. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1062. }
  1063. var Token = function(stream, type, state) {
  1064. this.start = stream.start; this.end = stream.pos;
  1065. this.string = stream.current();
  1066. this.type = type || null;
  1067. this.state = state;
  1068. };
  1069. // Utility for getTokenAt and getLineTokens
  1070. function takeToken(cm, pos, precise, asArray) {
  1071. var doc = cm.doc, mode = doc.mode, style;
  1072. pos = clipPos(doc, pos);
  1073. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1074. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1075. if (asArray) { tokens = []; }
  1076. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1077. stream.start = stream.pos;
  1078. style = readToken(mode, stream, context.state);
  1079. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1080. }
  1081. return asArray ? tokens : new Token(stream, style, context.state)
  1082. }
  1083. function extractLineClasses(type, output) {
  1084. if (type) { for (;;) {
  1085. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1086. if (!lineClass) { break }
  1087. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1088. var prop = lineClass[1] ? "bgClass" : "textClass";
  1089. if (output[prop] == null)
  1090. { output[prop] = lineClass[2]; }
  1091. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1092. { output[prop] += " " + lineClass[2]; }
  1093. } }
  1094. return type
  1095. }
  1096. // Run the given mode's parser over a line, calling f for each token.
  1097. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1098. var flattenSpans = mode.flattenSpans;
  1099. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1100. var curStart = 0, curStyle = null;
  1101. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1102. var inner = cm.options.addModeClass && [null];
  1103. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1104. while (!stream.eol()) {
  1105. if (stream.pos > cm.options.maxHighlightLength) {
  1106. flattenSpans = false;
  1107. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1108. stream.pos = text.length;
  1109. style = null;
  1110. } else {
  1111. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1112. }
  1113. if (inner) {
  1114. var mName = inner[0].name;
  1115. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1116. }
  1117. if (!flattenSpans || curStyle != style) {
  1118. while (curStart < stream.start) {
  1119. curStart = Math.min(stream.start, curStart + 5000);
  1120. f(curStart, curStyle);
  1121. }
  1122. curStyle = style;
  1123. }
  1124. stream.start = stream.pos;
  1125. }
  1126. while (curStart < stream.pos) {
  1127. // Webkit seems to refuse to render text nodes longer than 57444
  1128. // characters, and returns inaccurate measurements in nodes
  1129. // starting around 5000 chars.
  1130. var pos = Math.min(stream.pos, curStart + 5000);
  1131. f(pos, curStyle);
  1132. curStart = pos;
  1133. }
  1134. }
  1135. // Finds the line to start with when starting a parse. Tries to
  1136. // find a line with a stateAfter, so that it can start with a
  1137. // valid state. If that fails, it returns the line with the
  1138. // smallest indentation, which tends to need the least context to
  1139. // parse correctly.
  1140. function findStartLine(cm, n, precise) {
  1141. var minindent, minline, doc = cm.doc;
  1142. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1143. for (var search = n; search > lim; --search) {
  1144. if (search <= doc.first) { return doc.first }
  1145. var line = getLine(doc, search - 1), after = line.stateAfter;
  1146. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1147. { return search }
  1148. var indented = countColumn(line.text, null, cm.options.tabSize);
  1149. if (minline == null || minindent > indented) {
  1150. minline = search - 1;
  1151. minindent = indented;
  1152. }
  1153. }
  1154. return minline
  1155. }
  1156. function retreatFrontier(doc, n) {
  1157. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1158. if (doc.highlightFrontier < n - 10) { return }
  1159. var start = doc.first;
  1160. for (var line = n - 1; line > start; line--) {
  1161. var saved = getLine(doc, line).stateAfter;
  1162. // change is on 3
  1163. // state on line 1 looked ahead 2 -- so saw 3
  1164. // test 1 + 2 < 3 should cover this
  1165. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1166. start = line + 1;
  1167. break
  1168. }
  1169. }
  1170. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1171. }
  1172. // Optimize some code when these features are not used.
  1173. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1174. function seeReadOnlySpans() {
  1175. sawReadOnlySpans = true;
  1176. }
  1177. function seeCollapsedSpans() {
  1178. sawCollapsedSpans = true;
  1179. }
  1180. // TEXTMARKER SPANS
  1181. function MarkedSpan(marker, from, to) {
  1182. this.marker = marker;
  1183. this.from = from; this.to = to;
  1184. }
  1185. // Search an array of spans for a span matching the given marker.
  1186. function getMarkedSpanFor(spans, marker) {
  1187. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1188. var span = spans[i];
  1189. if (span.marker == marker) { return span }
  1190. } }
  1191. }
  1192. // Remove a span from an array, returning undefined if no spans are
  1193. // left (we don't store arrays for lines without spans).
  1194. function removeMarkedSpan(spans, span) {
  1195. var r;
  1196. for (var i = 0; i < spans.length; ++i)
  1197. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1198. return r
  1199. }
  1200. // Add a span to a line.
  1201. function addMarkedSpan(line, span, op) {
  1202. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1203. if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
  1204. line.markedSpans.push(span);
  1205. } else {
  1206. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1207. if (inThisOp) { inThisOp.add(line.markedSpans); }
  1208. }
  1209. span.marker.attachLine(line);
  1210. }
  1211. // Used for the algorithm that adjusts markers for a change in the
  1212. // document. These functions cut an array of spans at a given
  1213. // character position, returning an array of remaining chunks (or
  1214. // undefined if nothing remains).
  1215. function markedSpansBefore(old, startCh, isInsert) {
  1216. var nw;
  1217. if (old) { for (var i = 0; i < old.length; ++i) {
  1218. var span = old[i], marker = span.marker;
  1219. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1220. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1221. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1222. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1223. }
  1224. } }
  1225. return nw
  1226. }
  1227. function markedSpansAfter(old, endCh, isInsert) {
  1228. var nw;
  1229. if (old) { for (var i = 0; i < old.length; ++i) {
  1230. var span = old[i], marker = span.marker;
  1231. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1232. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1233. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1234. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1235. span.to == null ? null : span.to - endCh));
  1236. }
  1237. } }
  1238. return nw
  1239. }
  1240. // Given a change object, compute the new set of marker spans that
  1241. // cover the line in which the change took place. Removes spans
  1242. // entirely within the change, reconnects spans belonging to the
  1243. // same marker that appear on both sides of the change, and cuts off
  1244. // spans partially within the change. Returns an array of span
  1245. // arrays with one element for each line in (after) the change.
  1246. function stretchSpansOverChange(doc, change) {
  1247. if (change.full) { return null }
  1248. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1249. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1250. if (!oldFirst && !oldLast) { return null }
  1251. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1252. // Get the spans that 'stick out' on both sides
  1253. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1254. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1255. // Next, merge those two ends
  1256. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1257. if (first) {
  1258. // Fix up .to properties of first
  1259. for (var i = 0; i < first.length; ++i) {
  1260. var span = first[i];
  1261. if (span.to == null) {
  1262. var found = getMarkedSpanFor(last, span.marker);
  1263. if (!found) { span.to = startCh; }
  1264. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1265. }
  1266. }
  1267. }
  1268. if (last) {
  1269. // Fix up .from in last (or move them into first in case of sameLine)
  1270. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1271. var span$1 = last[i$1];
  1272. if (span$1.to != null) { span$1.to += offset; }
  1273. if (span$1.from == null) {
  1274. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1275. if (!found$1) {
  1276. span$1.from = offset;
  1277. if (sameLine) { (first || (first = [])).push(span$1); }
  1278. }
  1279. } else {
  1280. span$1.from += offset;
  1281. if (sameLine) { (first || (first = [])).push(span$1); }
  1282. }
  1283. }
  1284. }
  1285. // Make sure we didn't create any zero-length spans
  1286. if (first) { first = clearEmptySpans(first); }
  1287. if (last && last != first) { last = clearEmptySpans(last); }
  1288. var newMarkers = [first];
  1289. if (!sameLine) {
  1290. // Fill gap with whole-line-spans
  1291. var gap = change.text.length - 2, gapMarkers;
  1292. if (gap > 0 && first)
  1293. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1294. { if (first[i$2].to == null)
  1295. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1296. for (var i$3 = 0; i$3 < gap; ++i$3)
  1297. { newMarkers.push(gapMarkers); }
  1298. newMarkers.push(last);
  1299. }
  1300. return newMarkers
  1301. }
  1302. // Remove spans that are empty and don't have a clearWhenEmpty
  1303. // option of false.
  1304. function clearEmptySpans(spans) {
  1305. for (var i = 0; i < spans.length; ++i) {
  1306. var span = spans[i];
  1307. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1308. { spans.splice(i--, 1); }
  1309. }
  1310. if (!spans.length) { return null }
  1311. return spans
  1312. }
  1313. // Used to 'clip' out readOnly ranges when making a change.
  1314. function removeReadOnlyRanges(doc, from, to) {
  1315. var markers = null;
  1316. doc.iter(from.line, to.line + 1, function (line) {
  1317. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1318. var mark = line.markedSpans[i].marker;
  1319. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1320. { (markers || (markers = [])).push(mark); }
  1321. } }
  1322. });
  1323. if (!markers) { return null }
  1324. var parts = [{from: from, to: to}];
  1325. for (var i = 0; i < markers.length; ++i) {
  1326. var mk = markers[i], m = mk.find(0);
  1327. for (var j = 0; j < parts.length; ++j) {
  1328. var p = parts[j];
  1329. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1330. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1331. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1332. { newParts.push({from: p.from, to: m.from}); }
  1333. if (dto > 0 || !mk.inclusiveRight && !dto)
  1334. { newParts.push({from: m.to, to: p.to}); }
  1335. parts.splice.apply(parts, newParts);
  1336. j += newParts.length - 3;
  1337. }
  1338. }
  1339. return parts
  1340. }
  1341. // Connect or disconnect spans from a line.
  1342. function detachMarkedSpans(line) {
  1343. var spans = line.markedSpans;
  1344. if (!spans) { return }
  1345. for (var i = 0; i < spans.length; ++i)
  1346. { spans[i].marker.detachLine(line); }
  1347. line.markedSpans = null;
  1348. }
  1349. function attachMarkedSpans(line, spans) {
  1350. if (!spans) { return }
  1351. for (var i = 0; i < spans.length; ++i)
  1352. { spans[i].marker.attachLine(line); }
  1353. line.markedSpans = spans;
  1354. }
  1355. // Helpers used when computing which overlapping collapsed span
  1356. // counts as the larger one.
  1357. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1358. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1359. // Returns a number indicating which of two overlapping collapsed
  1360. // spans is larger (and thus includes the other). Falls back to
  1361. // comparing ids when the spans cover exactly the same range.
  1362. function compareCollapsedMarkers(a, b) {
  1363. var lenDiff = a.lines.length - b.lines.length;
  1364. if (lenDiff != 0) { return lenDiff }
  1365. var aPos = a.find(), bPos = b.find();
  1366. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1367. if (fromCmp) { return -fromCmp }
  1368. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1369. if (toCmp) { return toCmp }
  1370. return b.id - a.id
  1371. }
  1372. // Find out whether a line ends or starts in a collapsed span. If
  1373. // so, return the marker for that span.
  1374. function collapsedSpanAtSide(line, start) {
  1375. var sps = sawCollapsedSpans && line.markedSpans, found;
  1376. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1377. sp = sps[i];
  1378. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1379. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1380. { found = sp.marker; }
  1381. } }
  1382. return found
  1383. }
  1384. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1385. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1386. function collapsedSpanAround(line, ch) {
  1387. var sps = sawCollapsedSpans && line.markedSpans, found;
  1388. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1389. var sp = sps[i];
  1390. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1391. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1392. } }
  1393. return found
  1394. }
  1395. // Test whether there exists a collapsed span that partially
  1396. // overlaps (covers the start or end, but not both) of a new span.
  1397. // Such overlap is not allowed.
  1398. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1399. var line = getLine(doc, lineNo);
  1400. var sps = sawCollapsedSpans && line.markedSpans;
  1401. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1402. var sp = sps[i];
  1403. if (!sp.marker.collapsed) { continue }
  1404. var found = sp.marker.find(0);
  1405. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1406. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1407. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1408. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1409. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1410. { return true }
  1411. } }
  1412. }
  1413. // A visual line is a line as drawn on the screen. Folding, for
  1414. // example, can cause multiple logical lines to appear on the same
  1415. // visual line. This finds the start of the visual line that the
  1416. // given line is part of (usually that is the line itself).
  1417. function visualLine(line) {
  1418. var merged;
  1419. while (merged = collapsedSpanAtStart(line))
  1420. { line = merged.find(-1, true).line; }
  1421. return line
  1422. }
  1423. function visualLineEnd(line) {
  1424. var merged;
  1425. while (merged = collapsedSpanAtEnd(line))
  1426. { line = merged.find(1, true).line; }
  1427. return line
  1428. }
  1429. // Returns an array of logical lines that continue the visual line
  1430. // started by the argument, or undefined if there are no such lines.
  1431. function visualLineContinued(line) {
  1432. var merged, lines;
  1433. while (merged = collapsedSpanAtEnd(line)) {
  1434. line = merged.find(1, true).line
  1435. ;(lines || (lines = [])).push(line);
  1436. }
  1437. return lines
  1438. }
  1439. // Get the line number of the start of the visual line that the
  1440. // given line number is part of.
  1441. function visualLineNo(doc, lineN) {
  1442. var line = getLine(doc, lineN), vis = visualLine(line);
  1443. if (line == vis) { return lineN }
  1444. return lineNo(vis)
  1445. }
  1446. // Get the line number of the start of the next visual line after
  1447. // the given line.
  1448. function visualLineEndNo(doc, lineN) {
  1449. if (lineN > doc.lastLine()) { return lineN }
  1450. var line = getLine(doc, lineN), merged;
  1451. if (!lineIsHidden(doc, line)) { return lineN }
  1452. while (merged = collapsedSpanAtEnd(line))
  1453. { line = merged.find(1, true).line; }
  1454. return lineNo(line) + 1
  1455. }
  1456. // Compute whether a line is hidden. Lines count as hidden when they
  1457. // are part of a visual line that starts with another line, or when
  1458. // they are entirely covered by collapsed, non-widget span.
  1459. function lineIsHidden(doc, line) {
  1460. var sps = sawCollapsedSpans && line.markedSpans;
  1461. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1462. sp = sps[i];
  1463. if (!sp.marker.collapsed) { continue }
  1464. if (sp.from == null) { return true }
  1465. if (sp.marker.widgetNode) { continue }
  1466. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1467. { return true }
  1468. } }
  1469. }
  1470. function lineIsHiddenInner(doc, line, span) {
  1471. if (span.to == null) {
  1472. var end = span.marker.find(1, true);
  1473. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1474. }
  1475. if (span.marker.inclusiveRight && span.to == line.text.length)
  1476. { return true }
  1477. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1478. sp = line.markedSpans[i];
  1479. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1480. (sp.to == null || sp.to != span.from) &&
  1481. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1482. lineIsHiddenInner(doc, line, sp)) { return true }
  1483. }
  1484. }
  1485. // Find the height above the given line.
  1486. function heightAtLine(lineObj) {
  1487. lineObj = visualLine(lineObj);
  1488. var h = 0, chunk = lineObj.parent;
  1489. for (var i = 0; i < chunk.lines.length; ++i) {
  1490. var line = chunk.lines[i];
  1491. if (line == lineObj) { break }
  1492. else { h += line.height; }
  1493. }
  1494. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1495. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1496. var cur = p.children[i$1];
  1497. if (cur == chunk) { break }
  1498. else { h += cur.height; }
  1499. }
  1500. }
  1501. return h
  1502. }
  1503. // Compute the character length of a line, taking into account
  1504. // collapsed ranges (see markText) that might hide parts, and join
  1505. // other lines onto it.
  1506. function lineLength(line) {
  1507. if (line.height == 0) { return 0 }
  1508. var len = line.text.length, merged, cur = line;
  1509. while (merged = collapsedSpanAtStart(cur)) {
  1510. var found = merged.find(0, true);
  1511. cur = found.from.line;
  1512. len += found.from.ch - found.to.ch;
  1513. }
  1514. cur = line;
  1515. while (merged = collapsedSpanAtEnd(cur)) {
  1516. var found$1 = merged.find(0, true);
  1517. len -= cur.text.length - found$1.from.ch;
  1518. cur = found$1.to.line;
  1519. len += cur.text.length - found$1.to.ch;
  1520. }
  1521. return len
  1522. }
  1523. // Find the longest line in the document.
  1524. function findMaxLine(cm) {
  1525. var d = cm.display, doc = cm.doc;
  1526. d.maxLine = getLine(doc, doc.first);
  1527. d.maxLineLength = lineLength(d.maxLine);
  1528. d.maxLineChanged = true;
  1529. doc.iter(function (line) {
  1530. var len = lineLength(line);
  1531. if (len > d.maxLineLength) {
  1532. d.maxLineLength = len;
  1533. d.maxLine = line;
  1534. }
  1535. });
  1536. }
  1537. // LINE DATA STRUCTURE
  1538. // Line objects. These hold state related to a line, including
  1539. // highlighting info (the styles array).
  1540. var Line = function(text, markedSpans, estimateHeight) {
  1541. this.text = text;
  1542. attachMarkedSpans(this, markedSpans);
  1543. this.height = estimateHeight ? estimateHeight(this) : 1;
  1544. };
  1545. Line.prototype.lineNo = function () { return lineNo(this) };
  1546. eventMixin(Line);
  1547. // Change the content (text, markers) of a line. Automatically
  1548. // invalidates cached information and tries to re-estimate the
  1549. // line's height.
  1550. function updateLine(line, text, markedSpans, estimateHeight) {
  1551. line.text = text;
  1552. if (line.stateAfter) { line.stateAfter = null; }
  1553. if (line.styles) { line.styles = null; }
  1554. if (line.order != null) { line.order = null; }
  1555. detachMarkedSpans(line);
  1556. attachMarkedSpans(line, markedSpans);
  1557. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1558. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1559. }
  1560. // Detach a line from the document tree and its markers.
  1561. function cleanUpLine(line) {
  1562. line.parent = null;
  1563. detachMarkedSpans(line);
  1564. }
  1565. // Convert a style as returned by a mode (either null, or a string
  1566. // containing one or more styles) to a CSS style. This is cached,
  1567. // and also looks for line-wide styles.
  1568. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1569. function interpretTokenStyle(style, options) {
  1570. if (!style || /^\s*$/.test(style)) { return null }
  1571. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1572. return cache[style] ||
  1573. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1574. }
  1575. // Render the DOM representation of the text of a line. Also builds
  1576. // up a 'line map', which points at the DOM nodes that represent
  1577. // specific stretches of text, and is used by the measuring code.
  1578. // The returned object contains the DOM node, this map, and
  1579. // information about line-wide styles that were set by the mode.
  1580. function buildLineContent(cm, lineView) {
  1581. // The padding-right forces the element to have a 'border', which
  1582. // is needed on Webkit to be able to get line-level bounding
  1583. // rectangles for it (in measureChar).
  1584. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1585. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1586. col: 0, pos: 0, cm: cm,
  1587. trailingSpace: false,
  1588. splitSpaces: cm.getOption("lineWrapping")};
  1589. lineView.measure = {};
  1590. // Iterate over the logical lines that make up this visual line.
  1591. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1592. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1593. builder.pos = 0;
  1594. builder.addToken = buildToken;
  1595. // Optionally wire in some hacks into the token-rendering
  1596. // algorithm, to deal with browser quirks.
  1597. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1598. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1599. builder.map = [];
  1600. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1601. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1602. if (line.styleClasses) {
  1603. if (line.styleClasses.bgClass)
  1604. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1605. if (line.styleClasses.textClass)
  1606. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1607. }
  1608. // Ensure at least a single node is present, for measuring.
  1609. if (builder.map.length == 0)
  1610. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1611. // Store the map and a cache object for the current logical line
  1612. if (i == 0) {
  1613. lineView.measure.map = builder.map;
  1614. lineView.measure.cache = {};
  1615. } else {
  1616. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1617. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1618. }
  1619. }
  1620. // See issue #2901
  1621. if (webkit) {
  1622. var last = builder.content.lastChild;
  1623. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1624. { builder.content.className = "cm-tab-wrap-hack"; }
  1625. }
  1626. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1627. if (builder.pre.className)
  1628. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1629. return builder
  1630. }
  1631. function defaultSpecialCharPlaceholder(ch) {
  1632. var token = elt("span", "\u2022", "cm-invalidchar");
  1633. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1634. token.setAttribute("aria-label", token.title);
  1635. return token
  1636. }
  1637. // Build up the DOM representation for a single token, and add it to
  1638. // the line map. Takes care to render special characters separately.
  1639. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1640. if (!text) { return }
  1641. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1642. var special = builder.cm.state.specialChars, mustWrap = false;
  1643. var content;
  1644. if (!special.test(text)) {
  1645. builder.col += text.length;
  1646. content = document.createTextNode(displayText);
  1647. builder.map.push(builder.pos, builder.pos + text.length, content);
  1648. if (ie && ie_version < 9) { mustWrap = true; }
  1649. builder.pos += text.length;
  1650. } else {
  1651. content = document.createDocumentFragment();
  1652. var pos = 0;
  1653. while (true) {
  1654. special.lastIndex = pos;
  1655. var m = special.exec(text);
  1656. var skipped = m ? m.index - pos : text.length - pos;
  1657. if (skipped) {
  1658. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1659. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1660. else { content.appendChild(txt); }
  1661. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1662. builder.col += skipped;
  1663. builder.pos += skipped;
  1664. }
  1665. if (!m) { break }
  1666. pos += skipped + 1;
  1667. var txt$1 = (void 0);
  1668. if (m[0] == "\t") {
  1669. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1670. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1671. txt$1.setAttribute("role", "presentation");
  1672. txt$1.setAttribute("cm-text", "\t");
  1673. builder.col += tabWidth;
  1674. } else if (m[0] == "\r" || m[0] == "\n") {
  1675. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1676. txt$1.setAttribute("cm-text", m[0]);
  1677. builder.col += 1;
  1678. } else {
  1679. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1680. txt$1.setAttribute("cm-text", m[0]);
  1681. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1682. else { content.appendChild(txt$1); }
  1683. builder.col += 1;
  1684. }
  1685. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1686. builder.pos++;
  1687. }
  1688. }
  1689. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1690. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1691. var fullStyle = style || "";
  1692. if (startStyle) { fullStyle += startStyle; }
  1693. if (endStyle) { fullStyle += endStyle; }
  1694. var token = elt("span", [content], fullStyle, css);
  1695. if (attributes) {
  1696. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1697. { token.setAttribute(attr, attributes[attr]); } }
  1698. }
  1699. return builder.content.appendChild(token)
  1700. }
  1701. builder.content.appendChild(content);
  1702. }
  1703. // Change some spaces to NBSP to prevent the browser from collapsing
  1704. // trailing spaces at the end of a line when rendering text (issue #1362).
  1705. function splitSpaces(text, trailingBefore) {
  1706. if (text.length > 1 && !/ /.test(text)) { return text }
  1707. var spaceBefore = trailingBefore, result = "";
  1708. for (var i = 0; i < text.length; i++) {
  1709. var ch = text.charAt(i);
  1710. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1711. { ch = "\u00a0"; }
  1712. result += ch;
  1713. spaceBefore = ch == " ";
  1714. }
  1715. return result
  1716. }
  1717. // Work around nonsense dimensions being reported for stretches of
  1718. // right-to-left text.
  1719. function buildTokenBadBidi(inner, order) {
  1720. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1721. style = style ? style + " cm-force-border" : "cm-force-border";
  1722. var start = builder.pos, end = start + text.length;
  1723. for (;;) {
  1724. // Find the part that overlaps with the start of this text
  1725. var part = (void 0);
  1726. for (var i = 0; i < order.length; i++) {
  1727. part = order[i];
  1728. if (part.to > start && part.from <= start) { break }
  1729. }
  1730. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1731. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1732. startStyle = null;
  1733. text = text.slice(part.to - start);
  1734. start = part.to;
  1735. }
  1736. }
  1737. }
  1738. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1739. var widget = !ignoreWidget && marker.widgetNode;
  1740. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1741. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1742. if (!widget)
  1743. { widget = builder.content.appendChild(document.createElement("span")); }
  1744. widget.setAttribute("cm-marker", marker.id);
  1745. }
  1746. if (widget) {
  1747. builder.cm.display.input.setUneditable(widget);
  1748. builder.content.appendChild(widget);
  1749. }
  1750. builder.pos += size;
  1751. builder.trailingSpace = false;
  1752. }
  1753. // Outputs a number of spans to make up a line, taking highlighting
  1754. // and marked text into account.
  1755. function insertLineContent(line, builder, styles) {
  1756. var spans = line.markedSpans, allText = line.text, at = 0;
  1757. if (!spans) {
  1758. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1759. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1760. return
  1761. }
  1762. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1763. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1764. for (;;) {
  1765. if (nextChange == pos) { // Update current marker set
  1766. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1767. attributes = null;
  1768. collapsed = null; nextChange = Infinity;
  1769. var foundBookmarks = [], endStyles = (void 0);
  1770. for (var j = 0; j < spans.length; ++j) {
  1771. var sp = spans[j], m = sp.marker;
  1772. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1773. foundBookmarks.push(m);
  1774. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1775. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1776. nextChange = sp.to;
  1777. spanEndStyle = "";
  1778. }
  1779. if (m.className) { spanStyle += " " + m.className; }
  1780. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1781. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1782. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1783. // support for the old title property
  1784. // https://github.com/codemirror/CodeMirror/pull/5673
  1785. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1786. if (m.attributes) {
  1787. for (var attr in m.attributes)
  1788. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1789. }
  1790. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1791. { collapsed = sp; }
  1792. } else if (sp.from > pos && nextChange > sp.from) {
  1793. nextChange = sp.from;
  1794. }
  1795. }
  1796. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1797. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1798. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1799. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1800. if (collapsed && (collapsed.from || 0) == pos) {
  1801. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1802. collapsed.marker, collapsed.from == null);
  1803. if (collapsed.to == null) { return }
  1804. if (collapsed.to == pos) { collapsed = false; }
  1805. }
  1806. }
  1807. if (pos >= len) { break }
  1808. var upto = Math.min(len, nextChange);
  1809. while (true) {
  1810. if (text) {
  1811. var end = pos + text.length;
  1812. if (!collapsed) {
  1813. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1814. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1815. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1816. }
  1817. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1818. pos = end;
  1819. spanStartStyle = "";
  1820. }
  1821. text = allText.slice(at, at = styles[i++]);
  1822. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1823. }
  1824. }
  1825. }
  1826. // These objects are used to represent the visible (currently drawn)
  1827. // part of the document. A LineView may correspond to multiple
  1828. // logical lines, if those are connected by collapsed ranges.
  1829. function LineView(doc, line, lineN) {
  1830. // The starting line
  1831. this.line = line;
  1832. // Continuing lines, if any
  1833. this.rest = visualLineContinued(line);
  1834. // Number of logical lines in this visual line
  1835. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1836. this.node = this.text = null;
  1837. this.hidden = lineIsHidden(doc, line);
  1838. }
  1839. // Create a range of LineView objects for the given lines.
  1840. function buildViewArray(cm, from, to) {
  1841. var array = [], nextPos;
  1842. for (var pos = from; pos < to; pos = nextPos) {
  1843. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1844. nextPos = pos + view.size;
  1845. array.push(view);
  1846. }
  1847. return array
  1848. }
  1849. var operationGroup = null;
  1850. function pushOperation(op) {
  1851. if (operationGroup) {
  1852. operationGroup.ops.push(op);
  1853. } else {
  1854. op.ownsGroup = operationGroup = {
  1855. ops: [op],
  1856. delayedCallbacks: []
  1857. };
  1858. }
  1859. }
  1860. function fireCallbacksForOps(group) {
  1861. // Calls delayed callbacks and cursorActivity handlers until no
  1862. // new ones appear
  1863. var callbacks = group.delayedCallbacks, i = 0;
  1864. do {
  1865. for (; i < callbacks.length; i++)
  1866. { callbacks[i].call(null); }
  1867. for (var j = 0; j < group.ops.length; j++) {
  1868. var op = group.ops[j];
  1869. if (op.cursorActivityHandlers)
  1870. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1871. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1872. }
  1873. } while (i < callbacks.length)
  1874. }
  1875. function finishOperation(op, endCb) {
  1876. var group = op.ownsGroup;
  1877. if (!group) { return }
  1878. try { fireCallbacksForOps(group); }
  1879. finally {
  1880. operationGroup = null;
  1881. endCb(group);
  1882. }
  1883. }
  1884. var orphanDelayedCallbacks = null;
  1885. // Often, we want to signal events at a point where we are in the
  1886. // middle of some work, but don't want the handler to start calling
  1887. // other methods on the editor, which might be in an inconsistent
  1888. // state or simply not expect any other events to happen.
  1889. // signalLater looks whether there are any handlers, and schedules
  1890. // them to be executed when the last operation ends, or, if no
  1891. // operation is active, when a timeout fires.
  1892. function signalLater(emitter, type /*, values...*/) {
  1893. var arr = getHandlers(emitter, type);
  1894. if (!arr.length) { return }
  1895. var args = Array.prototype.slice.call(arguments, 2), list;
  1896. if (operationGroup) {
  1897. list = operationGroup.delayedCallbacks;
  1898. } else if (orphanDelayedCallbacks) {
  1899. list = orphanDelayedCallbacks;
  1900. } else {
  1901. list = orphanDelayedCallbacks = [];
  1902. setTimeout(fireOrphanDelayed, 0);
  1903. }
  1904. var loop = function ( i ) {
  1905. list.push(function () { return arr[i].apply(null, args); });
  1906. };
  1907. for (var i = 0; i < arr.length; ++i)
  1908. loop( i );
  1909. }
  1910. function fireOrphanDelayed() {
  1911. var delayed = orphanDelayedCallbacks;
  1912. orphanDelayedCallbacks = null;
  1913. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1914. }
  1915. // When an aspect of a line changes, a string is added to
  1916. // lineView.changes. This updates the relevant part of the line's
  1917. // DOM structure.
  1918. function updateLineForChanges(cm, lineView, lineN, dims) {
  1919. for (var j = 0; j < lineView.changes.length; j++) {
  1920. var type = lineView.changes[j];
  1921. if (type == "text") { updateLineText(cm, lineView); }
  1922. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1923. else if (type == "class") { updateLineClasses(cm, lineView); }
  1924. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1925. }
  1926. lineView.changes = null;
  1927. }
  1928. // Lines with gutter elements, widgets or a background class need to
  1929. // be wrapped, and have the extra elements added to the wrapper div
  1930. function ensureLineWrapped(lineView) {
  1931. if (lineView.node == lineView.text) {
  1932. lineView.node = elt("div", null, null, "position: relative");
  1933. if (lineView.text.parentNode)
  1934. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1935. lineView.node.appendChild(lineView.text);
  1936. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1937. }
  1938. return lineView.node
  1939. }
  1940. function updateLineBackground(cm, lineView) {
  1941. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1942. if (cls) { cls += " CodeMirror-linebackground"; }
  1943. if (lineView.background) {
  1944. if (cls) { lineView.background.className = cls; }
  1945. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1946. } else if (cls) {
  1947. var wrap = ensureLineWrapped(lineView);
  1948. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1949. cm.display.input.setUneditable(lineView.background);
  1950. }
  1951. }
  1952. // Wrapper around buildLineContent which will reuse the structure
  1953. // in display.externalMeasured when possible.
  1954. function getLineContent(cm, lineView) {
  1955. var ext = cm.display.externalMeasured;
  1956. if (ext && ext.line == lineView.line) {
  1957. cm.display.externalMeasured = null;
  1958. lineView.measure = ext.measure;
  1959. return ext.built
  1960. }
  1961. return buildLineContent(cm, lineView)
  1962. }
  1963. // Redraw the line's text. Interacts with the background and text
  1964. // classes because the mode may output tokens that influence these
  1965. // classes.
  1966. function updateLineText(cm, lineView) {
  1967. var cls = lineView.text.className;
  1968. var built = getLineContent(cm, lineView);
  1969. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1970. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1971. lineView.text = built.pre;
  1972. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1973. lineView.bgClass = built.bgClass;
  1974. lineView.textClass = built.textClass;
  1975. updateLineClasses(cm, lineView);
  1976. } else if (cls) {
  1977. lineView.text.className = cls;
  1978. }
  1979. }
  1980. function updateLineClasses(cm, lineView) {
  1981. updateLineBackground(cm, lineView);
  1982. if (lineView.line.wrapClass)
  1983. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1984. else if (lineView.node != lineView.text)
  1985. { lineView.node.className = ""; }
  1986. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1987. lineView.text.className = textClass || "";
  1988. }
  1989. function updateLineGutter(cm, lineView, lineN, dims) {
  1990. if (lineView.gutter) {
  1991. lineView.node.removeChild(lineView.gutter);
  1992. lineView.gutter = null;
  1993. }
  1994. if (lineView.gutterBackground) {
  1995. lineView.node.removeChild(lineView.gutterBackground);
  1996. lineView.gutterBackground = null;
  1997. }
  1998. if (lineView.line.gutterClass) {
  1999. var wrap = ensureLineWrapped(lineView);
  2000. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2001. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2002. cm.display.input.setUneditable(lineView.gutterBackground);
  2003. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2004. }
  2005. var markers = lineView.line.gutterMarkers;
  2006. if (cm.options.lineNumbers || markers) {
  2007. var wrap$1 = ensureLineWrapped(lineView);
  2008. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2009. gutterWrap.setAttribute("aria-hidden", "true");
  2010. cm.display.input.setUneditable(gutterWrap);
  2011. wrap$1.insertBefore(gutterWrap, lineView.text);
  2012. if (lineView.line.gutterClass)
  2013. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2014. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2015. { lineView.lineNumber = gutterWrap.appendChild(
  2016. elt("div", lineNumberFor(cm.options, lineN),
  2017. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2018. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2019. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2020. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2021. if (found)
  2022. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2023. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2024. } }
  2025. }
  2026. }
  2027. function updateLineWidgets(cm, lineView, dims) {
  2028. if (lineView.alignable) { lineView.alignable = null; }
  2029. var isWidget = classTest("CodeMirror-linewidget");
  2030. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2031. next = node.nextSibling;
  2032. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2033. }
  2034. insertLineWidgets(cm, lineView, dims);
  2035. }
  2036. // Build a line's DOM representation from scratch
  2037. function buildLineElement(cm, lineView, lineN, dims) {
  2038. var built = getLineContent(cm, lineView);
  2039. lineView.text = lineView.node = built.pre;
  2040. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2041. if (built.textClass) { lineView.textClass = built.textClass; }
  2042. updateLineClasses(cm, lineView);
  2043. updateLineGutter(cm, lineView, lineN, dims);
  2044. insertLineWidgets(cm, lineView, dims);
  2045. return lineView.node
  2046. }
  2047. // A lineView may contain multiple logical lines (when merged by
  2048. // collapsed spans). The widgets for all of them need to be drawn.
  2049. function insertLineWidgets(cm, lineView, dims) {
  2050. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2051. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2052. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2053. }
  2054. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2055. if (!line.widgets) { return }
  2056. var wrap = ensureLineWrapped(lineView);
  2057. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2058. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2059. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2060. positionLineWidget(widget, node, lineView, dims);
  2061. cm.display.input.setUneditable(node);
  2062. if (allowAbove && widget.above)
  2063. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2064. else
  2065. { wrap.appendChild(node); }
  2066. signalLater(widget, "redraw");
  2067. }
  2068. }
  2069. function positionLineWidget(widget, node, lineView, dims) {
  2070. if (widget.noHScroll) {
  2071. (lineView.alignable || (lineView.alignable = [])).push(node);
  2072. var width = dims.wrapperWidth;
  2073. node.style.left = dims.fixedPos + "px";
  2074. if (!widget.coverGutter) {
  2075. width -= dims.gutterTotalWidth;
  2076. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2077. }
  2078. node.style.width = width + "px";
  2079. }
  2080. if (widget.coverGutter) {
  2081. node.style.zIndex = 5;
  2082. node.style.position = "relative";
  2083. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2084. }
  2085. }
  2086. function widgetHeight(widget) {
  2087. if (widget.height != null) { return widget.height }
  2088. var cm = widget.doc.cm;
  2089. if (!cm) { return 0 }
  2090. if (!contains(document.body, widget.node)) {
  2091. var parentStyle = "position: relative;";
  2092. if (widget.coverGutter)
  2093. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2094. if (widget.noHScroll)
  2095. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2096. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2097. }
  2098. return widget.height = widget.node.parentNode.offsetHeight
  2099. }
  2100. // Return true when the given mouse event happened in a widget
  2101. function eventInWidget(display, e) {
  2102. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2103. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2104. (n.parentNode == display.sizer && n != display.mover))
  2105. { return true }
  2106. }
  2107. }
  2108. // POSITION MEASUREMENT
  2109. function paddingTop(display) {return display.lineSpace.offsetTop}
  2110. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2111. function paddingH(display) {
  2112. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2113. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2114. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2115. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2116. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2117. return data
  2118. }
  2119. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2120. function displayWidth(cm) {
  2121. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2122. }
  2123. function displayHeight(cm) {
  2124. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2125. }
  2126. // Ensure the lineView.wrapping.heights array is populated. This is
  2127. // an array of bottom offsets for the lines that make up a drawn
  2128. // line. When lineWrapping is on, there might be more than one
  2129. // height.
  2130. function ensureLineHeights(cm, lineView, rect) {
  2131. var wrapping = cm.options.lineWrapping;
  2132. var curWidth = wrapping && displayWidth(cm);
  2133. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2134. var heights = lineView.measure.heights = [];
  2135. if (wrapping) {
  2136. lineView.measure.width = curWidth;
  2137. var rects = lineView.text.firstChild.getClientRects();
  2138. for (var i = 0; i < rects.length - 1; i++) {
  2139. var cur = rects[i], next = rects[i + 1];
  2140. if (Math.abs(cur.bottom - next.bottom) > 2)
  2141. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2142. }
  2143. }
  2144. heights.push(rect.bottom - rect.top);
  2145. }
  2146. }
  2147. // Find a line map (mapping character offsets to text nodes) and a
  2148. // measurement cache for the given line number. (A line view might
  2149. // contain multiple lines when collapsed ranges are present.)
  2150. function mapFromLineView(lineView, line, lineN) {
  2151. if (lineView.line == line)
  2152. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2153. if (lineView.rest) {
  2154. for (var i = 0; i < lineView.rest.length; i++)
  2155. { if (lineView.rest[i] == line)
  2156. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2157. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2158. { if (lineNo(lineView.rest[i$1]) > lineN)
  2159. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2160. }
  2161. }
  2162. // Render a line into the hidden node display.externalMeasured. Used
  2163. // when measurement is needed for a line that's not in the viewport.
  2164. function updateExternalMeasurement(cm, line) {
  2165. line = visualLine(line);
  2166. var lineN = lineNo(line);
  2167. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2168. view.lineN = lineN;
  2169. var built = view.built = buildLineContent(cm, view);
  2170. view.text = built.pre;
  2171. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2172. return view
  2173. }
  2174. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2175. // for a given character.
  2176. function measureChar(cm, line, ch, bias) {
  2177. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2178. }
  2179. // Find a line view that corresponds to the given line number.
  2180. function findViewForLine(cm, lineN) {
  2181. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2182. { return cm.display.view[findViewIndex(cm, lineN)] }
  2183. var ext = cm.display.externalMeasured;
  2184. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2185. { return ext }
  2186. }
  2187. // Measurement can be split in two steps, the set-up work that
  2188. // applies to the whole line, and the measurement of the actual
  2189. // character. Functions like coordsChar, that need to do a lot of
  2190. // measurements in a row, can thus ensure that the set-up work is
  2191. // only done once.
  2192. function prepareMeasureForLine(cm, line) {
  2193. var lineN = lineNo(line);
  2194. var view = findViewForLine(cm, lineN);
  2195. if (view && !view.text) {
  2196. view = null;
  2197. } else if (view && view.changes) {
  2198. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2199. cm.curOp.forceUpdate = true;
  2200. }
  2201. if (!view)
  2202. { view = updateExternalMeasurement(cm, line); }
  2203. var info = mapFromLineView(view, line, lineN);
  2204. return {
  2205. line: line, view: view, rect: null,
  2206. map: info.map, cache: info.cache, before: info.before,
  2207. hasHeights: false
  2208. }
  2209. }
  2210. // Given a prepared measurement object, measures the position of an
  2211. // actual character (or fetches it from the cache).
  2212. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2213. if (prepared.before) { ch = -1; }
  2214. var key = ch + (bias || ""), found;
  2215. if (prepared.cache.hasOwnProperty(key)) {
  2216. found = prepared.cache[key];
  2217. } else {
  2218. if (!prepared.rect)
  2219. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2220. if (!prepared.hasHeights) {
  2221. ensureLineHeights(cm, prepared.view, prepared.rect);
  2222. prepared.hasHeights = true;
  2223. }
  2224. found = measureCharInner(cm, prepared, ch, bias);
  2225. if (!found.bogus) { prepared.cache[key] = found; }
  2226. }
  2227. return {left: found.left, right: found.right,
  2228. top: varHeight ? found.rtop : found.top,
  2229. bottom: varHeight ? found.rbottom : found.bottom}
  2230. }
  2231. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2232. function nodeAndOffsetInLineMap(map, ch, bias) {
  2233. var node, start, end, collapse, mStart, mEnd;
  2234. // First, search the line map for the text node corresponding to,
  2235. // or closest to, the target character.
  2236. for (var i = 0; i < map.length; i += 3) {
  2237. mStart = map[i];
  2238. mEnd = map[i + 1];
  2239. if (ch < mStart) {
  2240. start = 0; end = 1;
  2241. collapse = "left";
  2242. } else if (ch < mEnd) {
  2243. start = ch - mStart;
  2244. end = start + 1;
  2245. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2246. end = mEnd - mStart;
  2247. start = end - 1;
  2248. if (ch >= mEnd) { collapse = "right"; }
  2249. }
  2250. if (start != null) {
  2251. node = map[i + 2];
  2252. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2253. { collapse = bias; }
  2254. if (bias == "left" && start == 0)
  2255. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2256. node = map[(i -= 3) + 2];
  2257. collapse = "left";
  2258. } }
  2259. if (bias == "right" && start == mEnd - mStart)
  2260. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2261. node = map[(i += 3) + 2];
  2262. collapse = "right";
  2263. } }
  2264. break
  2265. }
  2266. }
  2267. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2268. }
  2269. function getUsefulRect(rects, bias) {
  2270. var rect = nullRect;
  2271. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2272. if ((rect = rects[i]).left != rect.right) { break }
  2273. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2274. if ((rect = rects[i$1]).left != rect.right) { break }
  2275. } }
  2276. return rect
  2277. }
  2278. function measureCharInner(cm, prepared, ch, bias) {
  2279. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2280. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2281. var rect;
  2282. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2283. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2284. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2285. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2286. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2287. { rect = node.parentNode.getBoundingClientRect(); }
  2288. else
  2289. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2290. if (rect.left || rect.right || start == 0) { break }
  2291. end = start;
  2292. start = start - 1;
  2293. collapse = "right";
  2294. }
  2295. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2296. } else { // If it is a widget, simply get the box for the whole widget.
  2297. if (start > 0) { collapse = bias = "right"; }
  2298. var rects;
  2299. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2300. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2301. else
  2302. { rect = node.getBoundingClientRect(); }
  2303. }
  2304. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2305. var rSpan = node.parentNode.getClientRects()[0];
  2306. if (rSpan)
  2307. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2308. else
  2309. { rect = nullRect; }
  2310. }
  2311. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2312. var mid = (rtop + rbot) / 2;
  2313. var heights = prepared.view.measure.heights;
  2314. var i = 0;
  2315. for (; i < heights.length - 1; i++)
  2316. { if (mid < heights[i]) { break } }
  2317. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2318. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2319. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2320. top: top, bottom: bot};
  2321. if (!rect.left && !rect.right) { result.bogus = true; }
  2322. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2323. return result
  2324. }
  2325. // Work around problem with bounding client rects on ranges being
  2326. // returned incorrectly when zoomed on IE10 and below.
  2327. function maybeUpdateRectForZooming(measure, rect) {
  2328. if (!window.screen || screen.logicalXDPI == null ||
  2329. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2330. { return rect }
  2331. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2332. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2333. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2334. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2335. }
  2336. function clearLineMeasurementCacheFor(lineView) {
  2337. if (lineView.measure) {
  2338. lineView.measure.cache = {};
  2339. lineView.measure.heights = null;
  2340. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2341. { lineView.measure.caches[i] = {}; } }
  2342. }
  2343. }
  2344. function clearLineMeasurementCache(cm) {
  2345. cm.display.externalMeasure = null;
  2346. removeChildren(cm.display.lineMeasure);
  2347. for (var i = 0; i < cm.display.view.length; i++)
  2348. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2349. }
  2350. function clearCaches(cm) {
  2351. clearLineMeasurementCache(cm);
  2352. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2353. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2354. cm.display.lineNumChars = null;
  2355. }
  2356. function pageScrollX(doc) {
  2357. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2358. // which causes page_Offset and bounding client rects to use
  2359. // different reference viewports and invalidate our calculations.
  2360. if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
  2361. return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
  2362. }
  2363. function pageScrollY(doc) {
  2364. if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
  2365. return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
  2366. }
  2367. function widgetTopHeight(lineObj) {
  2368. var ref = visualLine(lineObj);
  2369. var widgets = ref.widgets;
  2370. var height = 0;
  2371. if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
  2372. { height += widgetHeight(widgets[i]); } } }
  2373. return height
  2374. }
  2375. // Converts a {top, bottom, left, right} box from line-local
  2376. // coordinates into another coordinate system. Context may be one of
  2377. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2378. // or "page".
  2379. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2380. if (!includeWidgets) {
  2381. var height = widgetTopHeight(lineObj);
  2382. rect.top += height; rect.bottom += height;
  2383. }
  2384. if (context == "line") { return rect }
  2385. if (!context) { context = "local"; }
  2386. var yOff = heightAtLine(lineObj);
  2387. if (context == "local") { yOff += paddingTop(cm.display); }
  2388. else { yOff -= cm.display.viewOffset; }
  2389. if (context == "page" || context == "window") {
  2390. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2391. yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
  2392. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
  2393. rect.left += xOff; rect.right += xOff;
  2394. }
  2395. rect.top += yOff; rect.bottom += yOff;
  2396. return rect
  2397. }
  2398. // Coverts a box from "div" coords to another coordinate system.
  2399. // Context may be "window", "page", "div", or "local"./null.
  2400. function fromCoordSystem(cm, coords, context) {
  2401. if (context == "div") { return coords }
  2402. var left = coords.left, top = coords.top;
  2403. // First move into "page" coordinate system
  2404. if (context == "page") {
  2405. left -= pageScrollX(doc(cm));
  2406. top -= pageScrollY(doc(cm));
  2407. } else if (context == "local" || !context) {
  2408. var localBox = cm.display.sizer.getBoundingClientRect();
  2409. left += localBox.left;
  2410. top += localBox.top;
  2411. }
  2412. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2413. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2414. }
  2415. function charCoords(cm, pos, context, lineObj, bias) {
  2416. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2417. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2418. }
  2419. // Returns a box for a given cursor position, which may have an
  2420. // 'other' property containing the position of the secondary cursor
  2421. // on a bidi boundary.
  2422. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2423. // and after `char - 1` in writing order of `char - 1`
  2424. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2425. // and before `char` in writing order of `char`
  2426. // Examples (upper-case letters are RTL, lower-case are LTR):
  2427. // Pos(0, 1, ...)
  2428. // before after
  2429. // ab a|b a|b
  2430. // aB a|B aB|
  2431. // Ab |Ab A|b
  2432. // AB B|A B|A
  2433. // Every position after the last character on a line is considered to stick
  2434. // to the last character on the line.
  2435. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2436. lineObj = lineObj || getLine(cm.doc, pos.line);
  2437. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2438. function get(ch, right) {
  2439. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2440. if (right) { m.left = m.right; } else { m.right = m.left; }
  2441. return intoCoordSystem(cm, lineObj, m, context)
  2442. }
  2443. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2444. if (ch >= lineObj.text.length) {
  2445. ch = lineObj.text.length;
  2446. sticky = "before";
  2447. } else if (ch <= 0) {
  2448. ch = 0;
  2449. sticky = "after";
  2450. }
  2451. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2452. function getBidi(ch, partPos, invert) {
  2453. var part = order[partPos], right = part.level == 1;
  2454. return get(invert ? ch - 1 : ch, right != invert)
  2455. }
  2456. var partPos = getBidiPartAt(order, ch, sticky);
  2457. var other = bidiOther;
  2458. var val = getBidi(ch, partPos, sticky == "before");
  2459. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2460. return val
  2461. }
  2462. // Used to cheaply estimate the coordinates for a position. Used for
  2463. // intermediate scroll updates.
  2464. function estimateCoords(cm, pos) {
  2465. var left = 0;
  2466. pos = clipPos(cm.doc, pos);
  2467. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2468. var lineObj = getLine(cm.doc, pos.line);
  2469. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2470. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2471. }
  2472. // Positions returned by coordsChar contain some extra information.
  2473. // xRel is the relative x position of the input coordinates compared
  2474. // to the found position (so xRel > 0 means the coordinates are to
  2475. // the right of the character position, for example). When outside
  2476. // is true, that means the coordinates lie outside the line's
  2477. // vertical range.
  2478. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2479. var pos = Pos(line, ch, sticky);
  2480. pos.xRel = xRel;
  2481. if (outside) { pos.outside = outside; }
  2482. return pos
  2483. }
  2484. // Compute the character position closest to the given coordinates.
  2485. // Input must be lineSpace-local ("div" coordinate system).
  2486. function coordsChar(cm, x, y) {
  2487. var doc = cm.doc;
  2488. y += cm.display.viewOffset;
  2489. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2490. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2491. if (lineN > last)
  2492. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2493. if (x < 0) { x = 0; }
  2494. var lineObj = getLine(doc, lineN);
  2495. for (;;) {
  2496. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2497. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2498. if (!collapsed) { return found }
  2499. var rangeEnd = collapsed.find(1);
  2500. if (rangeEnd.line == lineN) { return rangeEnd }
  2501. lineObj = getLine(doc, lineN = rangeEnd.line);
  2502. }
  2503. }
  2504. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2505. y -= widgetTopHeight(lineObj);
  2506. var end = lineObj.text.length;
  2507. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2508. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2509. return {begin: begin, end: end}
  2510. }
  2511. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2512. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2513. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2514. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2515. }
  2516. // Returns true if the given side of a box is after the given
  2517. // coordinates, in top-to-bottom, left-to-right order.
  2518. function boxIsAfter(box, x, y, left) {
  2519. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2520. }
  2521. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2522. // Move y into line-local coordinate space
  2523. y -= heightAtLine(lineObj);
  2524. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2525. // When directly calling `measureCharPrepared`, we have to adjust
  2526. // for the widgets at this line.
  2527. var widgetHeight = widgetTopHeight(lineObj);
  2528. var begin = 0, end = lineObj.text.length, ltr = true;
  2529. var order = getOrder(lineObj, cm.doc.direction);
  2530. // If the line isn't plain left-to-right text, first figure out
  2531. // which bidi section the coordinates fall into.
  2532. if (order) {
  2533. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2534. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2535. ltr = part.level != 1;
  2536. // The awkward -1 offsets are needed because findFirst (called
  2537. // on these below) will treat its first bound as inclusive,
  2538. // second as exclusive, but we want to actually address the
  2539. // characters in the part's range
  2540. begin = ltr ? part.from : part.to - 1;
  2541. end = ltr ? part.to : part.from - 1;
  2542. }
  2543. // A binary search to find the first character whose bounding box
  2544. // starts after the coordinates. If we run across any whose box wrap
  2545. // the coordinates, store that.
  2546. var chAround = null, boxAround = null;
  2547. var ch = findFirst(function (ch) {
  2548. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2549. box.top += widgetHeight; box.bottom += widgetHeight;
  2550. if (!boxIsAfter(box, x, y, false)) { return false }
  2551. if (box.top <= y && box.left <= x) {
  2552. chAround = ch;
  2553. boxAround = box;
  2554. }
  2555. return true
  2556. }, begin, end);
  2557. var baseX, sticky, outside = false;
  2558. // If a box around the coordinates was found, use that
  2559. if (boxAround) {
  2560. // Distinguish coordinates nearer to the left or right side of the box
  2561. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2562. ch = chAround + (atStart ? 0 : 1);
  2563. sticky = atStart ? "after" : "before";
  2564. baseX = atLeft ? boxAround.left : boxAround.right;
  2565. } else {
  2566. // (Adjust for extended bound, if necessary.)
  2567. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2568. // To determine which side to associate with, get the box to the
  2569. // left of the character and compare it's vertical position to the
  2570. // coordinates
  2571. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2572. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2573. "after" : "before";
  2574. // Now get accurate coordinates for this place, in order to get a
  2575. // base X position
  2576. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2577. baseX = coords.left;
  2578. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2579. }
  2580. ch = skipExtendingChars(lineObj.text, ch, 1);
  2581. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2582. }
  2583. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2584. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2585. // situation, we can take this ordering to correspond to the visual
  2586. // ordering. This finds the first part whose end is after the given
  2587. // coordinates.
  2588. var index = findFirst(function (i) {
  2589. var part = order[i], ltr = part.level != 1;
  2590. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2591. "line", lineObj, preparedMeasure), x, y, true)
  2592. }, 0, order.length - 1);
  2593. var part = order[index];
  2594. // If this isn't the first part, the part's start is also after
  2595. // the coordinates, and the coordinates aren't on the same line as
  2596. // that start, move one part back.
  2597. if (index > 0) {
  2598. var ltr = part.level != 1;
  2599. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2600. "line", lineObj, preparedMeasure);
  2601. if (boxIsAfter(start, x, y, true) && start.top > y)
  2602. { part = order[index - 1]; }
  2603. }
  2604. return part
  2605. }
  2606. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2607. // In a wrapped line, rtl text on wrapping boundaries can do things
  2608. // that don't correspond to the ordering in our `order` array at
  2609. // all, so a binary search doesn't work, and we want to return a
  2610. // part that only spans one line so that the binary search in
  2611. // coordsCharInner is safe. As such, we first find the extent of the
  2612. // wrapped line, and then do a flat search in which we discard any
  2613. // spans that aren't on the line.
  2614. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2615. var begin = ref.begin;
  2616. var end = ref.end;
  2617. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2618. var part = null, closestDist = null;
  2619. for (var i = 0; i < order.length; i++) {
  2620. var p = order[i];
  2621. if (p.from >= end || p.to <= begin) { continue }
  2622. var ltr = p.level != 1;
  2623. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2624. // Weigh against spans ending before this, so that they are only
  2625. // picked if nothing ends after
  2626. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2627. if (!part || closestDist > dist) {
  2628. part = p;
  2629. closestDist = dist;
  2630. }
  2631. }
  2632. if (!part) { part = order[order.length - 1]; }
  2633. // Clip the part to the wrapped line.
  2634. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2635. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2636. return part
  2637. }
  2638. var measureText;
  2639. // Compute the default text height.
  2640. function textHeight(display) {
  2641. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2642. if (measureText == null) {
  2643. measureText = elt("pre", null, "CodeMirror-line-like");
  2644. // Measure a bunch of lines, for browsers that compute
  2645. // fractional heights.
  2646. for (var i = 0; i < 49; ++i) {
  2647. measureText.appendChild(document.createTextNode("x"));
  2648. measureText.appendChild(elt("br"));
  2649. }
  2650. measureText.appendChild(document.createTextNode("x"));
  2651. }
  2652. removeChildrenAndAdd(display.measure, measureText);
  2653. var height = measureText.offsetHeight / 50;
  2654. if (height > 3) { display.cachedTextHeight = height; }
  2655. removeChildren(display.measure);
  2656. return height || 1
  2657. }
  2658. // Compute the default character width.
  2659. function charWidth(display) {
  2660. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2661. var anchor = elt("span", "xxxxxxxxxx");
  2662. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2663. removeChildrenAndAdd(display.measure, pre);
  2664. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2665. if (width > 2) { display.cachedCharWidth = width; }
  2666. return width || 10
  2667. }
  2668. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2669. // view, so that we don't interleave reading and writing to the DOM.
  2670. function getDimensions(cm) {
  2671. var d = cm.display, left = {}, width = {};
  2672. var gutterLeft = d.gutters.clientLeft;
  2673. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2674. var id = cm.display.gutterSpecs[i].className;
  2675. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2676. width[id] = n.clientWidth;
  2677. }
  2678. return {fixedPos: compensateForHScroll(d),
  2679. gutterTotalWidth: d.gutters.offsetWidth,
  2680. gutterLeft: left,
  2681. gutterWidth: width,
  2682. wrapperWidth: d.wrapper.clientWidth}
  2683. }
  2684. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2685. // but using getBoundingClientRect to get a sub-pixel-accurate
  2686. // result.
  2687. function compensateForHScroll(display) {
  2688. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2689. }
  2690. // Returns a function that estimates the height of a line, to use as
  2691. // first approximation until the line becomes visible (and is thus
  2692. // properly measurable).
  2693. function estimateHeight(cm) {
  2694. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2695. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2696. return function (line) {
  2697. if (lineIsHidden(cm.doc, line)) { return 0 }
  2698. var widgetsHeight = 0;
  2699. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2700. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2701. } }
  2702. if (wrapping)
  2703. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2704. else
  2705. { return widgetsHeight + th }
  2706. }
  2707. }
  2708. function estimateLineHeights(cm) {
  2709. var doc = cm.doc, est = estimateHeight(cm);
  2710. doc.iter(function (line) {
  2711. var estHeight = est(line);
  2712. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2713. });
  2714. }
  2715. // Given a mouse event, find the corresponding position. If liberal
  2716. // is false, it checks whether a gutter or scrollbar was clicked,
  2717. // and returns null if it was. forRect is used by rectangular
  2718. // selections, and tries to estimate a character position even for
  2719. // coordinates beyond the right of the text.
  2720. function posFromMouse(cm, e, liberal, forRect) {
  2721. var display = cm.display;
  2722. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2723. var x, y, space = display.lineSpace.getBoundingClientRect();
  2724. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2725. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2726. catch (e$1) { return null }
  2727. var coords = coordsChar(cm, x, y), line;
  2728. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2729. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2730. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2731. }
  2732. return coords
  2733. }
  2734. // Find the view element corresponding to a given line. Return null
  2735. // when the line isn't visible.
  2736. function findViewIndex(cm, n) {
  2737. if (n >= cm.display.viewTo) { return null }
  2738. n -= cm.display.viewFrom;
  2739. if (n < 0) { return null }
  2740. var view = cm.display.view;
  2741. for (var i = 0; i < view.length; i++) {
  2742. n -= view[i].size;
  2743. if (n < 0) { return i }
  2744. }
  2745. }
  2746. // Updates the display.view data structure for a given change to the
  2747. // document. From and to are in pre-change coordinates. Lendiff is
  2748. // the amount of lines added or subtracted by the change. This is
  2749. // used for changes that span multiple lines, or change the way
  2750. // lines are divided into visual lines. regLineChange (below)
  2751. // registers single-line changes.
  2752. function regChange(cm, from, to, lendiff) {
  2753. if (from == null) { from = cm.doc.first; }
  2754. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2755. if (!lendiff) { lendiff = 0; }
  2756. var display = cm.display;
  2757. if (lendiff && to < display.viewTo &&
  2758. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2759. { display.updateLineNumbers = from; }
  2760. cm.curOp.viewChanged = true;
  2761. if (from >= display.viewTo) { // Change after
  2762. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2763. { resetView(cm); }
  2764. } else if (to <= display.viewFrom) { // Change before
  2765. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2766. resetView(cm);
  2767. } else {
  2768. display.viewFrom += lendiff;
  2769. display.viewTo += lendiff;
  2770. }
  2771. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2772. resetView(cm);
  2773. } else if (from <= display.viewFrom) { // Top overlap
  2774. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2775. if (cut) {
  2776. display.view = display.view.slice(cut.index);
  2777. display.viewFrom = cut.lineN;
  2778. display.viewTo += lendiff;
  2779. } else {
  2780. resetView(cm);
  2781. }
  2782. } else if (to >= display.viewTo) { // Bottom overlap
  2783. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2784. if (cut$1) {
  2785. display.view = display.view.slice(0, cut$1.index);
  2786. display.viewTo = cut$1.lineN;
  2787. } else {
  2788. resetView(cm);
  2789. }
  2790. } else { // Gap in the middle
  2791. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2792. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2793. if (cutTop && cutBot) {
  2794. display.view = display.view.slice(0, cutTop.index)
  2795. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2796. .concat(display.view.slice(cutBot.index));
  2797. display.viewTo += lendiff;
  2798. } else {
  2799. resetView(cm);
  2800. }
  2801. }
  2802. var ext = display.externalMeasured;
  2803. if (ext) {
  2804. if (to < ext.lineN)
  2805. { ext.lineN += lendiff; }
  2806. else if (from < ext.lineN + ext.size)
  2807. { display.externalMeasured = null; }
  2808. }
  2809. }
  2810. // Register a change to a single line. Type must be one of "text",
  2811. // "gutter", "class", "widget"
  2812. function regLineChange(cm, line, type) {
  2813. cm.curOp.viewChanged = true;
  2814. var display = cm.display, ext = cm.display.externalMeasured;
  2815. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2816. { display.externalMeasured = null; }
  2817. if (line < display.viewFrom || line >= display.viewTo) { return }
  2818. var lineView = display.view[findViewIndex(cm, line)];
  2819. if (lineView.node == null) { return }
  2820. var arr = lineView.changes || (lineView.changes = []);
  2821. if (indexOf(arr, type) == -1) { arr.push(type); }
  2822. }
  2823. // Clear the view.
  2824. function resetView(cm) {
  2825. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2826. cm.display.view = [];
  2827. cm.display.viewOffset = 0;
  2828. }
  2829. function viewCuttingPoint(cm, oldN, newN, dir) {
  2830. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2831. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2832. { return {index: index, lineN: newN} }
  2833. var n = cm.display.viewFrom;
  2834. for (var i = 0; i < index; i++)
  2835. { n += view[i].size; }
  2836. if (n != oldN) {
  2837. if (dir > 0) {
  2838. if (index == view.length - 1) { return null }
  2839. diff = (n + view[index].size) - oldN;
  2840. index++;
  2841. } else {
  2842. diff = n - oldN;
  2843. }
  2844. oldN += diff; newN += diff;
  2845. }
  2846. while (visualLineNo(cm.doc, newN) != newN) {
  2847. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2848. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2849. index += dir;
  2850. }
  2851. return {index: index, lineN: newN}
  2852. }
  2853. // Force the view to cover a given range, adding empty view element
  2854. // or clipping off existing ones as needed.
  2855. function adjustView(cm, from, to) {
  2856. var display = cm.display, view = display.view;
  2857. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2858. display.view = buildViewArray(cm, from, to);
  2859. display.viewFrom = from;
  2860. } else {
  2861. if (display.viewFrom > from)
  2862. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2863. else if (display.viewFrom < from)
  2864. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2865. display.viewFrom = from;
  2866. if (display.viewTo < to)
  2867. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2868. else if (display.viewTo > to)
  2869. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2870. }
  2871. display.viewTo = to;
  2872. }
  2873. // Count the number of lines in the view whose DOM representation is
  2874. // out of date (or nonexistent).
  2875. function countDirtyView(cm) {
  2876. var view = cm.display.view, dirty = 0;
  2877. for (var i = 0; i < view.length; i++) {
  2878. var lineView = view[i];
  2879. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2880. }
  2881. return dirty
  2882. }
  2883. function updateSelection(cm) {
  2884. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2885. }
  2886. function prepareSelection(cm, primary) {
  2887. if ( primary === void 0 ) primary = true;
  2888. var doc = cm.doc, result = {};
  2889. var curFragment = result.cursors = document.createDocumentFragment();
  2890. var selFragment = result.selection = document.createDocumentFragment();
  2891. var customCursor = cm.options.$customCursor;
  2892. if (customCursor) { primary = true; }
  2893. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2894. if (!primary && i == doc.sel.primIndex) { continue }
  2895. var range = doc.sel.ranges[i];
  2896. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2897. var collapsed = range.empty();
  2898. if (customCursor) {
  2899. var head = customCursor(cm, range);
  2900. if (head) { drawSelectionCursor(cm, head, curFragment); }
  2901. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  2902. drawSelectionCursor(cm, range.head, curFragment);
  2903. }
  2904. if (!collapsed)
  2905. { drawSelectionRange(cm, range, selFragment); }
  2906. }
  2907. return result
  2908. }
  2909. // Draws a cursor for the given range
  2910. function drawSelectionCursor(cm, head, output) {
  2911. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2912. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2913. cursor.style.left = pos.left + "px";
  2914. cursor.style.top = pos.top + "px";
  2915. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2916. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  2917. var charPos = charCoords(cm, head, "div", null, null);
  2918. var width = charPos.right - charPos.left;
  2919. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  2920. }
  2921. if (pos.other) {
  2922. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2923. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2924. otherCursor.style.display = "";
  2925. otherCursor.style.left = pos.other.left + "px";
  2926. otherCursor.style.top = pos.other.top + "px";
  2927. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2928. }
  2929. }
  2930. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2931. // Draws the given range as a highlighted selection
  2932. function drawSelectionRange(cm, range, output) {
  2933. var display = cm.display, doc = cm.doc;
  2934. var fragment = document.createDocumentFragment();
  2935. var padding = paddingH(cm.display), leftSide = padding.left;
  2936. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2937. var docLTR = doc.direction == "ltr";
  2938. function add(left, top, width, bottom) {
  2939. if (top < 0) { top = 0; }
  2940. top = Math.round(top);
  2941. bottom = Math.round(bottom);
  2942. 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")));
  2943. }
  2944. function drawForLine(line, fromArg, toArg) {
  2945. var lineObj = getLine(doc, line);
  2946. var lineLen = lineObj.text.length;
  2947. var start, end;
  2948. function coords(ch, bias) {
  2949. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2950. }
  2951. function wrapX(pos, dir, side) {
  2952. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2953. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2954. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2955. return coords(ch, prop)[prop]
  2956. }
  2957. var order = getOrder(lineObj, doc.direction);
  2958. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2959. var ltr = dir == "ltr";
  2960. var fromPos = coords(from, ltr ? "left" : "right");
  2961. var toPos = coords(to - 1, ltr ? "right" : "left");
  2962. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2963. var first = i == 0, last = !order || i == order.length - 1;
  2964. if (toPos.top - fromPos.top <= 3) { // Single line
  2965. var openLeft = (docLTR ? openStart : openEnd) && first;
  2966. var openRight = (docLTR ? openEnd : openStart) && last;
  2967. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2968. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2969. add(left, fromPos.top, right - left, fromPos.bottom);
  2970. } else { // Multiple lines
  2971. var topLeft, topRight, botLeft, botRight;
  2972. if (ltr) {
  2973. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2974. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2975. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2976. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2977. } else {
  2978. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2979. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2980. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2981. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2982. }
  2983. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2984. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2985. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2986. }
  2987. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2988. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2989. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2990. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2991. });
  2992. return {start: start, end: end}
  2993. }
  2994. var sFrom = range.from(), sTo = range.to();
  2995. if (sFrom.line == sTo.line) {
  2996. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2997. } else {
  2998. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2999. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  3000. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  3001. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  3002. if (singleVLine) {
  3003. if (leftEnd.top < rightStart.top - 2) {
  3004. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  3005. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  3006. } else {
  3007. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3008. }
  3009. }
  3010. if (leftEnd.bottom < rightStart.top)
  3011. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3012. }
  3013. output.appendChild(fragment);
  3014. }
  3015. // Cursor-blinking
  3016. function restartBlink(cm) {
  3017. if (!cm.state.focused) { return }
  3018. var display = cm.display;
  3019. clearInterval(display.blinker);
  3020. var on = true;
  3021. display.cursorDiv.style.visibility = "";
  3022. if (cm.options.cursorBlinkRate > 0)
  3023. { display.blinker = setInterval(function () {
  3024. if (!cm.hasFocus()) { onBlur(cm); }
  3025. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3026. }, cm.options.cursorBlinkRate); }
  3027. else if (cm.options.cursorBlinkRate < 0)
  3028. { display.cursorDiv.style.visibility = "hidden"; }
  3029. }
  3030. function ensureFocus(cm) {
  3031. if (!cm.hasFocus()) {
  3032. cm.display.input.focus();
  3033. if (!cm.state.focused) { onFocus(cm); }
  3034. }
  3035. }
  3036. function delayBlurEvent(cm) {
  3037. cm.state.delayingBlurEvent = true;
  3038. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3039. cm.state.delayingBlurEvent = false;
  3040. if (cm.state.focused) { onBlur(cm); }
  3041. } }, 100);
  3042. }
  3043. function onFocus(cm, e) {
  3044. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3045. if (cm.options.readOnly == "nocursor") { return }
  3046. if (!cm.state.focused) {
  3047. signal(cm, "focus", cm, e);
  3048. cm.state.focused = true;
  3049. addClass(cm.display.wrapper, "CodeMirror-focused");
  3050. // This test prevents this from firing when a context
  3051. // menu is closed (since the input reset would kill the
  3052. // select-all detection hack)
  3053. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3054. cm.display.input.reset();
  3055. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3056. }
  3057. cm.display.input.receivedFocus();
  3058. }
  3059. restartBlink(cm);
  3060. }
  3061. function onBlur(cm, e) {
  3062. if (cm.state.delayingBlurEvent) { return }
  3063. if (cm.state.focused) {
  3064. signal(cm, "blur", cm, e);
  3065. cm.state.focused = false;
  3066. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3067. }
  3068. clearInterval(cm.display.blinker);
  3069. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3070. }
  3071. // Read the actual heights of the rendered lines, and update their
  3072. // stored heights to match.
  3073. function updateHeightsInViewport(cm) {
  3074. var display = cm.display;
  3075. var prevBottom = display.lineDiv.offsetTop;
  3076. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  3077. var oldHeight = display.lineDiv.getBoundingClientRect().top;
  3078. var mustScroll = 0;
  3079. for (var i = 0; i < display.view.length; i++) {
  3080. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3081. var height = (void 0), width = 0;
  3082. if (cur.hidden) { continue }
  3083. oldHeight += cur.line.height;
  3084. if (ie && ie_version < 8) {
  3085. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3086. height = bot - prevBottom;
  3087. prevBottom = bot;
  3088. } else {
  3089. var box = cur.node.getBoundingClientRect();
  3090. height = box.bottom - box.top;
  3091. // Check that lines don't extend past the right of the current
  3092. // editor width
  3093. if (!wrapping && cur.text.firstChild)
  3094. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3095. }
  3096. var diff = cur.line.height - height;
  3097. if (diff > .005 || diff < -.005) {
  3098. if (oldHeight < viewTop) { mustScroll -= diff; }
  3099. updateLineHeight(cur.line, height);
  3100. updateWidgetHeight(cur.line);
  3101. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3102. { updateWidgetHeight(cur.rest[j]); } }
  3103. }
  3104. if (width > cm.display.sizerWidth) {
  3105. var chWidth = Math.ceil(width / charWidth(cm.display));
  3106. if (chWidth > cm.display.maxLineLength) {
  3107. cm.display.maxLineLength = chWidth;
  3108. cm.display.maxLine = cur.line;
  3109. cm.display.maxLineChanged = true;
  3110. }
  3111. }
  3112. }
  3113. if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  3114. }
  3115. // Read and store the height of line widgets associated with the
  3116. // given line.
  3117. function updateWidgetHeight(line) {
  3118. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3119. var w = line.widgets[i], parent = w.node.parentNode;
  3120. if (parent) { w.height = parent.offsetHeight; }
  3121. } }
  3122. }
  3123. // Compute the lines that are visible in a given viewport (defaults
  3124. // the the current scroll position). viewport may contain top,
  3125. // height, and ensure (see op.scrollToPos) properties.
  3126. function visibleLines(display, doc, viewport) {
  3127. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3128. top = Math.floor(top - paddingTop(display));
  3129. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3130. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3131. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3132. // forces those lines into the viewport (if possible).
  3133. if (viewport && viewport.ensure) {
  3134. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3135. if (ensureFrom < from) {
  3136. from = ensureFrom;
  3137. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3138. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3139. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3140. to = ensureTo;
  3141. }
  3142. }
  3143. return {from: from, to: Math.max(to, from + 1)}
  3144. }
  3145. // SCROLLING THINGS INTO VIEW
  3146. // If an editor sits on the top or bottom of the window, partially
  3147. // scrolled out of view, this ensures that the cursor is visible.
  3148. function maybeScrollWindow(cm, rect) {
  3149. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3150. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3151. var doc = display.wrapper.ownerDocument;
  3152. if (rect.top + box.top < 0) { doScroll = true; }
  3153. else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
  3154. if (doScroll != null && !phantom) {
  3155. 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;"));
  3156. cm.display.lineSpace.appendChild(scrollNode);
  3157. scrollNode.scrollIntoView(doScroll);
  3158. cm.display.lineSpace.removeChild(scrollNode);
  3159. }
  3160. }
  3161. // Scroll a given position into view (immediately), verifying that
  3162. // it actually became visible (as line heights are accurately
  3163. // measured, the position of something may 'drift' during drawing).
  3164. function scrollPosIntoView(cm, pos, end, margin) {
  3165. if (margin == null) { margin = 0; }
  3166. var rect;
  3167. if (!cm.options.lineWrapping && pos == end) {
  3168. // Set pos and end to the cursor positions around the character pos sticks to
  3169. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3170. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3171. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3172. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3173. }
  3174. for (var limit = 0; limit < 5; limit++) {
  3175. var changed = false;
  3176. var coords = cursorCoords(cm, pos);
  3177. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3178. rect = {left: Math.min(coords.left, endCoords.left),
  3179. top: Math.min(coords.top, endCoords.top) - margin,
  3180. right: Math.max(coords.left, endCoords.left),
  3181. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3182. var scrollPos = calculateScrollPos(cm, rect);
  3183. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3184. if (scrollPos.scrollTop != null) {
  3185. updateScrollTop(cm, scrollPos.scrollTop);
  3186. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3187. }
  3188. if (scrollPos.scrollLeft != null) {
  3189. setScrollLeft(cm, scrollPos.scrollLeft);
  3190. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3191. }
  3192. if (!changed) { break }
  3193. }
  3194. return rect
  3195. }
  3196. // Scroll a given set of coordinates into view (immediately).
  3197. function scrollIntoView(cm, rect) {
  3198. var scrollPos = calculateScrollPos(cm, rect);
  3199. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3200. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3201. }
  3202. // Calculate a new scroll position needed to scroll the given
  3203. // rectangle into view. Returns an object with scrollTop and
  3204. // scrollLeft properties. When these are undefined, the
  3205. // vertical/horizontal position does not need to be adjusted.
  3206. function calculateScrollPos(cm, rect) {
  3207. var display = cm.display, snapMargin = textHeight(cm.display);
  3208. if (rect.top < 0) { rect.top = 0; }
  3209. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3210. var screen = displayHeight(cm), result = {};
  3211. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3212. var docBottom = cm.doc.height + paddingVert(display);
  3213. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3214. if (rect.top < screentop) {
  3215. result.scrollTop = atTop ? 0 : rect.top;
  3216. } else if (rect.bottom > screentop + screen) {
  3217. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3218. if (newTop != screentop) { result.scrollTop = newTop; }
  3219. }
  3220. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3221. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3222. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3223. var tooWide = rect.right - rect.left > screenw;
  3224. if (tooWide) { rect.right = rect.left + screenw; }
  3225. if (rect.left < 10)
  3226. { result.scrollLeft = 0; }
  3227. else if (rect.left < screenleft)
  3228. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3229. else if (rect.right > screenw + screenleft - 3)
  3230. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3231. return result
  3232. }
  3233. // Store a relative adjustment to the scroll position in the current
  3234. // operation (to be applied when the operation finishes).
  3235. function addToScrollTop(cm, top) {
  3236. if (top == null) { return }
  3237. resolveScrollToPos(cm);
  3238. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3239. }
  3240. // Make sure that at the end of the operation the current cursor is
  3241. // shown.
  3242. function ensureCursorVisible(cm) {
  3243. resolveScrollToPos(cm);
  3244. var cur = cm.getCursor();
  3245. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3246. }
  3247. function scrollToCoords(cm, x, y) {
  3248. if (x != null || y != null) { resolveScrollToPos(cm); }
  3249. if (x != null) { cm.curOp.scrollLeft = x; }
  3250. if (y != null) { cm.curOp.scrollTop = y; }
  3251. }
  3252. function scrollToRange(cm, range) {
  3253. resolveScrollToPos(cm);
  3254. cm.curOp.scrollToPos = range;
  3255. }
  3256. // When an operation has its scrollToPos property set, and another
  3257. // scroll action is applied before the end of the operation, this
  3258. // 'simulates' scrolling that position into view in a cheap way, so
  3259. // that the effect of intermediate scroll commands is not ignored.
  3260. function resolveScrollToPos(cm) {
  3261. var range = cm.curOp.scrollToPos;
  3262. if (range) {
  3263. cm.curOp.scrollToPos = null;
  3264. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3265. scrollToCoordsRange(cm, from, to, range.margin);
  3266. }
  3267. }
  3268. function scrollToCoordsRange(cm, from, to, margin) {
  3269. var sPos = calculateScrollPos(cm, {
  3270. left: Math.min(from.left, to.left),
  3271. top: Math.min(from.top, to.top) - margin,
  3272. right: Math.max(from.right, to.right),
  3273. bottom: Math.max(from.bottom, to.bottom) + margin
  3274. });
  3275. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3276. }
  3277. // Sync the scrollable area and scrollbars, ensure the viewport
  3278. // covers the visible area.
  3279. function updateScrollTop(cm, val) {
  3280. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3281. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3282. setScrollTop(cm, val, true);
  3283. if (gecko) { updateDisplaySimple(cm); }
  3284. startWorker(cm, 100);
  3285. }
  3286. function setScrollTop(cm, val, forceScroll) {
  3287. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3288. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3289. cm.doc.scrollTop = val;
  3290. cm.display.scrollbars.setScrollTop(val);
  3291. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3292. }
  3293. // Sync scroller and scrollbar, ensure the gutter elements are
  3294. // aligned.
  3295. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3296. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3297. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3298. cm.doc.scrollLeft = val;
  3299. alignHorizontally(cm);
  3300. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3301. cm.display.scrollbars.setScrollLeft(val);
  3302. }
  3303. // SCROLLBARS
  3304. // Prepare DOM reads needed to update the scrollbars. Done in one
  3305. // shot to minimize update/measure roundtrips.
  3306. function measureForScrollbars(cm) {
  3307. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3308. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3309. return {
  3310. clientHeight: d.scroller.clientHeight,
  3311. viewHeight: d.wrapper.clientHeight,
  3312. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3313. viewWidth: d.wrapper.clientWidth,
  3314. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3315. docHeight: docH,
  3316. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3317. nativeBarWidth: d.nativeBarWidth,
  3318. gutterWidth: gutterW
  3319. }
  3320. }
  3321. var NativeScrollbars = function(place, scroll, cm) {
  3322. this.cm = cm;
  3323. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3324. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3325. vert.tabIndex = horiz.tabIndex = -1;
  3326. place(vert); place(horiz);
  3327. on(vert, "scroll", function () {
  3328. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3329. });
  3330. on(horiz, "scroll", function () {
  3331. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3332. });
  3333. this.checkedZeroWidth = false;
  3334. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3335. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3336. };
  3337. NativeScrollbars.prototype.update = function (measure) {
  3338. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3339. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3340. var sWidth = measure.nativeBarWidth;
  3341. if (needsV) {
  3342. this.vert.style.display = "block";
  3343. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3344. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3345. // A bug in IE8 can cause this value to be negative, so guard it.
  3346. this.vert.firstChild.style.height =
  3347. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3348. } else {
  3349. this.vert.scrollTop = 0;
  3350. this.vert.style.display = "";
  3351. this.vert.firstChild.style.height = "0";
  3352. }
  3353. if (needsH) {
  3354. this.horiz.style.display = "block";
  3355. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3356. this.horiz.style.left = measure.barLeft + "px";
  3357. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3358. this.horiz.firstChild.style.width =
  3359. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3360. } else {
  3361. this.horiz.style.display = "";
  3362. this.horiz.firstChild.style.width = "0";
  3363. }
  3364. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3365. if (sWidth == 0) { this.zeroWidthHack(); }
  3366. this.checkedZeroWidth = true;
  3367. }
  3368. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3369. };
  3370. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3371. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3372. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3373. };
  3374. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3375. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3376. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3377. };
  3378. NativeScrollbars.prototype.zeroWidthHack = function () {
  3379. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3380. this.horiz.style.height = this.vert.style.width = w;
  3381. this.horiz.style.visibility = this.vert.style.visibility = "hidden";
  3382. this.disableHoriz = new Delayed;
  3383. this.disableVert = new Delayed;
  3384. };
  3385. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3386. bar.style.visibility = "";
  3387. function maybeDisable() {
  3388. // To find out whether the scrollbar is still visible, we
  3389. // check whether the element under the pixel in the bottom
  3390. // right corner of the scrollbar box is the scrollbar box
  3391. // itself (when the bar is still visible) or its filler child
  3392. // (when the bar is hidden). If it is still visible, we keep
  3393. // it enabled, if it's hidden, we disable pointer events.
  3394. var box = bar.getBoundingClientRect();
  3395. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3396. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3397. if (elt != bar) { bar.style.visibility = "hidden"; }
  3398. else { delay.set(1000, maybeDisable); }
  3399. }
  3400. delay.set(1000, maybeDisable);
  3401. };
  3402. NativeScrollbars.prototype.clear = function () {
  3403. var parent = this.horiz.parentNode;
  3404. parent.removeChild(this.horiz);
  3405. parent.removeChild(this.vert);
  3406. };
  3407. var NullScrollbars = function () {};
  3408. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3409. NullScrollbars.prototype.setScrollLeft = function () {};
  3410. NullScrollbars.prototype.setScrollTop = function () {};
  3411. NullScrollbars.prototype.clear = function () {};
  3412. function updateScrollbars(cm, measure) {
  3413. if (!measure) { measure = measureForScrollbars(cm); }
  3414. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3415. updateScrollbarsInner(cm, measure);
  3416. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3417. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3418. { updateHeightsInViewport(cm); }
  3419. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3420. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3421. }
  3422. }
  3423. // Re-synchronize the fake scrollbars with the actual size of the
  3424. // content.
  3425. function updateScrollbarsInner(cm, measure) {
  3426. var d = cm.display;
  3427. var sizes = d.scrollbars.update(measure);
  3428. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3429. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3430. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3431. if (sizes.right && sizes.bottom) {
  3432. d.scrollbarFiller.style.display = "block";
  3433. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3434. d.scrollbarFiller.style.width = sizes.right + "px";
  3435. } else { d.scrollbarFiller.style.display = ""; }
  3436. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3437. d.gutterFiller.style.display = "block";
  3438. d.gutterFiller.style.height = sizes.bottom + "px";
  3439. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3440. } else { d.gutterFiller.style.display = ""; }
  3441. }
  3442. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3443. function initScrollbars(cm) {
  3444. if (cm.display.scrollbars) {
  3445. cm.display.scrollbars.clear();
  3446. if (cm.display.scrollbars.addClass)
  3447. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3448. }
  3449. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3450. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3451. // Prevent clicks in the scrollbars from killing focus
  3452. on(node, "mousedown", function () {
  3453. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3454. });
  3455. node.setAttribute("cm-not-content", "true");
  3456. }, function (pos, axis) {
  3457. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3458. else { updateScrollTop(cm, pos); }
  3459. }, cm);
  3460. if (cm.display.scrollbars.addClass)
  3461. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3462. }
  3463. // Operations are used to wrap a series of changes to the editor
  3464. // state in such a way that each change won't have to update the
  3465. // cursor and display (which would be awkward, slow, and
  3466. // error-prone). Instead, display updates are batched and then all
  3467. // combined and executed at once.
  3468. var nextOpId = 0;
  3469. // Start a new operation.
  3470. function startOperation(cm) {
  3471. cm.curOp = {
  3472. cm: cm,
  3473. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3474. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3475. forceUpdate: false, // Used to force a redraw
  3476. updateInput: 0, // Whether to reset the input textarea
  3477. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3478. changeObjs: null, // Accumulated changes, for firing change events
  3479. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3480. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3481. selectionChanged: false, // Whether the selection needs to be redrawn
  3482. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3483. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3484. scrollToPos: null, // Used to scroll to a specific position
  3485. focus: false,
  3486. id: ++nextOpId, // Unique ID
  3487. markArrays: null // Used by addMarkedSpan
  3488. };
  3489. pushOperation(cm.curOp);
  3490. }
  3491. // Finish an operation, updating the display and signalling delayed events
  3492. function endOperation(cm) {
  3493. var op = cm.curOp;
  3494. if (op) { finishOperation(op, function (group) {
  3495. for (var i = 0; i < group.ops.length; i++)
  3496. { group.ops[i].cm.curOp = null; }
  3497. endOperations(group);
  3498. }); }
  3499. }
  3500. // The DOM updates done when an operation finishes are batched so
  3501. // that the minimum number of relayouts are required.
  3502. function endOperations(group) {
  3503. var ops = group.ops;
  3504. for (var i = 0; i < ops.length; i++) // Read DOM
  3505. { endOperation_R1(ops[i]); }
  3506. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3507. { endOperation_W1(ops[i$1]); }
  3508. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3509. { endOperation_R2(ops[i$2]); }
  3510. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3511. { endOperation_W2(ops[i$3]); }
  3512. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3513. { endOperation_finish(ops[i$4]); }
  3514. }
  3515. function endOperation_R1(op) {
  3516. var cm = op.cm, display = cm.display;
  3517. maybeClipScrollbars(cm);
  3518. if (op.updateMaxLine) { findMaxLine(cm); }
  3519. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3520. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3521. op.scrollToPos.to.line >= display.viewTo) ||
  3522. display.maxLineChanged && cm.options.lineWrapping;
  3523. op.update = op.mustUpdate &&
  3524. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3525. }
  3526. function endOperation_W1(op) {
  3527. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3528. }
  3529. function endOperation_R2(op) {
  3530. var cm = op.cm, display = cm.display;
  3531. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3532. op.barMeasure = measureForScrollbars(cm);
  3533. // If the max line changed since it was last measured, measure it,
  3534. // and ensure the document's width matches it.
  3535. // updateDisplay_W2 will use these properties to do the actual resizing
  3536. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3537. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3538. cm.display.sizerWidth = op.adjustWidthTo;
  3539. op.barMeasure.scrollWidth =
  3540. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3541. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3542. }
  3543. if (op.updatedDisplay || op.selectionChanged)
  3544. { op.preparedSelection = display.input.prepareSelection(); }
  3545. }
  3546. function endOperation_W2(op) {
  3547. var cm = op.cm;
  3548. if (op.adjustWidthTo != null) {
  3549. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3550. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3551. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3552. cm.display.maxLineChanged = false;
  3553. }
  3554. var takeFocus = op.focus && op.focus == activeElt(root(cm));
  3555. if (op.preparedSelection)
  3556. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3557. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3558. { updateScrollbars(cm, op.barMeasure); }
  3559. if (op.updatedDisplay)
  3560. { setDocumentHeight(cm, op.barMeasure); }
  3561. if (op.selectionChanged) { restartBlink(cm); }
  3562. if (cm.state.focused && op.updateInput)
  3563. { cm.display.input.reset(op.typing); }
  3564. if (takeFocus) { ensureFocus(op.cm); }
  3565. }
  3566. function endOperation_finish(op) {
  3567. var cm = op.cm, display = cm.display, doc = cm.doc;
  3568. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3569. // Abort mouse wheel delta measurement, when scrolling explicitly
  3570. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3571. { display.wheelStartX = display.wheelStartY = null; }
  3572. // Propagate the scroll position to the actual DOM scroller
  3573. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3574. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3575. // If we need to scroll a specific position into view, do so.
  3576. if (op.scrollToPos) {
  3577. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3578. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3579. maybeScrollWindow(cm, rect);
  3580. }
  3581. // Fire events for markers that are hidden/unidden by editing or
  3582. // undoing
  3583. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3584. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3585. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3586. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3587. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3588. if (display.wrapper.offsetHeight)
  3589. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3590. // Fire change events, and delayed event handlers
  3591. if (op.changeObjs)
  3592. { signal(cm, "changes", cm, op.changeObjs); }
  3593. if (op.update)
  3594. { op.update.finish(); }
  3595. }
  3596. // Run the given function in an operation
  3597. function runInOp(cm, f) {
  3598. if (cm.curOp) { return f() }
  3599. startOperation(cm);
  3600. try { return f() }
  3601. finally { endOperation(cm); }
  3602. }
  3603. // Wraps a function in an operation. Returns the wrapped function.
  3604. function operation(cm, f) {
  3605. return function() {
  3606. if (cm.curOp) { return f.apply(cm, arguments) }
  3607. startOperation(cm);
  3608. try { return f.apply(cm, arguments) }
  3609. finally { endOperation(cm); }
  3610. }
  3611. }
  3612. // Used to add methods to editor and doc instances, wrapping them in
  3613. // operations.
  3614. function methodOp(f) {
  3615. return function() {
  3616. if (this.curOp) { return f.apply(this, arguments) }
  3617. startOperation(this);
  3618. try { return f.apply(this, arguments) }
  3619. finally { endOperation(this); }
  3620. }
  3621. }
  3622. function docMethodOp(f) {
  3623. return function() {
  3624. var cm = this.cm;
  3625. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3626. startOperation(cm);
  3627. try { return f.apply(this, arguments) }
  3628. finally { endOperation(cm); }
  3629. }
  3630. }
  3631. // HIGHLIGHT WORKER
  3632. function startWorker(cm, time) {
  3633. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3634. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3635. }
  3636. function highlightWorker(cm) {
  3637. var doc = cm.doc;
  3638. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3639. var end = +new Date + cm.options.workTime;
  3640. var context = getContextBefore(cm, doc.highlightFrontier);
  3641. var changedLines = [];
  3642. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3643. if (context.line >= cm.display.viewFrom) { // Visible
  3644. var oldStyles = line.styles;
  3645. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3646. var highlighted = highlightLine(cm, line, context, true);
  3647. if (resetState) { context.state = resetState; }
  3648. line.styles = highlighted.styles;
  3649. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3650. if (newCls) { line.styleClasses = newCls; }
  3651. else if (oldCls) { line.styleClasses = null; }
  3652. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3653. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3654. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3655. if (ischange) { changedLines.push(context.line); }
  3656. line.stateAfter = context.save();
  3657. context.nextLine();
  3658. } else {
  3659. if (line.text.length <= cm.options.maxHighlightLength)
  3660. { processLine(cm, line.text, context); }
  3661. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3662. context.nextLine();
  3663. }
  3664. if (+new Date > end) {
  3665. startWorker(cm, cm.options.workDelay);
  3666. return true
  3667. }
  3668. });
  3669. doc.highlightFrontier = context.line;
  3670. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3671. if (changedLines.length) { runInOp(cm, function () {
  3672. for (var i = 0; i < changedLines.length; i++)
  3673. { regLineChange(cm, changedLines[i], "text"); }
  3674. }); }
  3675. }
  3676. // DISPLAY DRAWING
  3677. var DisplayUpdate = function(cm, viewport, force) {
  3678. var display = cm.display;
  3679. this.viewport = viewport;
  3680. // Store some values that we'll need later (but don't want to force a relayout for)
  3681. this.visible = visibleLines(display, cm.doc, viewport);
  3682. this.editorIsHidden = !display.wrapper.offsetWidth;
  3683. this.wrapperHeight = display.wrapper.clientHeight;
  3684. this.wrapperWidth = display.wrapper.clientWidth;
  3685. this.oldDisplayWidth = displayWidth(cm);
  3686. this.force = force;
  3687. this.dims = getDimensions(cm);
  3688. this.events = [];
  3689. };
  3690. DisplayUpdate.prototype.signal = function (emitter, type) {
  3691. if (hasHandler(emitter, type))
  3692. { this.events.push(arguments); }
  3693. };
  3694. DisplayUpdate.prototype.finish = function () {
  3695. for (var i = 0; i < this.events.length; i++)
  3696. { signal.apply(null, this.events[i]); }
  3697. };
  3698. function maybeClipScrollbars(cm) {
  3699. var display = cm.display;
  3700. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3701. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3702. display.heightForcer.style.height = scrollGap(cm) + "px";
  3703. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3704. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3705. display.scrollbarsClipped = true;
  3706. }
  3707. }
  3708. function selectionSnapshot(cm) {
  3709. if (cm.hasFocus()) { return null }
  3710. var active = activeElt(root(cm));
  3711. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3712. var result = {activeElt: active};
  3713. if (window.getSelection) {
  3714. var sel = win(cm).getSelection();
  3715. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3716. result.anchorNode = sel.anchorNode;
  3717. result.anchorOffset = sel.anchorOffset;
  3718. result.focusNode = sel.focusNode;
  3719. result.focusOffset = sel.focusOffset;
  3720. }
  3721. }
  3722. return result
  3723. }
  3724. function restoreSelection(snapshot) {
  3725. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(rootNode(snapshot.activeElt))) { return }
  3726. snapshot.activeElt.focus();
  3727. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3728. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3729. var doc = snapshot.activeElt.ownerDocument;
  3730. var sel = doc.defaultView.getSelection(), range = doc.createRange();
  3731. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3732. range.collapse(false);
  3733. sel.removeAllRanges();
  3734. sel.addRange(range);
  3735. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3736. }
  3737. }
  3738. // Does the actual updating of the line display. Bails out
  3739. // (returning false) when there is nothing to be done and forced is
  3740. // false.
  3741. function updateDisplayIfNeeded(cm, update) {
  3742. var display = cm.display, doc = cm.doc;
  3743. if (update.editorIsHidden) {
  3744. resetView(cm);
  3745. return false
  3746. }
  3747. // Bail out if the visible area is already rendered and nothing changed.
  3748. if (!update.force &&
  3749. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3750. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3751. display.renderedView == display.view && countDirtyView(cm) == 0)
  3752. { return false }
  3753. if (maybeUpdateLineNumberWidth(cm)) {
  3754. resetView(cm);
  3755. update.dims = getDimensions(cm);
  3756. }
  3757. // Compute a suitable new viewport (from & to)
  3758. var end = doc.first + doc.size;
  3759. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3760. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3761. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3762. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3763. if (sawCollapsedSpans) {
  3764. from = visualLineNo(cm.doc, from);
  3765. to = visualLineEndNo(cm.doc, to);
  3766. }
  3767. var different = from != display.viewFrom || to != display.viewTo ||
  3768. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3769. adjustView(cm, from, to);
  3770. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3771. // Position the mover div to align with the current scroll position
  3772. cm.display.mover.style.top = display.viewOffset + "px";
  3773. var toUpdate = countDirtyView(cm);
  3774. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3775. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3776. { return false }
  3777. // For big changes, we hide the enclosing element during the
  3778. // update, since that speeds up the operations on most browsers.
  3779. var selSnapshot = selectionSnapshot(cm);
  3780. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3781. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3782. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3783. display.renderedView = display.view;
  3784. // There might have been a widget with a focused element that got
  3785. // hidden or updated, if so re-focus it.
  3786. restoreSelection(selSnapshot);
  3787. // Prevent selection and cursors from interfering with the scroll
  3788. // width and height.
  3789. removeChildren(display.cursorDiv);
  3790. removeChildren(display.selectionDiv);
  3791. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3792. if (different) {
  3793. display.lastWrapHeight = update.wrapperHeight;
  3794. display.lastWrapWidth = update.wrapperWidth;
  3795. startWorker(cm, 400);
  3796. }
  3797. display.updateLineNumbers = null;
  3798. return true
  3799. }
  3800. function postUpdateDisplay(cm, update) {
  3801. var viewport = update.viewport;
  3802. for (var first = true;; first = false) {
  3803. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3804. // Clip forced viewport to actual scrollable area.
  3805. if (viewport && viewport.top != null)
  3806. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3807. // Updated line heights might result in the drawn area not
  3808. // actually covering the viewport. Keep looping until it does.
  3809. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3810. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3811. { break }
  3812. } else if (first) {
  3813. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3814. }
  3815. if (!updateDisplayIfNeeded(cm, update)) { break }
  3816. updateHeightsInViewport(cm);
  3817. var barMeasure = measureForScrollbars(cm);
  3818. updateSelection(cm);
  3819. updateScrollbars(cm, barMeasure);
  3820. setDocumentHeight(cm, barMeasure);
  3821. update.force = false;
  3822. }
  3823. update.signal(cm, "update", cm);
  3824. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3825. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3826. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3827. }
  3828. }
  3829. function updateDisplaySimple(cm, viewport) {
  3830. var update = new DisplayUpdate(cm, viewport);
  3831. if (updateDisplayIfNeeded(cm, update)) {
  3832. updateHeightsInViewport(cm);
  3833. postUpdateDisplay(cm, update);
  3834. var barMeasure = measureForScrollbars(cm);
  3835. updateSelection(cm);
  3836. updateScrollbars(cm, barMeasure);
  3837. setDocumentHeight(cm, barMeasure);
  3838. update.finish();
  3839. }
  3840. }
  3841. // Sync the actual display DOM structure with display.view, removing
  3842. // nodes for lines that are no longer in view, and creating the ones
  3843. // that are not there yet, and updating the ones that are out of
  3844. // date.
  3845. function patchDisplay(cm, updateNumbersFrom, dims) {
  3846. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3847. var container = display.lineDiv, cur = container.firstChild;
  3848. function rm(node) {
  3849. var next = node.nextSibling;
  3850. // Works around a throw-scroll bug in OS X Webkit
  3851. if (webkit && mac && cm.display.currentWheelTarget == node)
  3852. { node.style.display = "none"; }
  3853. else
  3854. { node.parentNode.removeChild(node); }
  3855. return next
  3856. }
  3857. var view = display.view, lineN = display.viewFrom;
  3858. // Loop over the elements in the view, syncing cur (the DOM nodes
  3859. // in display.lineDiv) with the view as we go.
  3860. for (var i = 0; i < view.length; i++) {
  3861. var lineView = view[i];
  3862. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3863. var node = buildLineElement(cm, lineView, lineN, dims);
  3864. container.insertBefore(node, cur);
  3865. } else { // Already drawn
  3866. while (cur != lineView.node) { cur = rm(cur); }
  3867. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3868. updateNumbersFrom <= lineN && lineView.lineNumber;
  3869. if (lineView.changes) {
  3870. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3871. updateLineForChanges(cm, lineView, lineN, dims);
  3872. }
  3873. if (updateNumber) {
  3874. removeChildren(lineView.lineNumber);
  3875. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3876. }
  3877. cur = lineView.node.nextSibling;
  3878. }
  3879. lineN += lineView.size;
  3880. }
  3881. while (cur) { cur = rm(cur); }
  3882. }
  3883. function updateGutterSpace(display) {
  3884. var width = display.gutters.offsetWidth;
  3885. display.sizer.style.marginLeft = width + "px";
  3886. // Send an event to consumers responding to changes in gutter width.
  3887. signalLater(display, "gutterChanged", display);
  3888. }
  3889. function setDocumentHeight(cm, measure) {
  3890. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3891. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3892. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3893. }
  3894. // Re-align line numbers and gutter marks to compensate for
  3895. // horizontal scrolling.
  3896. function alignHorizontally(cm) {
  3897. var display = cm.display, view = display.view;
  3898. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3899. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3900. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3901. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3902. if (cm.options.fixedGutter) {
  3903. if (view[i].gutter)
  3904. { view[i].gutter.style.left = left; }
  3905. if (view[i].gutterBackground)
  3906. { view[i].gutterBackground.style.left = left; }
  3907. }
  3908. var align = view[i].alignable;
  3909. if (align) { for (var j = 0; j < align.length; j++)
  3910. { align[j].style.left = left; } }
  3911. } }
  3912. if (cm.options.fixedGutter)
  3913. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3914. }
  3915. // Used to ensure that the line number gutter is still the right
  3916. // size for the current document size. Returns true when an update
  3917. // is needed.
  3918. function maybeUpdateLineNumberWidth(cm) {
  3919. if (!cm.options.lineNumbers) { return false }
  3920. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3921. if (last.length != display.lineNumChars) {
  3922. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3923. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3924. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3925. display.lineGutter.style.width = "";
  3926. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3927. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3928. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3929. display.lineGutter.style.width = display.lineNumWidth + "px";
  3930. updateGutterSpace(cm.display);
  3931. return true
  3932. }
  3933. return false
  3934. }
  3935. function getGutters(gutters, lineNumbers) {
  3936. var result = [], sawLineNumbers = false;
  3937. for (var i = 0; i < gutters.length; i++) {
  3938. var name = gutters[i], style = null;
  3939. if (typeof name != "string") { style = name.style; name = name.className; }
  3940. if (name == "CodeMirror-linenumbers") {
  3941. if (!lineNumbers) { continue }
  3942. else { sawLineNumbers = true; }
  3943. }
  3944. result.push({className: name, style: style});
  3945. }
  3946. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3947. return result
  3948. }
  3949. // Rebuild the gutter elements, ensure the margin to the left of the
  3950. // code matches their width.
  3951. function renderGutters(display) {
  3952. var gutters = display.gutters, specs = display.gutterSpecs;
  3953. removeChildren(gutters);
  3954. display.lineGutter = null;
  3955. for (var i = 0; i < specs.length; ++i) {
  3956. var ref = specs[i];
  3957. var className = ref.className;
  3958. var style = ref.style;
  3959. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3960. if (style) { gElt.style.cssText = style; }
  3961. if (className == "CodeMirror-linenumbers") {
  3962. display.lineGutter = gElt;
  3963. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3964. }
  3965. }
  3966. gutters.style.display = specs.length ? "" : "none";
  3967. updateGutterSpace(display);
  3968. }
  3969. function updateGutters(cm) {
  3970. renderGutters(cm.display);
  3971. regChange(cm);
  3972. alignHorizontally(cm);
  3973. }
  3974. // The display handles the DOM integration, both for input reading
  3975. // and content drawing. It holds references to DOM nodes and
  3976. // display-related state.
  3977. function Display(place, doc, input, options) {
  3978. var d = this;
  3979. this.input = input;
  3980. // Covers bottom-right square when both scrollbars are present.
  3981. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3982. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3983. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3984. // and h scrollbar is present.
  3985. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3986. d.gutterFiller.setAttribute("cm-not-content", "true");
  3987. // Will contain the actual code, positioned to cover the viewport.
  3988. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3989. // Elements are added to these to represent selection and cursors.
  3990. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3991. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3992. // A visibility: hidden element used to find the size of things.
  3993. d.measure = elt("div", null, "CodeMirror-measure");
  3994. // When lines outside of the viewport are measured, they are drawn in this.
  3995. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3996. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3997. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3998. null, "position: relative; outline: none");
  3999. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  4000. // Moved around its parent to cover visible view.
  4001. d.mover = elt("div", [lines], null, "position: relative");
  4002. // Set to the height of the document, allowing scrolling.
  4003. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  4004. d.sizerWidth = null;
  4005. // Behavior of elts with overflow: auto and padding is
  4006. // inconsistent across browsers. This is used to ensure the
  4007. // scrollable area is big enough.
  4008. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  4009. // Will contain the gutters, if any.
  4010. d.gutters = elt("div", null, "CodeMirror-gutters");
  4011. d.lineGutter = null;
  4012. // Actual scrollable element.
  4013. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4014. d.scroller.setAttribute("tabIndex", "-1");
  4015. // The element in which the editor lives.
  4016. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4017. // See #6982. FIXME remove when this has been fixed for a while in Chrome
  4018. if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }
  4019. // This attribute is respected by automatic translation systems such as Google Translate,
  4020. // and may also be respected by tools used by human translators.
  4021. d.wrapper.setAttribute('translate', 'no');
  4022. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4023. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4024. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4025. if (place) {
  4026. if (place.appendChild) { place.appendChild(d.wrapper); }
  4027. else { place(d.wrapper); }
  4028. }
  4029. // Current rendered range (may be bigger than the view window).
  4030. d.viewFrom = d.viewTo = doc.first;
  4031. d.reportedViewFrom = d.reportedViewTo = doc.first;
  4032. // Information about the rendered lines.
  4033. d.view = [];
  4034. d.renderedView = null;
  4035. // Holds info about a single rendered line when it was rendered
  4036. // for measurement, while not in view.
  4037. d.externalMeasured = null;
  4038. // Empty space (in pixels) above the view
  4039. d.viewOffset = 0;
  4040. d.lastWrapHeight = d.lastWrapWidth = 0;
  4041. d.updateLineNumbers = null;
  4042. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4043. d.scrollbarsClipped = false;
  4044. // Used to only resize the line number gutter when necessary (when
  4045. // the amount of lines crosses a boundary that makes its width change)
  4046. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4047. // Set to true when a non-horizontal-scrolling line widget is
  4048. // added. As an optimization, line widget aligning is skipped when
  4049. // this is false.
  4050. d.alignWidgets = false;
  4051. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4052. // Tracks the maximum line length so that the horizontal scrollbar
  4053. // can be kept static when scrolling.
  4054. d.maxLine = null;
  4055. d.maxLineLength = 0;
  4056. d.maxLineChanged = false;
  4057. // Used for measuring wheel scrolling granularity
  4058. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4059. // True when shift is held down.
  4060. d.shift = false;
  4061. // Used to track whether anything happened since the context menu
  4062. // was opened.
  4063. d.selForContextMenu = null;
  4064. d.activeTouch = null;
  4065. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4066. renderGutters(d);
  4067. input.init(d);
  4068. }
  4069. // Since the delta values reported on mouse wheel events are
  4070. // unstandardized between browsers and even browser versions, and
  4071. // generally horribly unpredictable, this code starts by measuring
  4072. // the scroll effect that the first few mouse wheel events have,
  4073. // and, from that, detects the way it can convert deltas to pixel
  4074. // offsets afterwards.
  4075. //
  4076. // The reason we want to know the amount a wheel event will scroll
  4077. // is that it gives us a chance to update the display before the
  4078. // actual scrolling happens, reducing flickering.
  4079. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4080. // Fill in a browser-detected starting value on browsers where we
  4081. // know one. These don't have to be accurate -- the result of them
  4082. // being wrong would just be a slight flicker on the first wheel
  4083. // scroll (if it is large enough).
  4084. if (ie) { wheelPixelsPerUnit = -.53; }
  4085. else if (gecko) { wheelPixelsPerUnit = 15; }
  4086. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4087. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4088. function wheelEventDelta(e) {
  4089. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4090. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4091. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4092. else if (dy == null) { dy = e.wheelDelta; }
  4093. return {x: dx, y: dy}
  4094. }
  4095. function wheelEventPixels(e) {
  4096. var delta = wheelEventDelta(e);
  4097. delta.x *= wheelPixelsPerUnit;
  4098. delta.y *= wheelPixelsPerUnit;
  4099. return delta
  4100. }
  4101. function onScrollWheel(cm, e) {
  4102. // On Chrome 102, viewport updates somehow stop wheel-based
  4103. // scrolling. Turning off pointer events during the scroll seems
  4104. // to avoid the issue.
  4105. if (chrome && chrome_version == 102) {
  4106. if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
  4107. else { clearTimeout(cm.display.chromeScrollHack); }
  4108. cm.display.chromeScrollHack = setTimeout(function () {
  4109. cm.display.chromeScrollHack = null;
  4110. cm.display.sizer.style.pointerEvents = "";
  4111. }, 100);
  4112. }
  4113. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4114. var pixelsPerUnit = wheelPixelsPerUnit;
  4115. if (e.deltaMode === 0) {
  4116. dx = e.deltaX;
  4117. dy = e.deltaY;
  4118. pixelsPerUnit = 1;
  4119. }
  4120. var display = cm.display, scroll = display.scroller;
  4121. // Quit if there's nothing to scroll here
  4122. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4123. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4124. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4125. // Webkit browsers on OS X abort momentum scrolls when the target
  4126. // of the scroll event is removed from the scrollable element.
  4127. // This hack (see related code in patchDisplay) makes sure the
  4128. // element is kept around.
  4129. if (dy && mac && webkit) {
  4130. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4131. for (var i = 0; i < view.length; i++) {
  4132. if (view[i].node == cur) {
  4133. cm.display.currentWheelTarget = cur;
  4134. break outer
  4135. }
  4136. }
  4137. }
  4138. }
  4139. // On some browsers, horizontal scrolling will cause redraws to
  4140. // happen before the gutter has been realigned, causing it to
  4141. // wriggle around in a most unseemly way. When we have an
  4142. // estimated pixels/delta value, we just handle horizontal
  4143. // scrolling entirely here. It'll be slightly off from native, but
  4144. // better than glitching out.
  4145. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  4146. if (dy && canScrollY)
  4147. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  4148. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  4149. // Only prevent default scrolling if vertical scrolling is
  4150. // actually possible. Otherwise, it causes vertical scroll
  4151. // jitter on OSX trackpads when deltaX is small and deltaY
  4152. // is large (issue #3579)
  4153. if (!dy || (dy && canScrollY))
  4154. { e_preventDefault(e); }
  4155. display.wheelStartX = null; // Abort measurement, if in progress
  4156. return
  4157. }
  4158. // 'Project' the visible viewport to cover the area that is being
  4159. // scrolled into view (if we know enough to estimate it).
  4160. if (dy && pixelsPerUnit != null) {
  4161. var pixels = dy * pixelsPerUnit;
  4162. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4163. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4164. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4165. updateDisplaySimple(cm, {top: top, bottom: bot});
  4166. }
  4167. if (wheelSamples < 20 && e.deltaMode !== 0) {
  4168. if (display.wheelStartX == null) {
  4169. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4170. display.wheelDX = dx; display.wheelDY = dy;
  4171. setTimeout(function () {
  4172. if (display.wheelStartX == null) { return }
  4173. var movedX = scroll.scrollLeft - display.wheelStartX;
  4174. var movedY = scroll.scrollTop - display.wheelStartY;
  4175. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4176. (movedX && display.wheelDX && movedX / display.wheelDX);
  4177. display.wheelStartX = display.wheelStartY = null;
  4178. if (!sample) { return }
  4179. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4180. ++wheelSamples;
  4181. }, 200);
  4182. } else {
  4183. display.wheelDX += dx; display.wheelDY += dy;
  4184. }
  4185. }
  4186. }
  4187. // Selection objects are immutable. A new one is created every time
  4188. // the selection changes. A selection is one or more non-overlapping
  4189. // (and non-touching) ranges, sorted, and an integer that indicates
  4190. // which one is the primary selection (the one that's scrolled into
  4191. // view, that getCursor returns, etc).
  4192. var Selection = function(ranges, primIndex) {
  4193. this.ranges = ranges;
  4194. this.primIndex = primIndex;
  4195. };
  4196. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4197. Selection.prototype.equals = function (other) {
  4198. if (other == this) { return true }
  4199. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4200. for (var i = 0; i < this.ranges.length; i++) {
  4201. var here = this.ranges[i], there = other.ranges[i];
  4202. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4203. }
  4204. return true
  4205. };
  4206. Selection.prototype.deepCopy = function () {
  4207. var out = [];
  4208. for (var i = 0; i < this.ranges.length; i++)
  4209. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4210. return new Selection(out, this.primIndex)
  4211. };
  4212. Selection.prototype.somethingSelected = function () {
  4213. for (var i = 0; i < this.ranges.length; i++)
  4214. { if (!this.ranges[i].empty()) { return true } }
  4215. return false
  4216. };
  4217. Selection.prototype.contains = function (pos, end) {
  4218. if (!end) { end = pos; }
  4219. for (var i = 0; i < this.ranges.length; i++) {
  4220. var range = this.ranges[i];
  4221. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4222. { return i }
  4223. }
  4224. return -1
  4225. };
  4226. var Range = function(anchor, head) {
  4227. this.anchor = anchor; this.head = head;
  4228. };
  4229. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4230. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4231. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4232. // Take an unsorted, potentially overlapping set of ranges, and
  4233. // build a selection out of it. 'Consumes' ranges array (modifying
  4234. // it).
  4235. function normalizeSelection(cm, ranges, primIndex) {
  4236. var mayTouch = cm && cm.options.selectionsMayTouch;
  4237. var prim = ranges[primIndex];
  4238. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4239. primIndex = indexOf(ranges, prim);
  4240. for (var i = 1; i < ranges.length; i++) {
  4241. var cur = ranges[i], prev = ranges[i - 1];
  4242. var diff = cmp(prev.to(), cur.from());
  4243. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4244. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4245. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4246. if (i <= primIndex) { --primIndex; }
  4247. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4248. }
  4249. }
  4250. return new Selection(ranges, primIndex)
  4251. }
  4252. function simpleSelection(anchor, head) {
  4253. return new Selection([new Range(anchor, head || anchor)], 0)
  4254. }
  4255. // Compute the position of the end of a change (its 'to' property
  4256. // refers to the pre-change end).
  4257. function changeEnd(change) {
  4258. if (!change.text) { return change.to }
  4259. return Pos(change.from.line + change.text.length - 1,
  4260. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4261. }
  4262. // Adjust a position to refer to the post-change position of the
  4263. // same text, or the end of the change if the change covers it.
  4264. function adjustForChange(pos, change) {
  4265. if (cmp(pos, change.from) < 0) { return pos }
  4266. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4267. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4268. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4269. return Pos(line, ch)
  4270. }
  4271. function computeSelAfterChange(doc, change) {
  4272. var out = [];
  4273. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4274. var range = doc.sel.ranges[i];
  4275. out.push(new Range(adjustForChange(range.anchor, change),
  4276. adjustForChange(range.head, change)));
  4277. }
  4278. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4279. }
  4280. function offsetPos(pos, old, nw) {
  4281. if (pos.line == old.line)
  4282. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4283. else
  4284. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4285. }
  4286. // Used by replaceSelections to allow moving the selection to the
  4287. // start or around the replaced test. Hint may be "start" or "around".
  4288. function computeReplacedSel(doc, changes, hint) {
  4289. var out = [];
  4290. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4291. for (var i = 0; i < changes.length; i++) {
  4292. var change = changes[i];
  4293. var from = offsetPos(change.from, oldPrev, newPrev);
  4294. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4295. oldPrev = change.to;
  4296. newPrev = to;
  4297. if (hint == "around") {
  4298. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4299. out[i] = new Range(inv ? to : from, inv ? from : to);
  4300. } else {
  4301. out[i] = new Range(from, from);
  4302. }
  4303. }
  4304. return new Selection(out, doc.sel.primIndex)
  4305. }
  4306. // Used to get the editor into a consistent state again when options change.
  4307. function loadMode(cm) {
  4308. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4309. resetModeState(cm);
  4310. }
  4311. function resetModeState(cm) {
  4312. cm.doc.iter(function (line) {
  4313. if (line.stateAfter) { line.stateAfter = null; }
  4314. if (line.styles) { line.styles = null; }
  4315. });
  4316. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4317. startWorker(cm, 100);
  4318. cm.state.modeGen++;
  4319. if (cm.curOp) { regChange(cm); }
  4320. }
  4321. // DOCUMENT DATA STRUCTURE
  4322. // By default, updates that start and end at the beginning of a line
  4323. // are treated specially, in order to make the association of line
  4324. // widgets and marker elements with the text behave more intuitive.
  4325. function isWholeLineUpdate(doc, change) {
  4326. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4327. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4328. }
  4329. // Perform a change on the document data structure.
  4330. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4331. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4332. function update(line, text, spans) {
  4333. updateLine(line, text, spans, estimateHeight);
  4334. signalLater(line, "change", line, change);
  4335. }
  4336. function linesFor(start, end) {
  4337. var result = [];
  4338. for (var i = start; i < end; ++i)
  4339. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4340. return result
  4341. }
  4342. var from = change.from, to = change.to, text = change.text;
  4343. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4344. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4345. // Adjust the line structure
  4346. if (change.full) {
  4347. doc.insert(0, linesFor(0, text.length));
  4348. doc.remove(text.length, doc.size - text.length);
  4349. } else if (isWholeLineUpdate(doc, change)) {
  4350. // This is a whole-line replace. Treated specially to make
  4351. // sure line objects move the way they are supposed to.
  4352. var added = linesFor(0, text.length - 1);
  4353. update(lastLine, lastLine.text, lastSpans);
  4354. if (nlines) { doc.remove(from.line, nlines); }
  4355. if (added.length) { doc.insert(from.line, added); }
  4356. } else if (firstLine == lastLine) {
  4357. if (text.length == 1) {
  4358. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4359. } else {
  4360. var added$1 = linesFor(1, text.length - 1);
  4361. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4362. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4363. doc.insert(from.line + 1, added$1);
  4364. }
  4365. } else if (text.length == 1) {
  4366. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4367. doc.remove(from.line + 1, nlines);
  4368. } else {
  4369. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4370. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4371. var added$2 = linesFor(1, text.length - 1);
  4372. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4373. doc.insert(from.line + 1, added$2);
  4374. }
  4375. signalLater(doc, "change", doc, change);
  4376. }
  4377. // Call f for all linked documents.
  4378. function linkedDocs(doc, f, sharedHistOnly) {
  4379. function propagate(doc, skip, sharedHist) {
  4380. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4381. var rel = doc.linked[i];
  4382. if (rel.doc == skip) { continue }
  4383. var shared = sharedHist && rel.sharedHist;
  4384. if (sharedHistOnly && !shared) { continue }
  4385. f(rel.doc, shared);
  4386. propagate(rel.doc, doc, shared);
  4387. } }
  4388. }
  4389. propagate(doc, null, true);
  4390. }
  4391. // Attach a document to an editor.
  4392. function attachDoc(cm, doc) {
  4393. if (doc.cm) { throw new Error("This document is already in use.") }
  4394. cm.doc = doc;
  4395. doc.cm = cm;
  4396. estimateLineHeights(cm);
  4397. loadMode(cm);
  4398. setDirectionClass(cm);
  4399. cm.options.direction = doc.direction;
  4400. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4401. cm.options.mode = doc.modeOption;
  4402. regChange(cm);
  4403. }
  4404. function setDirectionClass(cm) {
  4405. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4406. }
  4407. function directionChanged(cm) {
  4408. runInOp(cm, function () {
  4409. setDirectionClass(cm);
  4410. regChange(cm);
  4411. });
  4412. }
  4413. function History(prev) {
  4414. // Arrays of change events and selections. Doing something adds an
  4415. // event to done and clears undo. Undoing moves events from done
  4416. // to undone, redoing moves them in the other direction.
  4417. this.done = []; this.undone = [];
  4418. this.undoDepth = prev ? prev.undoDepth : Infinity;
  4419. // Used to track when changes can be merged into a single undo
  4420. // event
  4421. this.lastModTime = this.lastSelTime = 0;
  4422. this.lastOp = this.lastSelOp = null;
  4423. this.lastOrigin = this.lastSelOrigin = null;
  4424. // Used by the isClean() method
  4425. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4426. }
  4427. // Create a history change event from an updateDoc-style change
  4428. // object.
  4429. function historyChangeFromChange(doc, change) {
  4430. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4431. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4432. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4433. return histChange
  4434. }
  4435. // Pop all selection events off the end of a history array. Stop at
  4436. // a change event.
  4437. function clearSelectionEvents(array) {
  4438. while (array.length) {
  4439. var last = lst(array);
  4440. if (last.ranges) { array.pop(); }
  4441. else { break }
  4442. }
  4443. }
  4444. // Find the top change event in the history. Pop off selection
  4445. // events that are in the way.
  4446. function lastChangeEvent(hist, force) {
  4447. if (force) {
  4448. clearSelectionEvents(hist.done);
  4449. return lst(hist.done)
  4450. } else if (hist.done.length && !lst(hist.done).ranges) {
  4451. return lst(hist.done)
  4452. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4453. hist.done.pop();
  4454. return lst(hist.done)
  4455. }
  4456. }
  4457. // Register a change in the history. Merges changes that are within
  4458. // a single operation, or are close together with an origin that
  4459. // allows merging (starting with "+") into a single event.
  4460. function addChangeToHistory(doc, change, selAfter, opId) {
  4461. var hist = doc.history;
  4462. hist.undone.length = 0;
  4463. var time = +new Date, cur;
  4464. var last;
  4465. if ((hist.lastOp == opId ||
  4466. hist.lastOrigin == change.origin && change.origin &&
  4467. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4468. change.origin.charAt(0) == "*")) &&
  4469. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4470. // Merge this change into the last event
  4471. last = lst(cur.changes);
  4472. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4473. // Optimized case for simple insertion -- don't want to add
  4474. // new changesets for every character typed
  4475. last.to = changeEnd(change);
  4476. } else {
  4477. // Add new sub-event
  4478. cur.changes.push(historyChangeFromChange(doc, change));
  4479. }
  4480. } else {
  4481. // Can not be merged, start a new event.
  4482. var before = lst(hist.done);
  4483. if (!before || !before.ranges)
  4484. { pushSelectionToHistory(doc.sel, hist.done); }
  4485. cur = {changes: [historyChangeFromChange(doc, change)],
  4486. generation: hist.generation};
  4487. hist.done.push(cur);
  4488. while (hist.done.length > hist.undoDepth) {
  4489. hist.done.shift();
  4490. if (!hist.done[0].ranges) { hist.done.shift(); }
  4491. }
  4492. }
  4493. hist.done.push(selAfter);
  4494. hist.generation = ++hist.maxGeneration;
  4495. hist.lastModTime = hist.lastSelTime = time;
  4496. hist.lastOp = hist.lastSelOp = opId;
  4497. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4498. if (!last) { signal(doc, "historyAdded"); }
  4499. }
  4500. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4501. var ch = origin.charAt(0);
  4502. return ch == "*" ||
  4503. ch == "+" &&
  4504. prev.ranges.length == sel.ranges.length &&
  4505. prev.somethingSelected() == sel.somethingSelected() &&
  4506. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4507. }
  4508. // Called whenever the selection changes, sets the new selection as
  4509. // the pending selection in the history, and pushes the old pending
  4510. // selection into the 'done' array when it was significantly
  4511. // different (in number of selected ranges, emptiness, or time).
  4512. function addSelectionToHistory(doc, sel, opId, options) {
  4513. var hist = doc.history, origin = options && options.origin;
  4514. // A new event is started when the previous origin does not match
  4515. // the current, or the origins don't allow matching. Origins
  4516. // starting with * are always merged, those starting with + are
  4517. // merged when similar and close together in time.
  4518. if (opId == hist.lastSelOp ||
  4519. (origin && hist.lastSelOrigin == origin &&
  4520. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4521. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4522. { hist.done[hist.done.length - 1] = sel; }
  4523. else
  4524. { pushSelectionToHistory(sel, hist.done); }
  4525. hist.lastSelTime = +new Date;
  4526. hist.lastSelOrigin = origin;
  4527. hist.lastSelOp = opId;
  4528. if (options && options.clearRedo !== false)
  4529. { clearSelectionEvents(hist.undone); }
  4530. }
  4531. function pushSelectionToHistory(sel, dest) {
  4532. var top = lst(dest);
  4533. if (!(top && top.ranges && top.equals(sel)))
  4534. { dest.push(sel); }
  4535. }
  4536. // Used to store marked span information in the history.
  4537. function attachLocalSpans(doc, change, from, to) {
  4538. var existing = change["spans_" + doc.id], n = 0;
  4539. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4540. if (line.markedSpans)
  4541. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4542. ++n;
  4543. });
  4544. }
  4545. // When un/re-doing restores text containing marked spans, those
  4546. // that have been explicitly cleared should not be restored.
  4547. function removeClearedSpans(spans) {
  4548. if (!spans) { return null }
  4549. var out;
  4550. for (var i = 0; i < spans.length; ++i) {
  4551. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4552. else if (out) { out.push(spans[i]); }
  4553. }
  4554. return !out ? spans : out.length ? out : null
  4555. }
  4556. // Retrieve and filter the old marked spans stored in a change event.
  4557. function getOldSpans(doc, change) {
  4558. var found = change["spans_" + doc.id];
  4559. if (!found) { return null }
  4560. var nw = [];
  4561. for (var i = 0; i < change.text.length; ++i)
  4562. { nw.push(removeClearedSpans(found[i])); }
  4563. return nw
  4564. }
  4565. // Used for un/re-doing changes from the history. Combines the
  4566. // result of computing the existing spans with the set of spans that
  4567. // existed in the history (so that deleting around a span and then
  4568. // undoing brings back the span).
  4569. function mergeOldSpans(doc, change) {
  4570. var old = getOldSpans(doc, change);
  4571. var stretched = stretchSpansOverChange(doc, change);
  4572. if (!old) { return stretched }
  4573. if (!stretched) { return old }
  4574. for (var i = 0; i < old.length; ++i) {
  4575. var oldCur = old[i], stretchCur = stretched[i];
  4576. if (oldCur && stretchCur) {
  4577. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4578. var span = stretchCur[j];
  4579. for (var k = 0; k < oldCur.length; ++k)
  4580. { if (oldCur[k].marker == span.marker) { continue spans } }
  4581. oldCur.push(span);
  4582. }
  4583. } else if (stretchCur) {
  4584. old[i] = stretchCur;
  4585. }
  4586. }
  4587. return old
  4588. }
  4589. // Used both to provide a JSON-safe object in .getHistory, and, when
  4590. // detaching a document, to split the history in two
  4591. function copyHistoryArray(events, newGroup, instantiateSel) {
  4592. var copy = [];
  4593. for (var i = 0; i < events.length; ++i) {
  4594. var event = events[i];
  4595. if (event.ranges) {
  4596. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4597. continue
  4598. }
  4599. var changes = event.changes, newChanges = [];
  4600. copy.push({changes: newChanges});
  4601. for (var j = 0; j < changes.length; ++j) {
  4602. var change = changes[j], m = (void 0);
  4603. newChanges.push({from: change.from, to: change.to, text: change.text});
  4604. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4605. if (indexOf(newGroup, Number(m[1])) > -1) {
  4606. lst(newChanges)[prop] = change[prop];
  4607. delete change[prop];
  4608. }
  4609. } } }
  4610. }
  4611. }
  4612. return copy
  4613. }
  4614. // The 'scroll' parameter given to many of these indicated whether
  4615. // the new cursor position should be scrolled into view after
  4616. // modifying the selection.
  4617. // If shift is held or the extend flag is set, extends a range to
  4618. // include a given position (and optionally a second position).
  4619. // Otherwise, simply returns the range between the given positions.
  4620. // Used for cursor motion and such.
  4621. function extendRange(range, head, other, extend) {
  4622. if (extend) {
  4623. var anchor = range.anchor;
  4624. if (other) {
  4625. var posBefore = cmp(head, anchor) < 0;
  4626. if (posBefore != (cmp(other, anchor) < 0)) {
  4627. anchor = head;
  4628. head = other;
  4629. } else if (posBefore != (cmp(head, other) < 0)) {
  4630. head = other;
  4631. }
  4632. }
  4633. return new Range(anchor, head)
  4634. } else {
  4635. return new Range(other || head, head)
  4636. }
  4637. }
  4638. // Extend the primary selection range, discard the rest.
  4639. function extendSelection(doc, head, other, options, extend) {
  4640. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4641. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4642. }
  4643. // Extend all selections (pos is an array of selections with length
  4644. // equal the number of selections)
  4645. function extendSelections(doc, heads, options) {
  4646. var out = [];
  4647. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4648. for (var i = 0; i < doc.sel.ranges.length; i++)
  4649. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4650. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4651. setSelection(doc, newSel, options);
  4652. }
  4653. // Updates a single range in the selection.
  4654. function replaceOneSelection(doc, i, range, options) {
  4655. var ranges = doc.sel.ranges.slice(0);
  4656. ranges[i] = range;
  4657. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4658. }
  4659. // Reset the selection to a single range.
  4660. function setSimpleSelection(doc, anchor, head, options) {
  4661. setSelection(doc, simpleSelection(anchor, head), options);
  4662. }
  4663. // Give beforeSelectionChange handlers a change to influence a
  4664. // selection update.
  4665. function filterSelectionChange(doc, sel, options) {
  4666. var obj = {
  4667. ranges: sel.ranges,
  4668. update: function(ranges) {
  4669. this.ranges = [];
  4670. for (var i = 0; i < ranges.length; i++)
  4671. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4672. clipPos(doc, ranges[i].head)); }
  4673. },
  4674. origin: options && options.origin
  4675. };
  4676. signal(doc, "beforeSelectionChange", doc, obj);
  4677. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4678. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4679. else { return sel }
  4680. }
  4681. function setSelectionReplaceHistory(doc, sel, options) {
  4682. var done = doc.history.done, last = lst(done);
  4683. if (last && last.ranges) {
  4684. done[done.length - 1] = sel;
  4685. setSelectionNoUndo(doc, sel, options);
  4686. } else {
  4687. setSelection(doc, sel, options);
  4688. }
  4689. }
  4690. // Set a new selection.
  4691. function setSelection(doc, sel, options) {
  4692. setSelectionNoUndo(doc, sel, options);
  4693. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4694. }
  4695. function setSelectionNoUndo(doc, sel, options) {
  4696. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4697. { sel = filterSelectionChange(doc, sel, options); }
  4698. var bias = options && options.bias ||
  4699. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4700. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4701. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  4702. { ensureCursorVisible(doc.cm); }
  4703. }
  4704. function setSelectionInner(doc, sel) {
  4705. if (sel.equals(doc.sel)) { return }
  4706. doc.sel = sel;
  4707. if (doc.cm) {
  4708. doc.cm.curOp.updateInput = 1;
  4709. doc.cm.curOp.selectionChanged = true;
  4710. signalCursorActivity(doc.cm);
  4711. }
  4712. signalLater(doc, "cursorActivity", doc);
  4713. }
  4714. // Verify that the selection does not partially select any atomic
  4715. // marked ranges.
  4716. function reCheckSelection(doc) {
  4717. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4718. }
  4719. // Return a selection that does not partially select any atomic
  4720. // ranges.
  4721. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4722. var out;
  4723. for (var i = 0; i < sel.ranges.length; i++) {
  4724. var range = sel.ranges[i];
  4725. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4726. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4727. var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4728. if (out || newAnchor != range.anchor || newHead != range.head) {
  4729. if (!out) { out = sel.ranges.slice(0, i); }
  4730. out[i] = new Range(newAnchor, newHead);
  4731. }
  4732. }
  4733. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4734. }
  4735. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4736. var line = getLine(doc, pos.line);
  4737. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4738. var sp = line.markedSpans[i], m = sp.marker;
  4739. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4740. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4741. // is with selectLeft/Right
  4742. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4743. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4744. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4745. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4746. if (mayClear) {
  4747. signal(m, "beforeCursorEnter");
  4748. if (m.explicitlyCleared) {
  4749. if (!line.markedSpans) { break }
  4750. else {--i; continue}
  4751. }
  4752. }
  4753. if (!m.atomic) { continue }
  4754. if (oldPos) {
  4755. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4756. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4757. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4758. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4759. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4760. }
  4761. var far = m.find(dir < 0 ? -1 : 1);
  4762. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4763. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4764. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4765. }
  4766. } }
  4767. return pos
  4768. }
  4769. // Ensure a given position is not inside an atomic range.
  4770. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4771. var dir = bias || 1;
  4772. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4773. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4774. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4775. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4776. if (!found) {
  4777. doc.cantEdit = true;
  4778. return Pos(doc.first, 0)
  4779. }
  4780. return found
  4781. }
  4782. function movePos(doc, pos, dir, line) {
  4783. if (dir < 0 && pos.ch == 0) {
  4784. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4785. else { return null }
  4786. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4787. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4788. else { return null }
  4789. } else {
  4790. return new Pos(pos.line, pos.ch + dir)
  4791. }
  4792. }
  4793. function selectAll(cm) {
  4794. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4795. }
  4796. // UPDATING
  4797. // Allow "beforeChange" event handlers to influence a change
  4798. function filterChange(doc, change, update) {
  4799. var obj = {
  4800. canceled: false,
  4801. from: change.from,
  4802. to: change.to,
  4803. text: change.text,
  4804. origin: change.origin,
  4805. cancel: function () { return obj.canceled = true; }
  4806. };
  4807. if (update) { obj.update = function (from, to, text, origin) {
  4808. if (from) { obj.from = clipPos(doc, from); }
  4809. if (to) { obj.to = clipPos(doc, to); }
  4810. if (text) { obj.text = text; }
  4811. if (origin !== undefined) { obj.origin = origin; }
  4812. }; }
  4813. signal(doc, "beforeChange", doc, obj);
  4814. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4815. if (obj.canceled) {
  4816. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4817. return null
  4818. }
  4819. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4820. }
  4821. // Apply a change to a document, and add it to the document's
  4822. // history, and propagating it to all linked documents.
  4823. function makeChange(doc, change, ignoreReadOnly) {
  4824. if (doc.cm) {
  4825. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4826. if (doc.cm.state.suppressEdits) { return }
  4827. }
  4828. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4829. change = filterChange(doc, change, true);
  4830. if (!change) { return }
  4831. }
  4832. // Possibly split or suppress the update based on the presence
  4833. // of read-only spans in its range.
  4834. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4835. if (split) {
  4836. for (var i = split.length - 1; i >= 0; --i)
  4837. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4838. } else {
  4839. makeChangeInner(doc, change);
  4840. }
  4841. }
  4842. function makeChangeInner(doc, change) {
  4843. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4844. var selAfter = computeSelAfterChange(doc, change);
  4845. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4846. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4847. var rebased = [];
  4848. linkedDocs(doc, function (doc, sharedHist) {
  4849. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4850. rebaseHist(doc.history, change);
  4851. rebased.push(doc.history);
  4852. }
  4853. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4854. });
  4855. }
  4856. // Revert a change stored in a document's history.
  4857. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4858. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4859. if (suppress && !allowSelectionOnly) { return }
  4860. var hist = doc.history, event, selAfter = doc.sel;
  4861. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4862. // Verify that there is a useable event (so that ctrl-z won't
  4863. // needlessly clear selection events)
  4864. var i = 0;
  4865. for (; i < source.length; i++) {
  4866. event = source[i];
  4867. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4868. { break }
  4869. }
  4870. if (i == source.length) { return }
  4871. hist.lastOrigin = hist.lastSelOrigin = null;
  4872. for (;;) {
  4873. event = source.pop();
  4874. if (event.ranges) {
  4875. pushSelectionToHistory(event, dest);
  4876. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4877. setSelection(doc, event, {clearRedo: false});
  4878. return
  4879. }
  4880. selAfter = event;
  4881. } else if (suppress) {
  4882. source.push(event);
  4883. return
  4884. } else { break }
  4885. }
  4886. // Build up a reverse change object to add to the opposite history
  4887. // stack (redo when undoing, and vice versa).
  4888. var antiChanges = [];
  4889. pushSelectionToHistory(selAfter, dest);
  4890. dest.push({changes: antiChanges, generation: hist.generation});
  4891. hist.generation = event.generation || ++hist.maxGeneration;
  4892. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4893. var loop = function ( i ) {
  4894. var change = event.changes[i];
  4895. change.origin = type;
  4896. if (filter && !filterChange(doc, change, false)) {
  4897. source.length = 0;
  4898. return {}
  4899. }
  4900. antiChanges.push(historyChangeFromChange(doc, change));
  4901. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4902. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4903. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4904. var rebased = [];
  4905. // Propagate to the linked documents
  4906. linkedDocs(doc, function (doc, sharedHist) {
  4907. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4908. rebaseHist(doc.history, change);
  4909. rebased.push(doc.history);
  4910. }
  4911. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4912. });
  4913. };
  4914. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4915. var returned = loop( i$1 );
  4916. if ( returned ) return returned.v;
  4917. }
  4918. }
  4919. // Sub-views need their line numbers shifted when text is added
  4920. // above or below them in the parent document.
  4921. function shiftDoc(doc, distance) {
  4922. if (distance == 0) { return }
  4923. doc.first += distance;
  4924. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4925. Pos(range.anchor.line + distance, range.anchor.ch),
  4926. Pos(range.head.line + distance, range.head.ch)
  4927. ); }), doc.sel.primIndex);
  4928. if (doc.cm) {
  4929. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4930. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4931. { regLineChange(doc.cm, l, "gutter"); }
  4932. }
  4933. }
  4934. // More lower-level change function, handling only a single document
  4935. // (not linked ones).
  4936. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4937. if (doc.cm && !doc.cm.curOp)
  4938. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4939. if (change.to.line < doc.first) {
  4940. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4941. return
  4942. }
  4943. if (change.from.line > doc.lastLine()) { return }
  4944. // Clip the change to the size of this doc
  4945. if (change.from.line < doc.first) {
  4946. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4947. shiftDoc(doc, shift);
  4948. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4949. text: [lst(change.text)], origin: change.origin};
  4950. }
  4951. var last = doc.lastLine();
  4952. if (change.to.line > last) {
  4953. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4954. text: [change.text[0]], origin: change.origin};
  4955. }
  4956. change.removed = getBetween(doc, change.from, change.to);
  4957. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4958. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4959. else { updateDoc(doc, change, spans); }
  4960. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4961. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4962. { doc.cantEdit = false; }
  4963. }
  4964. // Handle the interaction of a change to a document with the editor
  4965. // that this document is part of.
  4966. function makeChangeSingleDocInEditor(cm, change, spans) {
  4967. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4968. var recomputeMaxLength = false, checkWidthStart = from.line;
  4969. if (!cm.options.lineWrapping) {
  4970. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4971. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4972. if (line == display.maxLine) {
  4973. recomputeMaxLength = true;
  4974. return true
  4975. }
  4976. });
  4977. }
  4978. if (doc.sel.contains(change.from, change.to) > -1)
  4979. { signalCursorActivity(cm); }
  4980. updateDoc(doc, change, spans, estimateHeight(cm));
  4981. if (!cm.options.lineWrapping) {
  4982. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4983. var len = lineLength(line);
  4984. if (len > display.maxLineLength) {
  4985. display.maxLine = line;
  4986. display.maxLineLength = len;
  4987. display.maxLineChanged = true;
  4988. recomputeMaxLength = false;
  4989. }
  4990. });
  4991. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4992. }
  4993. retreatFrontier(doc, from.line);
  4994. startWorker(cm, 400);
  4995. var lendiff = change.text.length - (to.line - from.line) - 1;
  4996. // Remember that these lines changed, for updating the display
  4997. if (change.full)
  4998. { regChange(cm); }
  4999. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  5000. { regLineChange(cm, from.line, "text"); }
  5001. else
  5002. { regChange(cm, from.line, to.line + 1, lendiff); }
  5003. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  5004. if (changeHandler || changesHandler) {
  5005. var obj = {
  5006. from: from, to: to,
  5007. text: change.text,
  5008. removed: change.removed,
  5009. origin: change.origin
  5010. };
  5011. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  5012. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  5013. }
  5014. cm.display.selForContextMenu = null;
  5015. }
  5016. function replaceRange(doc, code, from, to, origin) {
  5017. var assign;
  5018. if (!to) { to = from; }
  5019. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  5020. if (typeof code == "string") { code = doc.splitLines(code); }
  5021. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  5022. }
  5023. // Rebasing/resetting history to deal with externally-sourced changes
  5024. function rebaseHistSelSingle(pos, from, to, diff) {
  5025. if (to < pos.line) {
  5026. pos.line += diff;
  5027. } else if (from < pos.line) {
  5028. pos.line = from;
  5029. pos.ch = 0;
  5030. }
  5031. }
  5032. // Tries to rebase an array of history events given a change in the
  5033. // document. If the change touches the same lines as the event, the
  5034. // event, and everything 'behind' it, is discarded. If the change is
  5035. // before the event, the event's positions are updated. Uses a
  5036. // copy-on-write scheme for the positions, to avoid having to
  5037. // reallocate them all on every rebase, but also avoid problems with
  5038. // shared position objects being unsafely updated.
  5039. function rebaseHistArray(array, from, to, diff) {
  5040. for (var i = 0; i < array.length; ++i) {
  5041. var sub = array[i], ok = true;
  5042. if (sub.ranges) {
  5043. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5044. for (var j = 0; j < sub.ranges.length; j++) {
  5045. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5046. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5047. }
  5048. continue
  5049. }
  5050. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5051. var cur = sub.changes[j$1];
  5052. if (to < cur.from.line) {
  5053. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5054. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5055. } else if (from <= cur.to.line) {
  5056. ok = false;
  5057. break
  5058. }
  5059. }
  5060. if (!ok) {
  5061. array.splice(0, i + 1);
  5062. i = 0;
  5063. }
  5064. }
  5065. }
  5066. function rebaseHist(hist, change) {
  5067. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5068. rebaseHistArray(hist.done, from, to, diff);
  5069. rebaseHistArray(hist.undone, from, to, diff);
  5070. }
  5071. // Utility for applying a change to a line by handle or number,
  5072. // returning the number and optionally registering the line as
  5073. // changed.
  5074. function changeLine(doc, handle, changeType, op) {
  5075. var no = handle, line = handle;
  5076. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5077. else { no = lineNo(handle); }
  5078. if (no == null) { return null }
  5079. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5080. return line
  5081. }
  5082. // The document is represented as a BTree consisting of leaves, with
  5083. // chunk of lines in them, and branches, with up to ten leaves or
  5084. // other branch nodes below them. The top node is always a branch
  5085. // node, and is the document object itself (meaning it has
  5086. // additional methods and properties).
  5087. //
  5088. // All nodes have parent links. The tree is used both to go from
  5089. // line numbers to line objects, and to go from objects to numbers.
  5090. // It also indexes by height, and is used to convert between height
  5091. // and line object, and to find the total height of the document.
  5092. //
  5093. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5094. function LeafChunk(lines) {
  5095. this.lines = lines;
  5096. this.parent = null;
  5097. var height = 0;
  5098. for (var i = 0; i < lines.length; ++i) {
  5099. lines[i].parent = this;
  5100. height += lines[i].height;
  5101. }
  5102. this.height = height;
  5103. }
  5104. LeafChunk.prototype = {
  5105. chunkSize: function() { return this.lines.length },
  5106. // Remove the n lines at offset 'at'.
  5107. removeInner: function(at, n) {
  5108. for (var i = at, e = at + n; i < e; ++i) {
  5109. var line = this.lines[i];
  5110. this.height -= line.height;
  5111. cleanUpLine(line);
  5112. signalLater(line, "delete");
  5113. }
  5114. this.lines.splice(at, n);
  5115. },
  5116. // Helper used to collapse a small branch into a single leaf.
  5117. collapse: function(lines) {
  5118. lines.push.apply(lines, this.lines);
  5119. },
  5120. // Insert the given array of lines at offset 'at', count them as
  5121. // having the given height.
  5122. insertInner: function(at, lines, height) {
  5123. this.height += height;
  5124. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5125. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5126. },
  5127. // Used to iterate over a part of the tree.
  5128. iterN: function(at, n, op) {
  5129. for (var e = at + n; at < e; ++at)
  5130. { if (op(this.lines[at])) { return true } }
  5131. }
  5132. };
  5133. function BranchChunk(children) {
  5134. this.children = children;
  5135. var size = 0, height = 0;
  5136. for (var i = 0; i < children.length; ++i) {
  5137. var ch = children[i];
  5138. size += ch.chunkSize(); height += ch.height;
  5139. ch.parent = this;
  5140. }
  5141. this.size = size;
  5142. this.height = height;
  5143. this.parent = null;
  5144. }
  5145. BranchChunk.prototype = {
  5146. chunkSize: function() { return this.size },
  5147. removeInner: function(at, n) {
  5148. this.size -= n;
  5149. for (var i = 0; i < this.children.length; ++i) {
  5150. var child = this.children[i], sz = child.chunkSize();
  5151. if (at < sz) {
  5152. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5153. child.removeInner(at, rm);
  5154. this.height -= oldHeight - child.height;
  5155. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5156. if ((n -= rm) == 0) { break }
  5157. at = 0;
  5158. } else { at -= sz; }
  5159. }
  5160. // If the result is smaller than 25 lines, ensure that it is a
  5161. // single leaf node.
  5162. if (this.size - n < 25 &&
  5163. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5164. var lines = [];
  5165. this.collapse(lines);
  5166. this.children = [new LeafChunk(lines)];
  5167. this.children[0].parent = this;
  5168. }
  5169. },
  5170. collapse: function(lines) {
  5171. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5172. },
  5173. insertInner: function(at, lines, height) {
  5174. this.size += lines.length;
  5175. this.height += height;
  5176. for (var i = 0; i < this.children.length; ++i) {
  5177. var child = this.children[i], sz = child.chunkSize();
  5178. if (at <= sz) {
  5179. child.insertInner(at, lines, height);
  5180. if (child.lines && child.lines.length > 50) {
  5181. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5182. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5183. var remaining = child.lines.length % 25 + 25;
  5184. for (var pos = remaining; pos < child.lines.length;) {
  5185. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5186. child.height -= leaf.height;
  5187. this.children.splice(++i, 0, leaf);
  5188. leaf.parent = this;
  5189. }
  5190. child.lines = child.lines.slice(0, remaining);
  5191. this.maybeSpill();
  5192. }
  5193. break
  5194. }
  5195. at -= sz;
  5196. }
  5197. },
  5198. // When a node has grown, check whether it should be split.
  5199. maybeSpill: function() {
  5200. if (this.children.length <= 10) { return }
  5201. var me = this;
  5202. do {
  5203. var spilled = me.children.splice(me.children.length - 5, 5);
  5204. var sibling = new BranchChunk(spilled);
  5205. if (!me.parent) { // Become the parent node
  5206. var copy = new BranchChunk(me.children);
  5207. copy.parent = me;
  5208. me.children = [copy, sibling];
  5209. me = copy;
  5210. } else {
  5211. me.size -= sibling.size;
  5212. me.height -= sibling.height;
  5213. var myIndex = indexOf(me.parent.children, me);
  5214. me.parent.children.splice(myIndex + 1, 0, sibling);
  5215. }
  5216. sibling.parent = me.parent;
  5217. } while (me.children.length > 10)
  5218. me.parent.maybeSpill();
  5219. },
  5220. iterN: function(at, n, op) {
  5221. for (var i = 0; i < this.children.length; ++i) {
  5222. var child = this.children[i], sz = child.chunkSize();
  5223. if (at < sz) {
  5224. var used = Math.min(n, sz - at);
  5225. if (child.iterN(at, used, op)) { return true }
  5226. if ((n -= used) == 0) { break }
  5227. at = 0;
  5228. } else { at -= sz; }
  5229. }
  5230. }
  5231. };
  5232. // Line widgets are block elements displayed above or below a line.
  5233. var LineWidget = function(doc, node, options) {
  5234. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5235. { this[opt] = options[opt]; } } }
  5236. this.doc = doc;
  5237. this.node = node;
  5238. };
  5239. LineWidget.prototype.clear = function () {
  5240. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5241. if (no == null || !ws) { return }
  5242. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5243. if (!ws.length) { line.widgets = null; }
  5244. var height = widgetHeight(this);
  5245. updateLineHeight(line, Math.max(0, line.height - height));
  5246. if (cm) {
  5247. runInOp(cm, function () {
  5248. adjustScrollWhenAboveVisible(cm, line, -height);
  5249. regLineChange(cm, no, "widget");
  5250. });
  5251. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5252. }
  5253. };
  5254. LineWidget.prototype.changed = function () {
  5255. var this$1 = this;
  5256. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5257. this.height = null;
  5258. var diff = widgetHeight(this) - oldH;
  5259. if (!diff) { return }
  5260. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5261. if (cm) {
  5262. runInOp(cm, function () {
  5263. cm.curOp.forceUpdate = true;
  5264. adjustScrollWhenAboveVisible(cm, line, diff);
  5265. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5266. });
  5267. }
  5268. };
  5269. eventMixin(LineWidget);
  5270. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5271. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5272. { addToScrollTop(cm, diff); }
  5273. }
  5274. function addLineWidget(doc, handle, node, options) {
  5275. var widget = new LineWidget(doc, node, options);
  5276. var cm = doc.cm;
  5277. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5278. changeLine(doc, handle, "widget", function (line) {
  5279. var widgets = line.widgets || (line.widgets = []);
  5280. if (widget.insertAt == null) { widgets.push(widget); }
  5281. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5282. widget.line = line;
  5283. if (cm && !lineIsHidden(doc, line)) {
  5284. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5285. updateLineHeight(line, line.height + widgetHeight(widget));
  5286. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5287. cm.curOp.forceUpdate = true;
  5288. }
  5289. return true
  5290. });
  5291. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5292. return widget
  5293. }
  5294. // TEXTMARKERS
  5295. // Created with markText and setBookmark methods. A TextMarker is a
  5296. // handle that can be used to clear or find a marked position in the
  5297. // document. Line objects hold arrays (markedSpans) containing
  5298. // {from, to, marker} object pointing to such marker objects, and
  5299. // indicating that such a marker is present on that line. Multiple
  5300. // lines may point to the same marker when it spans across lines.
  5301. // The spans will have null for their from/to properties when the
  5302. // marker continues beyond the start/end of the line. Markers have
  5303. // links back to the lines they currently touch.
  5304. // Collapsed markers have unique ids, in order to be able to order
  5305. // them, which is needed for uniquely determining an outer marker
  5306. // when they overlap (they may nest, but not partially overlap).
  5307. var nextMarkerId = 0;
  5308. var TextMarker = function(doc, type) {
  5309. this.lines = [];
  5310. this.type = type;
  5311. this.doc = doc;
  5312. this.id = ++nextMarkerId;
  5313. };
  5314. // Clear the marker.
  5315. TextMarker.prototype.clear = function () {
  5316. if (this.explicitlyCleared) { return }
  5317. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5318. if (withOp) { startOperation(cm); }
  5319. if (hasHandler(this, "clear")) {
  5320. var found = this.find();
  5321. if (found) { signalLater(this, "clear", found.from, found.to); }
  5322. }
  5323. var min = null, max = null;
  5324. for (var i = 0; i < this.lines.length; ++i) {
  5325. var line = this.lines[i];
  5326. var span = getMarkedSpanFor(line.markedSpans, this);
  5327. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5328. else if (cm) {
  5329. if (span.to != null) { max = lineNo(line); }
  5330. if (span.from != null) { min = lineNo(line); }
  5331. }
  5332. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5333. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5334. { updateLineHeight(line, textHeight(cm.display)); }
  5335. }
  5336. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5337. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5338. if (len > cm.display.maxLineLength) {
  5339. cm.display.maxLine = visual;
  5340. cm.display.maxLineLength = len;
  5341. cm.display.maxLineChanged = true;
  5342. }
  5343. } }
  5344. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5345. this.lines.length = 0;
  5346. this.explicitlyCleared = true;
  5347. if (this.atomic && this.doc.cantEdit) {
  5348. this.doc.cantEdit = false;
  5349. if (cm) { reCheckSelection(cm.doc); }
  5350. }
  5351. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5352. if (withOp) { endOperation(cm); }
  5353. if (this.parent) { this.parent.clear(); }
  5354. };
  5355. // Find the position of the marker in the document. Returns a {from,
  5356. // to} object by default. Side can be passed to get a specific side
  5357. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5358. // Pos objects returned contain a line object, rather than a line
  5359. // number (used to prevent looking up the same line twice).
  5360. TextMarker.prototype.find = function (side, lineObj) {
  5361. if (side == null && this.type == "bookmark") { side = 1; }
  5362. var from, to;
  5363. for (var i = 0; i < this.lines.length; ++i) {
  5364. var line = this.lines[i];
  5365. var span = getMarkedSpanFor(line.markedSpans, this);
  5366. if (span.from != null) {
  5367. from = Pos(lineObj ? line : lineNo(line), span.from);
  5368. if (side == -1) { return from }
  5369. }
  5370. if (span.to != null) {
  5371. to = Pos(lineObj ? line : lineNo(line), span.to);
  5372. if (side == 1) { return to }
  5373. }
  5374. }
  5375. return from && {from: from, to: to}
  5376. };
  5377. // Signals that the marker's widget changed, and surrounding layout
  5378. // should be recomputed.
  5379. TextMarker.prototype.changed = function () {
  5380. var this$1 = this;
  5381. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5382. if (!pos || !cm) { return }
  5383. runInOp(cm, function () {
  5384. var line = pos.line, lineN = lineNo(pos.line);
  5385. var view = findViewForLine(cm, lineN);
  5386. if (view) {
  5387. clearLineMeasurementCacheFor(view);
  5388. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5389. }
  5390. cm.curOp.updateMaxLine = true;
  5391. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5392. var oldHeight = widget.height;
  5393. widget.height = null;
  5394. var dHeight = widgetHeight(widget) - oldHeight;
  5395. if (dHeight)
  5396. { updateLineHeight(line, line.height + dHeight); }
  5397. }
  5398. signalLater(cm, "markerChanged", cm, this$1);
  5399. });
  5400. };
  5401. TextMarker.prototype.attachLine = function (line) {
  5402. if (!this.lines.length && this.doc.cm) {
  5403. var op = this.doc.cm.curOp;
  5404. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5405. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5406. }
  5407. this.lines.push(line);
  5408. };
  5409. TextMarker.prototype.detachLine = function (line) {
  5410. this.lines.splice(indexOf(this.lines, line), 1);
  5411. if (!this.lines.length && this.doc.cm) {
  5412. var op = this.doc.cm.curOp
  5413. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5414. }
  5415. };
  5416. eventMixin(TextMarker);
  5417. // Create a marker, wire it up to the right lines, and
  5418. function markText(doc, from, to, options, type) {
  5419. // Shared markers (across linked documents) are handled separately
  5420. // (markTextShared will call out to this again, once per
  5421. // document).
  5422. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5423. // Ensure we are in an operation.
  5424. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5425. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5426. if (options) { copyObj(options, marker, false); }
  5427. // Don't connect empty markers unless clearWhenEmpty is false
  5428. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5429. { return marker }
  5430. if (marker.replacedWith) {
  5431. // Showing up as a widget implies collapsed (widget replaces text)
  5432. marker.collapsed = true;
  5433. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5434. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5435. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5436. }
  5437. if (marker.collapsed) {
  5438. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5439. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5440. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5441. seeCollapsedSpans();
  5442. }
  5443. if (marker.addToHistory)
  5444. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5445. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5446. doc.iter(curLine, to.line + 1, function (line) {
  5447. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5448. { updateMaxLine = true; }
  5449. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5450. addMarkedSpan(line, new MarkedSpan(marker,
  5451. curLine == from.line ? from.ch : null,
  5452. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  5453. ++curLine;
  5454. });
  5455. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5456. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5457. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5458. }); }
  5459. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5460. if (marker.readOnly) {
  5461. seeReadOnlySpans();
  5462. if (doc.history.done.length || doc.history.undone.length)
  5463. { doc.clearHistory(); }
  5464. }
  5465. if (marker.collapsed) {
  5466. marker.id = ++nextMarkerId;
  5467. marker.atomic = true;
  5468. }
  5469. if (cm) {
  5470. // Sync editor state
  5471. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5472. if (marker.collapsed)
  5473. { regChange(cm, from.line, to.line + 1); }
  5474. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5475. marker.attributes || marker.title)
  5476. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5477. if (marker.atomic) { reCheckSelection(cm.doc); }
  5478. signalLater(cm, "markerAdded", cm, marker);
  5479. }
  5480. return marker
  5481. }
  5482. // SHARED TEXTMARKERS
  5483. // A shared marker spans multiple linked documents. It is
  5484. // implemented as a meta-marker-object controlling multiple normal
  5485. // markers.
  5486. var SharedTextMarker = function(markers, primary) {
  5487. this.markers = markers;
  5488. this.primary = primary;
  5489. for (var i = 0; i < markers.length; ++i)
  5490. { markers[i].parent = this; }
  5491. };
  5492. SharedTextMarker.prototype.clear = function () {
  5493. if (this.explicitlyCleared) { return }
  5494. this.explicitlyCleared = true;
  5495. for (var i = 0; i < this.markers.length; ++i)
  5496. { this.markers[i].clear(); }
  5497. signalLater(this, "clear");
  5498. };
  5499. SharedTextMarker.prototype.find = function (side, lineObj) {
  5500. return this.primary.find(side, lineObj)
  5501. };
  5502. eventMixin(SharedTextMarker);
  5503. function markTextShared(doc, from, to, options, type) {
  5504. options = copyObj(options);
  5505. options.shared = false;
  5506. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5507. var widget = options.widgetNode;
  5508. linkedDocs(doc, function (doc) {
  5509. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5510. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5511. for (var i = 0; i < doc.linked.length; ++i)
  5512. { if (doc.linked[i].isParent) { return } }
  5513. primary = lst(markers);
  5514. });
  5515. return new SharedTextMarker(markers, primary)
  5516. }
  5517. function findSharedMarkers(doc) {
  5518. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5519. }
  5520. function copySharedMarkers(doc, markers) {
  5521. for (var i = 0; i < markers.length; i++) {
  5522. var marker = markers[i], pos = marker.find();
  5523. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5524. if (cmp(mFrom, mTo)) {
  5525. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5526. marker.markers.push(subMark);
  5527. subMark.parent = marker;
  5528. }
  5529. }
  5530. }
  5531. function detachSharedMarkers(markers) {
  5532. var loop = function ( i ) {
  5533. var marker = markers[i], linked = [marker.primary.doc];
  5534. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5535. for (var j = 0; j < marker.markers.length; j++) {
  5536. var subMarker = marker.markers[j];
  5537. if (indexOf(linked, subMarker.doc) == -1) {
  5538. subMarker.parent = null;
  5539. marker.markers.splice(j--, 1);
  5540. }
  5541. }
  5542. };
  5543. for (var i = 0; i < markers.length; i++) loop( i );
  5544. }
  5545. var nextDocId = 0;
  5546. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5547. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5548. if (firstLine == null) { firstLine = 0; }
  5549. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5550. this.first = firstLine;
  5551. this.scrollTop = this.scrollLeft = 0;
  5552. this.cantEdit = false;
  5553. this.cleanGeneration = 1;
  5554. this.modeFrontier = this.highlightFrontier = firstLine;
  5555. var start = Pos(firstLine, 0);
  5556. this.sel = simpleSelection(start);
  5557. this.history = new History(null);
  5558. this.id = ++nextDocId;
  5559. this.modeOption = mode;
  5560. this.lineSep = lineSep;
  5561. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5562. this.extend = false;
  5563. if (typeof text == "string") { text = this.splitLines(text); }
  5564. updateDoc(this, {from: start, to: start, text: text});
  5565. setSelection(this, simpleSelection(start), sel_dontScroll);
  5566. };
  5567. Doc.prototype = createObj(BranchChunk.prototype, {
  5568. constructor: Doc,
  5569. // Iterate over the document. Supports two forms -- with only one
  5570. // argument, it calls that for each line in the document. With
  5571. // three, it iterates over the range given by the first two (with
  5572. // the second being non-inclusive).
  5573. iter: function(from, to, op) {
  5574. if (op) { this.iterN(from - this.first, to - from, op); }
  5575. else { this.iterN(this.first, this.first + this.size, from); }
  5576. },
  5577. // Non-public interface for adding and removing lines.
  5578. insert: function(at, lines) {
  5579. var height = 0;
  5580. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5581. this.insertInner(at - this.first, lines, height);
  5582. },
  5583. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5584. // From here, the methods are part of the public interface. Most
  5585. // are also available from CodeMirror (editor) instances.
  5586. getValue: function(lineSep) {
  5587. var lines = getLines(this, this.first, this.first + this.size);
  5588. if (lineSep === false) { return lines }
  5589. return lines.join(lineSep || this.lineSeparator())
  5590. },
  5591. setValue: docMethodOp(function(code) {
  5592. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5593. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5594. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5595. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5596. setSelection(this, simpleSelection(top), sel_dontScroll);
  5597. }),
  5598. replaceRange: function(code, from, to, origin) {
  5599. from = clipPos(this, from);
  5600. to = to ? clipPos(this, to) : from;
  5601. replaceRange(this, code, from, to, origin);
  5602. },
  5603. getRange: function(from, to, lineSep) {
  5604. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5605. if (lineSep === false) { return lines }
  5606. if (lineSep === '') { return lines.join('') }
  5607. return lines.join(lineSep || this.lineSeparator())
  5608. },
  5609. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5610. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5611. getLineNumber: function(line) {return lineNo(line)},
  5612. getLineHandleVisualStart: function(line) {
  5613. if (typeof line == "number") { line = getLine(this, line); }
  5614. return visualLine(line)
  5615. },
  5616. lineCount: function() {return this.size},
  5617. firstLine: function() {return this.first},
  5618. lastLine: function() {return this.first + this.size - 1},
  5619. clipPos: function(pos) {return clipPos(this, pos)},
  5620. getCursor: function(start) {
  5621. var range = this.sel.primary(), pos;
  5622. if (start == null || start == "head") { pos = range.head; }
  5623. else if (start == "anchor") { pos = range.anchor; }
  5624. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5625. else { pos = range.from(); }
  5626. return pos
  5627. },
  5628. listSelections: function() { return this.sel.ranges },
  5629. somethingSelected: function() {return this.sel.somethingSelected()},
  5630. setCursor: docMethodOp(function(line, ch, options) {
  5631. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5632. }),
  5633. setSelection: docMethodOp(function(anchor, head, options) {
  5634. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5635. }),
  5636. extendSelection: docMethodOp(function(head, other, options) {
  5637. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5638. }),
  5639. extendSelections: docMethodOp(function(heads, options) {
  5640. extendSelections(this, clipPosArray(this, heads), options);
  5641. }),
  5642. extendSelectionsBy: docMethodOp(function(f, options) {
  5643. var heads = map(this.sel.ranges, f);
  5644. extendSelections(this, clipPosArray(this, heads), options);
  5645. }),
  5646. setSelections: docMethodOp(function(ranges, primary, options) {
  5647. if (!ranges.length) { return }
  5648. var out = [];
  5649. for (var i = 0; i < ranges.length; i++)
  5650. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  5651. clipPos(this, ranges[i].head || ranges[i].anchor)); }
  5652. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5653. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5654. }),
  5655. addSelection: docMethodOp(function(anchor, head, options) {
  5656. var ranges = this.sel.ranges.slice(0);
  5657. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5658. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5659. }),
  5660. getSelection: function(lineSep) {
  5661. var ranges = this.sel.ranges, lines;
  5662. for (var i = 0; i < ranges.length; i++) {
  5663. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5664. lines = lines ? lines.concat(sel) : sel;
  5665. }
  5666. if (lineSep === false) { return lines }
  5667. else { return lines.join(lineSep || this.lineSeparator()) }
  5668. },
  5669. getSelections: function(lineSep) {
  5670. var parts = [], ranges = this.sel.ranges;
  5671. for (var i = 0; i < ranges.length; i++) {
  5672. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5673. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5674. parts[i] = sel;
  5675. }
  5676. return parts
  5677. },
  5678. replaceSelection: function(code, collapse, origin) {
  5679. var dup = [];
  5680. for (var i = 0; i < this.sel.ranges.length; i++)
  5681. { dup[i] = code; }
  5682. this.replaceSelections(dup, collapse, origin || "+input");
  5683. },
  5684. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5685. var changes = [], sel = this.sel;
  5686. for (var i = 0; i < sel.ranges.length; i++) {
  5687. var range = sel.ranges[i];
  5688. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  5689. }
  5690. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5691. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5692. { makeChange(this, changes[i$1]); }
  5693. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5694. else if (this.cm) { ensureCursorVisible(this.cm); }
  5695. }),
  5696. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5697. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5698. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5699. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5700. setExtending: function(val) {this.extend = val;},
  5701. getExtending: function() {return this.extend},
  5702. historySize: function() {
  5703. var hist = this.history, done = 0, undone = 0;
  5704. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5705. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5706. return {undo: done, redo: undone}
  5707. },
  5708. clearHistory: function() {
  5709. var this$1 = this;
  5710. this.history = new History(this.history);
  5711. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5712. },
  5713. markClean: function() {
  5714. this.cleanGeneration = this.changeGeneration(true);
  5715. },
  5716. changeGeneration: function(forceSplit) {
  5717. if (forceSplit)
  5718. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5719. return this.history.generation
  5720. },
  5721. isClean: function (gen) {
  5722. return this.history.generation == (gen || this.cleanGeneration)
  5723. },
  5724. getHistory: function() {
  5725. return {done: copyHistoryArray(this.history.done),
  5726. undone: copyHistoryArray(this.history.undone)}
  5727. },
  5728. setHistory: function(histData) {
  5729. var hist = this.history = new History(this.history);
  5730. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5731. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5732. },
  5733. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5734. return changeLine(this, line, "gutter", function (line) {
  5735. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5736. markers[gutterID] = value;
  5737. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5738. return true
  5739. })
  5740. }),
  5741. clearGutter: docMethodOp(function(gutterID) {
  5742. var this$1 = this;
  5743. this.iter(function (line) {
  5744. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5745. changeLine(this$1, line, "gutter", function () {
  5746. line.gutterMarkers[gutterID] = null;
  5747. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5748. return true
  5749. });
  5750. }
  5751. });
  5752. }),
  5753. lineInfo: function(line) {
  5754. var n;
  5755. if (typeof line == "number") {
  5756. if (!isLine(this, line)) { return null }
  5757. n = line;
  5758. line = getLine(this, line);
  5759. if (!line) { return null }
  5760. } else {
  5761. n = lineNo(line);
  5762. if (n == null) { return null }
  5763. }
  5764. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5765. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5766. widgets: line.widgets}
  5767. },
  5768. addLineClass: docMethodOp(function(handle, where, cls) {
  5769. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5770. var prop = where == "text" ? "textClass"
  5771. : where == "background" ? "bgClass"
  5772. : where == "gutter" ? "gutterClass" : "wrapClass";
  5773. if (!line[prop]) { line[prop] = cls; }
  5774. else if (classTest(cls).test(line[prop])) { return false }
  5775. else { line[prop] += " " + cls; }
  5776. return true
  5777. })
  5778. }),
  5779. removeLineClass: docMethodOp(function(handle, where, cls) {
  5780. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5781. var prop = where == "text" ? "textClass"
  5782. : where == "background" ? "bgClass"
  5783. : where == "gutter" ? "gutterClass" : "wrapClass";
  5784. var cur = line[prop];
  5785. if (!cur) { return false }
  5786. else if (cls == null) { line[prop] = null; }
  5787. else {
  5788. var found = cur.match(classTest(cls));
  5789. if (!found) { return false }
  5790. var end = found.index + found[0].length;
  5791. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5792. }
  5793. return true
  5794. })
  5795. }),
  5796. addLineWidget: docMethodOp(function(handle, node, options) {
  5797. return addLineWidget(this, handle, node, options)
  5798. }),
  5799. removeLineWidget: function(widget) { widget.clear(); },
  5800. markText: function(from, to, options) {
  5801. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5802. },
  5803. setBookmark: function(pos, options) {
  5804. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5805. insertLeft: options && options.insertLeft,
  5806. clearWhenEmpty: false, shared: options && options.shared,
  5807. handleMouseEvents: options && options.handleMouseEvents};
  5808. pos = clipPos(this, pos);
  5809. return markText(this, pos, pos, realOpts, "bookmark")
  5810. },
  5811. findMarksAt: function(pos) {
  5812. pos = clipPos(this, pos);
  5813. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5814. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5815. var span = spans[i];
  5816. if ((span.from == null || span.from <= pos.ch) &&
  5817. (span.to == null || span.to >= pos.ch))
  5818. { markers.push(span.marker.parent || span.marker); }
  5819. } }
  5820. return markers
  5821. },
  5822. findMarks: function(from, to, filter) {
  5823. from = clipPos(this, from); to = clipPos(this, to);
  5824. var found = [], lineNo = from.line;
  5825. this.iter(from.line, to.line + 1, function (line) {
  5826. var spans = line.markedSpans;
  5827. if (spans) { for (var i = 0; i < spans.length; i++) {
  5828. var span = spans[i];
  5829. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5830. span.from == null && lineNo != from.line ||
  5831. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5832. (!filter || filter(span.marker)))
  5833. { found.push(span.marker.parent || span.marker); }
  5834. } }
  5835. ++lineNo;
  5836. });
  5837. return found
  5838. },
  5839. getAllMarks: function() {
  5840. var markers = [];
  5841. this.iter(function (line) {
  5842. var sps = line.markedSpans;
  5843. if (sps) { for (var i = 0; i < sps.length; ++i)
  5844. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5845. });
  5846. return markers
  5847. },
  5848. posFromIndex: function(off) {
  5849. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5850. this.iter(function (line) {
  5851. var sz = line.text.length + sepSize;
  5852. if (sz > off) { ch = off; return true }
  5853. off -= sz;
  5854. ++lineNo;
  5855. });
  5856. return clipPos(this, Pos(lineNo, ch))
  5857. },
  5858. indexFromPos: function (coords) {
  5859. coords = clipPos(this, coords);
  5860. var index = coords.ch;
  5861. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5862. var sepSize = this.lineSeparator().length;
  5863. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5864. index += line.text.length + sepSize;
  5865. });
  5866. return index
  5867. },
  5868. copy: function(copyHistory) {
  5869. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5870. this.modeOption, this.first, this.lineSep, this.direction);
  5871. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5872. doc.sel = this.sel;
  5873. doc.extend = false;
  5874. if (copyHistory) {
  5875. doc.history.undoDepth = this.history.undoDepth;
  5876. doc.setHistory(this.getHistory());
  5877. }
  5878. return doc
  5879. },
  5880. linkedDoc: function(options) {
  5881. if (!options) { options = {}; }
  5882. var from = this.first, to = this.first + this.size;
  5883. if (options.from != null && options.from > from) { from = options.from; }
  5884. if (options.to != null && options.to < to) { to = options.to; }
  5885. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5886. if (options.sharedHist) { copy.history = this.history
  5887. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5888. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5889. copySharedMarkers(copy, findSharedMarkers(this));
  5890. return copy
  5891. },
  5892. unlinkDoc: function(other) {
  5893. if (other instanceof CodeMirror) { other = other.doc; }
  5894. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5895. var link = this.linked[i];
  5896. if (link.doc != other) { continue }
  5897. this.linked.splice(i, 1);
  5898. other.unlinkDoc(this);
  5899. detachSharedMarkers(findSharedMarkers(this));
  5900. break
  5901. } }
  5902. // If the histories were shared, split them again
  5903. if (other.history == this.history) {
  5904. var splitIds = [other.id];
  5905. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5906. other.history = new History(null);
  5907. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5908. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5909. }
  5910. },
  5911. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5912. getMode: function() {return this.mode},
  5913. getEditor: function() {return this.cm},
  5914. splitLines: function(str) {
  5915. if (this.lineSep) { return str.split(this.lineSep) }
  5916. return splitLinesAuto(str)
  5917. },
  5918. lineSeparator: function() { return this.lineSep || "\n" },
  5919. setDirection: docMethodOp(function (dir) {
  5920. if (dir != "rtl") { dir = "ltr"; }
  5921. if (dir == this.direction) { return }
  5922. this.direction = dir;
  5923. this.iter(function (line) { return line.order = null; });
  5924. if (this.cm) { directionChanged(this.cm); }
  5925. })
  5926. });
  5927. // Public alias.
  5928. Doc.prototype.eachLine = Doc.prototype.iter;
  5929. // Kludge to work around strange IE behavior where it'll sometimes
  5930. // re-fire a series of drag-related events right after the drop (#1551)
  5931. var lastDrop = 0;
  5932. function onDrop(e) {
  5933. var cm = this;
  5934. clearDragCursor(cm);
  5935. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5936. { return }
  5937. e_preventDefault(e);
  5938. if (ie) { lastDrop = +new Date; }
  5939. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5940. if (!pos || cm.isReadOnly()) { return }
  5941. // Might be a file drop, in which case we simply extract the text
  5942. // and insert it.
  5943. if (files && files.length && window.FileReader && window.File) {
  5944. var n = files.length, text = Array(n), read = 0;
  5945. var markAsReadAndPasteIfAllFilesAreRead = function () {
  5946. if (++read == n) {
  5947. operation(cm, function () {
  5948. pos = clipPos(cm.doc, pos);
  5949. var change = {from: pos, to: pos,
  5950. text: cm.doc.splitLines(
  5951. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  5952. origin: "paste"};
  5953. makeChange(cm.doc, change);
  5954. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  5955. })();
  5956. }
  5957. };
  5958. var readTextFromFile = function (file, i) {
  5959. if (cm.options.allowDropFileTypes &&
  5960. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  5961. markAsReadAndPasteIfAllFilesAreRead();
  5962. return
  5963. }
  5964. var reader = new FileReader;
  5965. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  5966. reader.onload = function () {
  5967. var content = reader.result;
  5968. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  5969. markAsReadAndPasteIfAllFilesAreRead();
  5970. return
  5971. }
  5972. text[i] = content;
  5973. markAsReadAndPasteIfAllFilesAreRead();
  5974. };
  5975. reader.readAsText(file);
  5976. };
  5977. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  5978. } else { // Normal drop
  5979. // Don't do a replace if the drop happened inside of the selected text.
  5980. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5981. cm.state.draggingText(e);
  5982. // Ensure the editor is re-focused
  5983. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5984. return
  5985. }
  5986. try {
  5987. var text$1 = e.dataTransfer.getData("Text");
  5988. if (text$1) {
  5989. var selected;
  5990. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5991. { selected = cm.listSelections(); }
  5992. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5993. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5994. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5995. cm.replaceSelection(text$1, "around", "paste");
  5996. cm.display.input.focus();
  5997. }
  5998. }
  5999. catch(e$1){}
  6000. }
  6001. }
  6002. function onDragStart(cm, e) {
  6003. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  6004. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  6005. e.dataTransfer.setData("Text", cm.getSelection());
  6006. e.dataTransfer.effectAllowed = "copyMove";
  6007. // Use dummy image instead of default browsers image.
  6008. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  6009. if (e.dataTransfer.setDragImage && !safari) {
  6010. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  6011. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  6012. if (presto) {
  6013. img.width = img.height = 1;
  6014. cm.display.wrapper.appendChild(img);
  6015. // Force a relayout, or Opera won't use our image for some obscure reason
  6016. img._top = img.offsetTop;
  6017. }
  6018. e.dataTransfer.setDragImage(img, 0, 0);
  6019. if (presto) { img.parentNode.removeChild(img); }
  6020. }
  6021. }
  6022. function onDragOver(cm, e) {
  6023. var pos = posFromMouse(cm, e);
  6024. if (!pos) { return }
  6025. var frag = document.createDocumentFragment();
  6026. drawSelectionCursor(cm, pos, frag);
  6027. if (!cm.display.dragCursor) {
  6028. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6029. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6030. }
  6031. removeChildrenAndAdd(cm.display.dragCursor, frag);
  6032. }
  6033. function clearDragCursor(cm) {
  6034. if (cm.display.dragCursor) {
  6035. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6036. cm.display.dragCursor = null;
  6037. }
  6038. }
  6039. // These must be handled carefully, because naively registering a
  6040. // handler for each editor will cause the editors to never be
  6041. // garbage collected.
  6042. function forEachCodeMirror(f) {
  6043. if (!document.getElementsByClassName) { return }
  6044. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6045. for (var i = 0; i < byClass.length; i++) {
  6046. var cm = byClass[i].CodeMirror;
  6047. if (cm) { editors.push(cm); }
  6048. }
  6049. if (editors.length) { editors[0].operation(function () {
  6050. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6051. }); }
  6052. }
  6053. var globalsRegistered = false;
  6054. function ensureGlobalHandlers() {
  6055. if (globalsRegistered) { return }
  6056. registerGlobalHandlers();
  6057. globalsRegistered = true;
  6058. }
  6059. function registerGlobalHandlers() {
  6060. // When the window resizes, we need to refresh active editors.
  6061. var resizeTimer;
  6062. on(window, "resize", function () {
  6063. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6064. resizeTimer = null;
  6065. forEachCodeMirror(onResize);
  6066. }, 100); }
  6067. });
  6068. // When the window loses focus, we want to show the editor as blurred
  6069. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6070. }
  6071. // Called when the window resizes
  6072. function onResize(cm) {
  6073. var d = cm.display;
  6074. // Might be a text scaling operation, clear size caches.
  6075. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6076. d.scrollbarsClipped = false;
  6077. cm.setSize();
  6078. }
  6079. var keyNames = {
  6080. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6081. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6082. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6083. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6084. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6085. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6086. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6087. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6088. };
  6089. // Number keys
  6090. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6091. // Alphabetic keys
  6092. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6093. // Function keys
  6094. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6095. var keyMap = {};
  6096. keyMap.basic = {
  6097. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6098. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6099. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6100. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6101. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6102. "Esc": "singleSelection"
  6103. };
  6104. // Note that the save and find-related commands aren't defined by
  6105. // default. User code or addons can define them. Unknown commands
  6106. // are simply ignored.
  6107. keyMap.pcDefault = {
  6108. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6109. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6110. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6111. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6112. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6113. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6114. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6115. "fallthrough": "basic"
  6116. };
  6117. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6118. keyMap.emacsy = {
  6119. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6120. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6121. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6122. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6123. };
  6124. keyMap.macDefault = {
  6125. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6126. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6127. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6128. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6129. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6130. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6131. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6132. "fallthrough": ["basic", "emacsy"]
  6133. };
  6134. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6135. // KEYMAP DISPATCH
  6136. function normalizeKeyName(name) {
  6137. var parts = name.split(/-(?!$)/);
  6138. name = parts[parts.length - 1];
  6139. var alt, ctrl, shift, cmd;
  6140. for (var i = 0; i < parts.length - 1; i++) {
  6141. var mod = parts[i];
  6142. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6143. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6144. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6145. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6146. else { throw new Error("Unrecognized modifier name: " + mod) }
  6147. }
  6148. if (alt) { name = "Alt-" + name; }
  6149. if (ctrl) { name = "Ctrl-" + name; }
  6150. if (cmd) { name = "Cmd-" + name; }
  6151. if (shift) { name = "Shift-" + name; }
  6152. return name
  6153. }
  6154. // This is a kludge to keep keymaps mostly working as raw objects
  6155. // (backwards compatibility) while at the same time support features
  6156. // like normalization and multi-stroke key bindings. It compiles a
  6157. // new normalized keymap, and then updates the old object to reflect
  6158. // this.
  6159. function normalizeKeyMap(keymap) {
  6160. var copy = {};
  6161. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6162. var value = keymap[keyname];
  6163. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6164. if (value == "...") { delete keymap[keyname]; continue }
  6165. var keys = map(keyname.split(" "), normalizeKeyName);
  6166. for (var i = 0; i < keys.length; i++) {
  6167. var val = (void 0), name = (void 0);
  6168. if (i == keys.length - 1) {
  6169. name = keys.join(" ");
  6170. val = value;
  6171. } else {
  6172. name = keys.slice(0, i + 1).join(" ");
  6173. val = "...";
  6174. }
  6175. var prev = copy[name];
  6176. if (!prev) { copy[name] = val; }
  6177. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6178. }
  6179. delete keymap[keyname];
  6180. } }
  6181. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6182. return keymap
  6183. }
  6184. function lookupKey(key, map, handle, context) {
  6185. map = getKeyMap(map);
  6186. var found = map.call ? map.call(key, context) : map[key];
  6187. if (found === false) { return "nothing" }
  6188. if (found === "...") { return "multi" }
  6189. if (found != null && handle(found)) { return "handled" }
  6190. if (map.fallthrough) {
  6191. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6192. { return lookupKey(key, map.fallthrough, handle, context) }
  6193. for (var i = 0; i < map.fallthrough.length; i++) {
  6194. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6195. if (result) { return result }
  6196. }
  6197. }
  6198. }
  6199. // Modifier key presses don't count as 'real' key presses for the
  6200. // purpose of keymap fallthrough.
  6201. function isModifierKey(value) {
  6202. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6203. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6204. }
  6205. function addModifierNames(name, event, noShift) {
  6206. var base = name;
  6207. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6208. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6209. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6210. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6211. return name
  6212. }
  6213. // Look up the name of a key as indicated by an event object.
  6214. function keyName(event, noShift) {
  6215. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6216. var name = keyNames[event.keyCode];
  6217. if (name == null || event.altGraphKey) { return false }
  6218. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6219. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6220. if (event.keyCode == 3 && event.code) { name = event.code; }
  6221. return addModifierNames(name, event, noShift)
  6222. }
  6223. function getKeyMap(val) {
  6224. return typeof val == "string" ? keyMap[val] : val
  6225. }
  6226. // Helper for deleting text near the selection(s), used to implement
  6227. // backspace, delete, and similar functionality.
  6228. function deleteNearSelection(cm, compute) {
  6229. var ranges = cm.doc.sel.ranges, kill = [];
  6230. // Build up a set of ranges to kill first, merging overlapping
  6231. // ranges.
  6232. for (var i = 0; i < ranges.length; i++) {
  6233. var toKill = compute(ranges[i]);
  6234. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6235. var replaced = kill.pop();
  6236. if (cmp(replaced.from, toKill.from) < 0) {
  6237. toKill.from = replaced.from;
  6238. break
  6239. }
  6240. }
  6241. kill.push(toKill);
  6242. }
  6243. // Next, remove those actual ranges.
  6244. runInOp(cm, function () {
  6245. for (var i = kill.length - 1; i >= 0; i--)
  6246. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6247. ensureCursorVisible(cm);
  6248. });
  6249. }
  6250. function moveCharLogically(line, ch, dir) {
  6251. var target = skipExtendingChars(line.text, ch + dir, dir);
  6252. return target < 0 || target > line.text.length ? null : target
  6253. }
  6254. function moveLogically(line, start, dir) {
  6255. var ch = moveCharLogically(line, start.ch, dir);
  6256. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6257. }
  6258. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6259. if (visually) {
  6260. if (cm.doc.direction == "rtl") { dir = -dir; }
  6261. var order = getOrder(lineObj, cm.doc.direction);
  6262. if (order) {
  6263. var part = dir < 0 ? lst(order) : order[0];
  6264. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6265. var sticky = moveInStorageOrder ? "after" : "before";
  6266. var ch;
  6267. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6268. // it could be that the last bidi part is not on the last visual line,
  6269. // since visual lines contain content order-consecutive chunks.
  6270. // Thus, in rtl, we are looking for the first (content-order) character
  6271. // in the rtl chunk that is on the last line (that is, the same line
  6272. // as the last (content-order) character).
  6273. if (part.level > 0 || cm.doc.direction == "rtl") {
  6274. var prep = prepareMeasureForLine(cm, lineObj);
  6275. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6276. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6277. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6278. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6279. } else { ch = dir < 0 ? part.to : part.from; }
  6280. return new Pos(lineNo, ch, sticky)
  6281. }
  6282. }
  6283. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6284. }
  6285. function moveVisually(cm, line, start, dir) {
  6286. var bidi = getOrder(line, cm.doc.direction);
  6287. if (!bidi) { return moveLogically(line, start, dir) }
  6288. if (start.ch >= line.text.length) {
  6289. start.ch = line.text.length;
  6290. start.sticky = "before";
  6291. } else if (start.ch <= 0) {
  6292. start.ch = 0;
  6293. start.sticky = "after";
  6294. }
  6295. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6296. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6297. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6298. // nothing interesting happens.
  6299. return moveLogically(line, start, dir)
  6300. }
  6301. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6302. var prep;
  6303. var getWrappedLineExtent = function (ch) {
  6304. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6305. prep = prep || prepareMeasureForLine(cm, line);
  6306. return wrappedLineExtentChar(cm, line, prep, ch)
  6307. };
  6308. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6309. if (cm.doc.direction == "rtl" || part.level == 1) {
  6310. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6311. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6312. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6313. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6314. var sticky = moveInStorageOrder ? "before" : "after";
  6315. return new Pos(start.line, ch, sticky)
  6316. }
  6317. }
  6318. // Case 3: Could not move within this bidi part in this visual line, so leave
  6319. // the current bidi part
  6320. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6321. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6322. ? new Pos(start.line, mv(ch, 1), "before")
  6323. : new Pos(start.line, ch, "after"); };
  6324. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6325. var part = bidi[partPos];
  6326. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6327. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6328. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6329. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6330. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6331. }
  6332. };
  6333. // Case 3a: Look for other bidi parts on the same visual line
  6334. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6335. if (res) { return res }
  6336. // Case 3b: Look for other bidi parts on the next visual line
  6337. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6338. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6339. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6340. if (res) { return res }
  6341. }
  6342. // Case 4: Nowhere to move
  6343. return null
  6344. }
  6345. // Commands are parameter-less actions that can be performed on an
  6346. // editor, mostly used for keybindings.
  6347. var commands = {
  6348. selectAll: selectAll,
  6349. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6350. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6351. if (range.empty()) {
  6352. var len = getLine(cm.doc, range.head.line).text.length;
  6353. if (range.head.ch == len && range.head.line < cm.lastLine())
  6354. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6355. else
  6356. { return {from: range.head, to: Pos(range.head.line, len)} }
  6357. } else {
  6358. return {from: range.from(), to: range.to()}
  6359. }
  6360. }); },
  6361. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6362. from: Pos(range.from().line, 0),
  6363. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6364. }); }); },
  6365. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6366. from: Pos(range.from().line, 0), to: range.from()
  6367. }); }); },
  6368. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6369. var top = cm.charCoords(range.head, "div").top + 5;
  6370. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6371. return {from: leftPos, to: range.from()}
  6372. }); },
  6373. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6374. var top = cm.charCoords(range.head, "div").top + 5;
  6375. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6376. return {from: range.from(), to: rightPos }
  6377. }); },
  6378. undo: function (cm) { return cm.undo(); },
  6379. redo: function (cm) { return cm.redo(); },
  6380. undoSelection: function (cm) { return cm.undoSelection(); },
  6381. redoSelection: function (cm) { return cm.redoSelection(); },
  6382. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6383. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6384. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6385. {origin: "+move", bias: 1}
  6386. ); },
  6387. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6388. {origin: "+move", bias: 1}
  6389. ); },
  6390. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6391. {origin: "+move", bias: -1}
  6392. ); },
  6393. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6394. var top = cm.cursorCoords(range.head, "div").top + 5;
  6395. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6396. }, sel_move); },
  6397. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6398. var top = cm.cursorCoords(range.head, "div").top + 5;
  6399. return cm.coordsChar({left: 0, top: top}, "div")
  6400. }, sel_move); },
  6401. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6402. var top = cm.cursorCoords(range.head, "div").top + 5;
  6403. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6404. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6405. return pos
  6406. }, sel_move); },
  6407. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6408. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6409. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6410. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6411. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6412. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6413. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6414. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6415. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6416. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6417. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6418. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6419. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6420. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6421. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6422. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6423. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6424. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6425. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6426. indentMore: function (cm) { return cm.indentSelection("add"); },
  6427. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6428. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6429. insertSoftTab: function (cm) {
  6430. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6431. for (var i = 0; i < ranges.length; i++) {
  6432. var pos = ranges[i].from();
  6433. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6434. spaces.push(spaceStr(tabSize - col % tabSize));
  6435. }
  6436. cm.replaceSelections(spaces);
  6437. },
  6438. defaultTab: function (cm) {
  6439. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6440. else { cm.execCommand("insertTab"); }
  6441. },
  6442. // Swap the two chars left and right of each selection's head.
  6443. // Move cursor behind the two swapped characters afterwards.
  6444. //
  6445. // Doesn't consider line feeds a character.
  6446. // Doesn't scan more than one line above to find a character.
  6447. // Doesn't do anything on an empty line.
  6448. // Doesn't do anything with non-empty selections.
  6449. transposeChars: function (cm) { return runInOp(cm, function () {
  6450. var ranges = cm.listSelections(), newSel = [];
  6451. for (var i = 0; i < ranges.length; i++) {
  6452. if (!ranges[i].empty()) { continue }
  6453. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6454. if (line) {
  6455. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6456. if (cur.ch > 0) {
  6457. cur = new Pos(cur.line, cur.ch + 1);
  6458. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6459. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6460. } else if (cur.line > cm.doc.first) {
  6461. var prev = getLine(cm.doc, cur.line - 1).text;
  6462. if (prev) {
  6463. cur = new Pos(cur.line, 1);
  6464. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6465. prev.charAt(prev.length - 1),
  6466. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6467. }
  6468. }
  6469. }
  6470. newSel.push(new Range(cur, cur));
  6471. }
  6472. cm.setSelections(newSel);
  6473. }); },
  6474. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6475. var sels = cm.listSelections();
  6476. for (var i = sels.length - 1; i >= 0; i--)
  6477. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6478. sels = cm.listSelections();
  6479. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6480. { cm.indentLine(sels[i$1].from().line, null, true); }
  6481. ensureCursorVisible(cm);
  6482. }); },
  6483. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6484. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6485. };
  6486. function lineStart(cm, lineN) {
  6487. var line = getLine(cm.doc, lineN);
  6488. var visual = visualLine(line);
  6489. if (visual != line) { lineN = lineNo(visual); }
  6490. return endOfLine(true, cm, visual, lineN, 1)
  6491. }
  6492. function lineEnd(cm, lineN) {
  6493. var line = getLine(cm.doc, lineN);
  6494. var visual = visualLineEnd(line);
  6495. if (visual != line) { lineN = lineNo(visual); }
  6496. return endOfLine(true, cm, line, lineN, -1)
  6497. }
  6498. function lineStartSmart(cm, pos) {
  6499. var start = lineStart(cm, pos.line);
  6500. var line = getLine(cm.doc, start.line);
  6501. var order = getOrder(line, cm.doc.direction);
  6502. if (!order || order[0].level == 0) {
  6503. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6504. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6505. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6506. }
  6507. return start
  6508. }
  6509. // Run a handler that was bound to a key.
  6510. function doHandleBinding(cm, bound, dropShift) {
  6511. if (typeof bound == "string") {
  6512. bound = commands[bound];
  6513. if (!bound) { return false }
  6514. }
  6515. // Ensure previous input has been read, so that the handler sees a
  6516. // consistent view of the document
  6517. cm.display.input.ensurePolled();
  6518. var prevShift = cm.display.shift, done = false;
  6519. try {
  6520. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6521. if (dropShift) { cm.display.shift = false; }
  6522. done = bound(cm) != Pass;
  6523. } finally {
  6524. cm.display.shift = prevShift;
  6525. cm.state.suppressEdits = false;
  6526. }
  6527. return done
  6528. }
  6529. function lookupKeyForEditor(cm, name, handle) {
  6530. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6531. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6532. if (result) { return result }
  6533. }
  6534. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6535. || lookupKey(name, cm.options.keyMap, handle, cm)
  6536. }
  6537. // Note that, despite the name, this function is also used to check
  6538. // for bound mouse clicks.
  6539. var stopSeq = new Delayed;
  6540. function dispatchKey(cm, name, e, handle) {
  6541. var seq = cm.state.keySeq;
  6542. if (seq) {
  6543. if (isModifierKey(name)) { return "handled" }
  6544. if (/\'$/.test(name))
  6545. { cm.state.keySeq = null; }
  6546. else
  6547. { stopSeq.set(50, function () {
  6548. if (cm.state.keySeq == seq) {
  6549. cm.state.keySeq = null;
  6550. cm.display.input.reset();
  6551. }
  6552. }); }
  6553. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6554. }
  6555. return dispatchKeyInner(cm, name, e, handle)
  6556. }
  6557. function dispatchKeyInner(cm, name, e, handle) {
  6558. var result = lookupKeyForEditor(cm, name, handle);
  6559. if (result == "multi")
  6560. { cm.state.keySeq = name; }
  6561. if (result == "handled")
  6562. { signalLater(cm, "keyHandled", cm, name, e); }
  6563. if (result == "handled" || result == "multi") {
  6564. e_preventDefault(e);
  6565. restartBlink(cm);
  6566. }
  6567. return !!result
  6568. }
  6569. // Handle a key from the keydown event.
  6570. function handleKeyBinding(cm, e) {
  6571. var name = keyName(e, true);
  6572. if (!name) { return false }
  6573. if (e.shiftKey && !cm.state.keySeq) {
  6574. // First try to resolve full name (including 'Shift-'). Failing
  6575. // that, see if there is a cursor-motion command (starting with
  6576. // 'go') bound to the keyname without 'Shift-'.
  6577. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6578. || dispatchKey(cm, name, e, function (b) {
  6579. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6580. { return doHandleBinding(cm, b) }
  6581. })
  6582. } else {
  6583. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6584. }
  6585. }
  6586. // Handle a key from the keypress event
  6587. function handleCharBinding(cm, e, ch) {
  6588. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6589. }
  6590. var lastStoppedKey = null;
  6591. function onKeyDown(e) {
  6592. var cm = this;
  6593. if (e.target && e.target != cm.display.input.getField()) { return }
  6594. cm.curOp.focus = activeElt(root(cm));
  6595. if (signalDOMEvent(cm, e)) { return }
  6596. // IE does strange things with escape.
  6597. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6598. var code = e.keyCode;
  6599. cm.display.shift = code == 16 || e.shiftKey;
  6600. var handled = handleKeyBinding(cm, e);
  6601. if (presto) {
  6602. lastStoppedKey = handled ? code : null;
  6603. // Opera has no cut event... we try to at least catch the key combo
  6604. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6605. { cm.replaceSelection("", null, "cut"); }
  6606. }
  6607. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6608. { document.execCommand("cut"); }
  6609. // Turn mouse into crosshair when Alt is held on Mac.
  6610. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6611. { showCrossHair(cm); }
  6612. }
  6613. function showCrossHair(cm) {
  6614. var lineDiv = cm.display.lineDiv;
  6615. addClass(lineDiv, "CodeMirror-crosshair");
  6616. function up(e) {
  6617. if (e.keyCode == 18 || !e.altKey) {
  6618. rmClass(lineDiv, "CodeMirror-crosshair");
  6619. off(document, "keyup", up);
  6620. off(document, "mouseover", up);
  6621. }
  6622. }
  6623. on(document, "keyup", up);
  6624. on(document, "mouseover", up);
  6625. }
  6626. function onKeyUp(e) {
  6627. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6628. signalDOMEvent(this, e);
  6629. }
  6630. function onKeyPress(e) {
  6631. var cm = this;
  6632. if (e.target && e.target != cm.display.input.getField()) { return }
  6633. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6634. var keyCode = e.keyCode, charCode = e.charCode;
  6635. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6636. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6637. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6638. // Some browsers fire keypress events for backspace
  6639. if (ch == "\x08") { return }
  6640. if (handleCharBinding(cm, e, ch)) { return }
  6641. cm.display.input.onKeyPress(e);
  6642. }
  6643. var DOUBLECLICK_DELAY = 400;
  6644. var PastClick = function(time, pos, button) {
  6645. this.time = time;
  6646. this.pos = pos;
  6647. this.button = button;
  6648. };
  6649. PastClick.prototype.compare = function (time, pos, button) {
  6650. return this.time + DOUBLECLICK_DELAY > time &&
  6651. cmp(pos, this.pos) == 0 && button == this.button
  6652. };
  6653. var lastClick, lastDoubleClick;
  6654. function clickRepeat(pos, button) {
  6655. var now = +new Date;
  6656. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6657. lastClick = lastDoubleClick = null;
  6658. return "triple"
  6659. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6660. lastDoubleClick = new PastClick(now, pos, button);
  6661. lastClick = null;
  6662. return "double"
  6663. } else {
  6664. lastClick = new PastClick(now, pos, button);
  6665. lastDoubleClick = null;
  6666. return "single"
  6667. }
  6668. }
  6669. // A mouse down can be a single click, double click, triple click,
  6670. // start of selection drag, start of text drag, new cursor
  6671. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6672. // middle-click-paste. Or it might be a click on something we should
  6673. // not interfere with, such as a scrollbar or widget.
  6674. function onMouseDown(e) {
  6675. var cm = this, display = cm.display;
  6676. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6677. display.input.ensurePolled();
  6678. display.shift = e.shiftKey;
  6679. if (eventInWidget(display, e)) {
  6680. if (!webkit) {
  6681. // Briefly turn off draggability, to allow widgets to do
  6682. // normal dragging things.
  6683. display.scroller.draggable = false;
  6684. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6685. }
  6686. return
  6687. }
  6688. if (clickInGutter(cm, e)) { return }
  6689. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6690. win(cm).focus();
  6691. // #3261: make sure, that we're not starting a second selection
  6692. if (button == 1 && cm.state.selectingText)
  6693. { cm.state.selectingText(e); }
  6694. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6695. if (button == 1) {
  6696. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6697. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6698. } else if (button == 2) {
  6699. if (pos) { extendSelection(cm.doc, pos); }
  6700. setTimeout(function () { return display.input.focus(); }, 20);
  6701. } else if (button == 3) {
  6702. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6703. else { delayBlurEvent(cm); }
  6704. }
  6705. }
  6706. function handleMappedButton(cm, button, pos, repeat, event) {
  6707. var name = "Click";
  6708. if (repeat == "double") { name = "Double" + name; }
  6709. else if (repeat == "triple") { name = "Triple" + name; }
  6710. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6711. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6712. if (typeof bound == "string") { bound = commands[bound]; }
  6713. if (!bound) { return false }
  6714. var done = false;
  6715. try {
  6716. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6717. done = bound(cm, pos) != Pass;
  6718. } finally {
  6719. cm.state.suppressEdits = false;
  6720. }
  6721. return done
  6722. })
  6723. }
  6724. function configureMouse(cm, repeat, event) {
  6725. var option = cm.getOption("configureMouse");
  6726. var value = option ? option(cm, repeat, event) : {};
  6727. if (value.unit == null) {
  6728. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6729. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6730. }
  6731. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6732. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6733. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6734. return value
  6735. }
  6736. function leftButtonDown(cm, pos, repeat, event) {
  6737. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6738. else { cm.curOp.focus = activeElt(root(cm)); }
  6739. var behavior = configureMouse(cm, repeat, event);
  6740. var sel = cm.doc.sel, contained;
  6741. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6742. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6743. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6744. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6745. { leftButtonStartDrag(cm, event, pos, behavior); }
  6746. else
  6747. { leftButtonSelect(cm, event, pos, behavior); }
  6748. }
  6749. // Start a text drag. When it ends, see if any dragging actually
  6750. // happen, and treat as a click if it didn't.
  6751. function leftButtonStartDrag(cm, event, pos, behavior) {
  6752. var display = cm.display, moved = false;
  6753. var dragEnd = operation(cm, function (e) {
  6754. if (webkit) { display.scroller.draggable = false; }
  6755. cm.state.draggingText = false;
  6756. if (cm.state.delayingBlurEvent) {
  6757. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6758. else { delayBlurEvent(cm); }
  6759. }
  6760. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6761. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6762. off(display.scroller, "dragstart", dragStart);
  6763. off(display.scroller, "drop", dragEnd);
  6764. if (!moved) {
  6765. e_preventDefault(e);
  6766. if (!behavior.addNew)
  6767. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6768. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6769. if ((webkit && !safari) || ie && ie_version == 9)
  6770. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  6771. else
  6772. { display.input.focus(); }
  6773. }
  6774. });
  6775. var mouseMove = function(e2) {
  6776. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6777. };
  6778. var dragStart = function () { return moved = true; };
  6779. // Let the drag handler handle this.
  6780. if (webkit) { display.scroller.draggable = true; }
  6781. cm.state.draggingText = dragEnd;
  6782. dragEnd.copy = !behavior.moveOnDrag;
  6783. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6784. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6785. on(display.scroller, "dragstart", dragStart);
  6786. on(display.scroller, "drop", dragEnd);
  6787. cm.state.delayingBlurEvent = true;
  6788. setTimeout(function () { return display.input.focus(); }, 20);
  6789. // IE's approach to draggable
  6790. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6791. }
  6792. function rangeForUnit(cm, pos, unit) {
  6793. if (unit == "char") { return new Range(pos, pos) }
  6794. if (unit == "word") { return cm.findWordAt(pos) }
  6795. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6796. var result = unit(cm, pos);
  6797. return new Range(result.from, result.to)
  6798. }
  6799. // Normal selection, as opposed to text dragging.
  6800. function leftButtonSelect(cm, event, start, behavior) {
  6801. if (ie) { delayBlurEvent(cm); }
  6802. var display = cm.display, doc = cm.doc;
  6803. e_preventDefault(event);
  6804. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6805. if (behavior.addNew && !behavior.extend) {
  6806. ourIndex = doc.sel.contains(start);
  6807. if (ourIndex > -1)
  6808. { ourRange = ranges[ourIndex]; }
  6809. else
  6810. { ourRange = new Range(start, start); }
  6811. } else {
  6812. ourRange = doc.sel.primary();
  6813. ourIndex = doc.sel.primIndex;
  6814. }
  6815. if (behavior.unit == "rectangle") {
  6816. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6817. start = posFromMouse(cm, event, true, true);
  6818. ourIndex = -1;
  6819. } else {
  6820. var range = rangeForUnit(cm, start, behavior.unit);
  6821. if (behavior.extend)
  6822. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6823. else
  6824. { ourRange = range; }
  6825. }
  6826. if (!behavior.addNew) {
  6827. ourIndex = 0;
  6828. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6829. startSel = doc.sel;
  6830. } else if (ourIndex == -1) {
  6831. ourIndex = ranges.length;
  6832. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6833. {scroll: false, origin: "*mouse"});
  6834. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6835. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6836. {scroll: false, origin: "*mouse"});
  6837. startSel = doc.sel;
  6838. } else {
  6839. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6840. }
  6841. var lastPos = start;
  6842. function extendTo(pos) {
  6843. if (cmp(lastPos, pos) == 0) { return }
  6844. lastPos = pos;
  6845. if (behavior.unit == "rectangle") {
  6846. var ranges = [], tabSize = cm.options.tabSize;
  6847. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6848. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6849. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6850. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6851. line <= end; line++) {
  6852. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6853. if (left == right)
  6854. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6855. else if (text.length > leftPos)
  6856. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6857. }
  6858. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6859. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6860. {origin: "*mouse", scroll: false});
  6861. cm.scrollIntoView(pos);
  6862. } else {
  6863. var oldRange = ourRange;
  6864. var range = rangeForUnit(cm, pos, behavior.unit);
  6865. var anchor = oldRange.anchor, head;
  6866. if (cmp(range.anchor, anchor) > 0) {
  6867. head = range.head;
  6868. anchor = minPos(oldRange.from(), range.anchor);
  6869. } else {
  6870. head = range.anchor;
  6871. anchor = maxPos(oldRange.to(), range.head);
  6872. }
  6873. var ranges$1 = startSel.ranges.slice(0);
  6874. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6875. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6876. }
  6877. }
  6878. var editorSize = display.wrapper.getBoundingClientRect();
  6879. // Used to ensure timeout re-tries don't fire when another extend
  6880. // happened in the meantime (clearTimeout isn't reliable -- at
  6881. // least on Chrome, the timeouts still happen even when cleared,
  6882. // if the clear happens after their scheduled firing time).
  6883. var counter = 0;
  6884. function extend(e) {
  6885. var curCount = ++counter;
  6886. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6887. if (!cur) { return }
  6888. if (cmp(cur, lastPos) != 0) {
  6889. cm.curOp.focus = activeElt(root(cm));
  6890. extendTo(cur);
  6891. var visible = visibleLines(display, doc);
  6892. if (cur.line >= visible.to || cur.line < visible.from)
  6893. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6894. } else {
  6895. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6896. if (outside) { setTimeout(operation(cm, function () {
  6897. if (counter != curCount) { return }
  6898. display.scroller.scrollTop += outside;
  6899. extend(e);
  6900. }), 50); }
  6901. }
  6902. }
  6903. function done(e) {
  6904. cm.state.selectingText = false;
  6905. counter = Infinity;
  6906. // If e is null or undefined we interpret this as someone trying
  6907. // to explicitly cancel the selection rather than the user
  6908. // letting go of the mouse button.
  6909. if (e) {
  6910. e_preventDefault(e);
  6911. display.input.focus();
  6912. }
  6913. off(display.wrapper.ownerDocument, "mousemove", move);
  6914. off(display.wrapper.ownerDocument, "mouseup", up);
  6915. doc.history.lastSelOrigin = null;
  6916. }
  6917. var move = operation(cm, function (e) {
  6918. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6919. else { extend(e); }
  6920. });
  6921. var up = operation(cm, done);
  6922. cm.state.selectingText = up;
  6923. on(display.wrapper.ownerDocument, "mousemove", move);
  6924. on(display.wrapper.ownerDocument, "mouseup", up);
  6925. }
  6926. // Used when mouse-selecting to adjust the anchor to the proper side
  6927. // of a bidi jump depending on the visual position of the head.
  6928. function bidiSimplify(cm, range) {
  6929. var anchor = range.anchor;
  6930. var head = range.head;
  6931. var anchorLine = getLine(cm.doc, anchor.line);
  6932. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6933. var order = getOrder(anchorLine);
  6934. if (!order) { return range }
  6935. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6936. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6937. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6938. if (boundary == 0 || boundary == order.length) { return range }
  6939. // Compute the relative visual position of the head compared to the
  6940. // anchor (<0 is to the left, >0 to the right)
  6941. var leftSide;
  6942. if (head.line != anchor.line) {
  6943. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6944. } else {
  6945. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6946. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6947. if (headIndex == boundary - 1 || headIndex == boundary)
  6948. { leftSide = dir < 0; }
  6949. else
  6950. { leftSide = dir > 0; }
  6951. }
  6952. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6953. var from = leftSide == (usePart.level == 1);
  6954. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6955. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6956. }
  6957. // Determines whether an event happened in the gutter, and fires the
  6958. // handlers for the corresponding event.
  6959. function gutterEvent(cm, e, type, prevent) {
  6960. var mX, mY;
  6961. if (e.touches) {
  6962. mX = e.touches[0].clientX;
  6963. mY = e.touches[0].clientY;
  6964. } else {
  6965. try { mX = e.clientX; mY = e.clientY; }
  6966. catch(e$1) { return false }
  6967. }
  6968. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6969. if (prevent) { e_preventDefault(e); }
  6970. var display = cm.display;
  6971. var lineBox = display.lineDiv.getBoundingClientRect();
  6972. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6973. mY -= lineBox.top - display.viewOffset;
  6974. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6975. var g = display.gutters.childNodes[i];
  6976. if (g && g.getBoundingClientRect().right >= mX) {
  6977. var line = lineAtHeight(cm.doc, mY);
  6978. var gutter = cm.display.gutterSpecs[i];
  6979. signal(cm, type, cm, line, gutter.className, e);
  6980. return e_defaultPrevented(e)
  6981. }
  6982. }
  6983. }
  6984. function clickInGutter(cm, e) {
  6985. return gutterEvent(cm, e, "gutterClick", true)
  6986. }
  6987. // CONTEXT MENU HANDLING
  6988. // To make the context menu work, we need to briefly unhide the
  6989. // textarea (making it as unobtrusive as possible) to let the
  6990. // right-click take effect on it.
  6991. function onContextMenu(cm, e) {
  6992. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6993. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6994. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6995. }
  6996. function contextMenuInGutter(cm, e) {
  6997. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6998. return gutterEvent(cm, e, "gutterContextMenu", false)
  6999. }
  7000. function themeChanged(cm) {
  7001. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  7002. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  7003. clearCaches(cm);
  7004. }
  7005. var Init = {toString: function(){return "CodeMirror.Init"}};
  7006. var defaults = {};
  7007. var optionHandlers = {};
  7008. function defineOptions(CodeMirror) {
  7009. var optionHandlers = CodeMirror.optionHandlers;
  7010. function option(name, deflt, handle, notOnInit) {
  7011. CodeMirror.defaults[name] = deflt;
  7012. if (handle) { optionHandlers[name] =
  7013. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  7014. }
  7015. CodeMirror.defineOption = option;
  7016. // Passed to option handlers when there is no old value.
  7017. CodeMirror.Init = Init;
  7018. // These two are, on init, called from the constructor because they
  7019. // have to be initialized before the editor can start at all.
  7020. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  7021. option("mode", null, function (cm, val) {
  7022. cm.doc.modeOption = val;
  7023. loadMode(cm);
  7024. }, true);
  7025. option("indentUnit", 2, loadMode, true);
  7026. option("indentWithTabs", false);
  7027. option("smartIndent", true);
  7028. option("tabSize", 4, function (cm) {
  7029. resetModeState(cm);
  7030. clearCaches(cm);
  7031. regChange(cm);
  7032. }, true);
  7033. option("lineSeparator", null, function (cm, val) {
  7034. cm.doc.lineSep = val;
  7035. if (!val) { return }
  7036. var newBreaks = [], lineNo = cm.doc.first;
  7037. cm.doc.iter(function (line) {
  7038. for (var pos = 0;;) {
  7039. var found = line.text.indexOf(val, pos);
  7040. if (found == -1) { break }
  7041. pos = found + val.length;
  7042. newBreaks.push(Pos(lineNo, found));
  7043. }
  7044. lineNo++;
  7045. });
  7046. for (var i = newBreaks.length - 1; i >= 0; i--)
  7047. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7048. });
  7049. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  7050. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7051. if (old != Init) { cm.refresh(); }
  7052. });
  7053. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7054. option("electricChars", true);
  7055. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7056. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7057. }, true);
  7058. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7059. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7060. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7061. option("rtlMoveVisually", !windows);
  7062. option("wholeLineUpdateBefore", true);
  7063. option("theme", "default", function (cm) {
  7064. themeChanged(cm);
  7065. updateGutters(cm);
  7066. }, true);
  7067. option("keyMap", "default", function (cm, val, old) {
  7068. var next = getKeyMap(val);
  7069. var prev = old != Init && getKeyMap(old);
  7070. if (prev && prev.detach) { prev.detach(cm, next); }
  7071. if (next.attach) { next.attach(cm, prev || null); }
  7072. });
  7073. option("extraKeys", null);
  7074. option("configureMouse", null);
  7075. option("lineWrapping", false, wrappingChanged, true);
  7076. option("gutters", [], function (cm, val) {
  7077. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7078. updateGutters(cm);
  7079. }, true);
  7080. option("fixedGutter", true, function (cm, val) {
  7081. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7082. cm.refresh();
  7083. }, true);
  7084. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7085. option("scrollbarStyle", "native", function (cm) {
  7086. initScrollbars(cm);
  7087. updateScrollbars(cm);
  7088. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7089. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7090. }, true);
  7091. option("lineNumbers", false, function (cm, val) {
  7092. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7093. updateGutters(cm);
  7094. }, true);
  7095. option("firstLineNumber", 1, updateGutters, true);
  7096. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7097. option("showCursorWhenSelecting", false, updateSelection, true);
  7098. option("resetSelectionOnContextMenu", true);
  7099. option("lineWiseCopyCut", true);
  7100. option("pasteLinesPerSelection", true);
  7101. option("selectionsMayTouch", false);
  7102. option("readOnly", false, function (cm, val) {
  7103. if (val == "nocursor") {
  7104. onBlur(cm);
  7105. cm.display.input.blur();
  7106. }
  7107. cm.display.input.readOnlyChanged(val);
  7108. });
  7109. option("screenReaderLabel", null, function (cm, val) {
  7110. val = (val === '') ? null : val;
  7111. cm.display.input.screenReaderLabelChanged(val);
  7112. });
  7113. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7114. option("dragDrop", true, dragDropChanged);
  7115. option("allowDropFileTypes", null);
  7116. option("cursorBlinkRate", 530);
  7117. option("cursorScrollMargin", 0);
  7118. option("cursorHeight", 1, updateSelection, true);
  7119. option("singleCursorHeightPerLine", true, updateSelection, true);
  7120. option("workTime", 100);
  7121. option("workDelay", 100);
  7122. option("flattenSpans", true, resetModeState, true);
  7123. option("addModeClass", false, resetModeState, true);
  7124. option("pollInterval", 100);
  7125. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7126. option("historyEventDelay", 1250);
  7127. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7128. option("maxHighlightLength", 10000, resetModeState, true);
  7129. option("moveInputWithCursor", true, function (cm, val) {
  7130. if (!val) { cm.display.input.resetPosition(); }
  7131. });
  7132. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7133. option("autofocus", null);
  7134. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7135. option("phrases", null);
  7136. }
  7137. function dragDropChanged(cm, value, old) {
  7138. var wasOn = old && old != Init;
  7139. if (!value != !wasOn) {
  7140. var funcs = cm.display.dragFunctions;
  7141. var toggle = value ? on : off;
  7142. toggle(cm.display.scroller, "dragstart", funcs.start);
  7143. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7144. toggle(cm.display.scroller, "dragover", funcs.over);
  7145. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7146. toggle(cm.display.scroller, "drop", funcs.drop);
  7147. }
  7148. }
  7149. function wrappingChanged(cm) {
  7150. if (cm.options.lineWrapping) {
  7151. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7152. cm.display.sizer.style.minWidth = "";
  7153. cm.display.sizerWidth = null;
  7154. } else {
  7155. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7156. findMaxLine(cm);
  7157. }
  7158. estimateLineHeights(cm);
  7159. regChange(cm);
  7160. clearCaches(cm);
  7161. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7162. }
  7163. // A CodeMirror instance represents an editor. This is the object
  7164. // that user code is usually dealing with.
  7165. function CodeMirror(place, options) {
  7166. var this$1 = this;
  7167. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7168. this.options = options = options ? copyObj(options) : {};
  7169. // Determine effective options based on given values and defaults.
  7170. copyObj(defaults, options, false);
  7171. var doc = options.value;
  7172. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7173. else if (options.mode) { doc.modeOption = options.mode; }
  7174. this.doc = doc;
  7175. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7176. var display = this.display = new Display(place, doc, input, options);
  7177. display.wrapper.CodeMirror = this;
  7178. themeChanged(this);
  7179. if (options.lineWrapping)
  7180. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7181. initScrollbars(this);
  7182. this.state = {
  7183. keyMaps: [], // stores maps added by addKeyMap
  7184. overlays: [], // highlighting overlays, as added by addOverlay
  7185. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7186. overwrite: false,
  7187. delayingBlurEvent: false,
  7188. focused: false,
  7189. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7190. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7191. selectingText: false,
  7192. draggingText: false,
  7193. highlight: new Delayed(), // stores highlight worker timeout
  7194. keySeq: null, // Unfinished key sequence
  7195. specialChars: null
  7196. };
  7197. if (options.autofocus && !mobile) { display.input.focus(); }
  7198. // Override magic textarea content restore that IE sometimes does
  7199. // on our hidden textarea on reload
  7200. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7201. registerEventHandlers(this);
  7202. ensureGlobalHandlers();
  7203. startOperation(this);
  7204. this.curOp.forceUpdate = true;
  7205. attachDoc(this, doc);
  7206. if ((options.autofocus && !mobile) || this.hasFocus())
  7207. { setTimeout(function () {
  7208. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7209. }, 20); }
  7210. else
  7211. { onBlur(this); }
  7212. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7213. { optionHandlers[opt](this, options[opt], Init); } }
  7214. maybeUpdateLineNumberWidth(this);
  7215. if (options.finishInit) { options.finishInit(this); }
  7216. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7217. endOperation(this);
  7218. // Suppress optimizelegibility in Webkit, since it breaks text
  7219. // measuring on line wrapping boundaries.
  7220. if (webkit && options.lineWrapping &&
  7221. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7222. { display.lineDiv.style.textRendering = "auto"; }
  7223. }
  7224. // The default configuration options.
  7225. CodeMirror.defaults = defaults;
  7226. // Functions to run when options are changed.
  7227. CodeMirror.optionHandlers = optionHandlers;
  7228. // Attach the necessary event handlers when initializing the editor
  7229. function registerEventHandlers(cm) {
  7230. var d = cm.display;
  7231. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7232. // Older IE's will not fire a second mousedown for a double click
  7233. if (ie && ie_version < 11)
  7234. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7235. if (signalDOMEvent(cm, e)) { return }
  7236. var pos = posFromMouse(cm, e);
  7237. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7238. e_preventDefault(e);
  7239. var word = cm.findWordAt(pos);
  7240. extendSelection(cm.doc, word.anchor, word.head);
  7241. })); }
  7242. else
  7243. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7244. // Some browsers fire contextmenu *after* opening the menu, at
  7245. // which point we can't mess with it anymore. Context menu is
  7246. // handled in onMouseDown for these browsers.
  7247. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7248. on(d.input.getField(), "contextmenu", function (e) {
  7249. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7250. });
  7251. // Used to suppress mouse event handling when a touch happens
  7252. var touchFinished, prevTouch = {end: 0};
  7253. function finishTouch() {
  7254. if (d.activeTouch) {
  7255. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7256. prevTouch = d.activeTouch;
  7257. prevTouch.end = +new Date;
  7258. }
  7259. }
  7260. function isMouseLikeTouchEvent(e) {
  7261. if (e.touches.length != 1) { return false }
  7262. var touch = e.touches[0];
  7263. return touch.radiusX <= 1 && touch.radiusY <= 1
  7264. }
  7265. function farAway(touch, other) {
  7266. if (other.left == null) { return true }
  7267. var dx = other.left - touch.left, dy = other.top - touch.top;
  7268. return dx * dx + dy * dy > 20 * 20
  7269. }
  7270. on(d.scroller, "touchstart", function (e) {
  7271. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7272. d.input.ensurePolled();
  7273. clearTimeout(touchFinished);
  7274. var now = +new Date;
  7275. d.activeTouch = {start: now, moved: false,
  7276. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7277. if (e.touches.length == 1) {
  7278. d.activeTouch.left = e.touches[0].pageX;
  7279. d.activeTouch.top = e.touches[0].pageY;
  7280. }
  7281. }
  7282. });
  7283. on(d.scroller, "touchmove", function () {
  7284. if (d.activeTouch) { d.activeTouch.moved = true; }
  7285. });
  7286. on(d.scroller, "touchend", function (e) {
  7287. var touch = d.activeTouch;
  7288. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7289. !touch.moved && new Date - touch.start < 300) {
  7290. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7291. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7292. { range = new Range(pos, pos); }
  7293. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7294. { range = cm.findWordAt(pos); }
  7295. else // Triple tap
  7296. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7297. cm.setSelection(range.anchor, range.head);
  7298. cm.focus();
  7299. e_preventDefault(e);
  7300. }
  7301. finishTouch();
  7302. });
  7303. on(d.scroller, "touchcancel", finishTouch);
  7304. // Sync scrolling between fake scrollbars and real scrollable
  7305. // area, ensure viewport is updated when scrolling.
  7306. on(d.scroller, "scroll", function () {
  7307. if (d.scroller.clientHeight) {
  7308. updateScrollTop(cm, d.scroller.scrollTop);
  7309. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7310. signal(cm, "scroll", cm);
  7311. }
  7312. });
  7313. // Listen to wheel events in order to try and update the viewport on time.
  7314. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7315. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7316. // Prevent wrapper from ever scrolling
  7317. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7318. d.dragFunctions = {
  7319. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7320. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7321. start: function (e) { return onDragStart(cm, e); },
  7322. drop: operation(cm, onDrop),
  7323. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7324. };
  7325. var inp = d.input.getField();
  7326. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7327. on(inp, "keydown", operation(cm, onKeyDown));
  7328. on(inp, "keypress", operation(cm, onKeyPress));
  7329. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7330. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7331. }
  7332. var initHooks = [];
  7333. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7334. // Indent the given line. The how parameter can be "smart",
  7335. // "add"/null, "subtract", or "prev". When aggressive is false
  7336. // (typically set to true for forced single-line indents), empty
  7337. // lines are not indented, and places where the mode returns Pass
  7338. // are left alone.
  7339. function indentLine(cm, n, how, aggressive) {
  7340. var doc = cm.doc, state;
  7341. if (how == null) { how = "add"; }
  7342. if (how == "smart") {
  7343. // Fall back to "prev" when the mode doesn't have an indentation
  7344. // method.
  7345. if (!doc.mode.indent) { how = "prev"; }
  7346. else { state = getContextBefore(cm, n).state; }
  7347. }
  7348. var tabSize = cm.options.tabSize;
  7349. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7350. if (line.stateAfter) { line.stateAfter = null; }
  7351. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7352. if (!aggressive && !/\S/.test(line.text)) {
  7353. indentation = 0;
  7354. how = "not";
  7355. } else if (how == "smart") {
  7356. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7357. if (indentation == Pass || indentation > 150) {
  7358. if (!aggressive) { return }
  7359. how = "prev";
  7360. }
  7361. }
  7362. if (how == "prev") {
  7363. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7364. else { indentation = 0; }
  7365. } else if (how == "add") {
  7366. indentation = curSpace + cm.options.indentUnit;
  7367. } else if (how == "subtract") {
  7368. indentation = curSpace - cm.options.indentUnit;
  7369. } else if (typeof how == "number") {
  7370. indentation = curSpace + how;
  7371. }
  7372. indentation = Math.max(0, indentation);
  7373. var indentString = "", pos = 0;
  7374. if (cm.options.indentWithTabs)
  7375. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7376. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7377. if (indentString != curSpaceString) {
  7378. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7379. line.stateAfter = null;
  7380. return true
  7381. } else {
  7382. // Ensure that, if the cursor was in the whitespace at the start
  7383. // of the line, it is moved to the end of that space.
  7384. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7385. var range = doc.sel.ranges[i$1];
  7386. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7387. var pos$1 = Pos(n, curSpaceString.length);
  7388. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7389. break
  7390. }
  7391. }
  7392. }
  7393. }
  7394. // This will be set to a {lineWise: bool, text: [string]} object, so
  7395. // that, when pasting, we know what kind of selections the copied
  7396. // text was made out of.
  7397. var lastCopied = null;
  7398. function setLastCopied(newLastCopied) {
  7399. lastCopied = newLastCopied;
  7400. }
  7401. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7402. var doc = cm.doc;
  7403. cm.display.shift = false;
  7404. if (!sel) { sel = doc.sel; }
  7405. var recent = +new Date - 200;
  7406. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7407. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7408. // When pasting N lines into N selections, insert one line per selection
  7409. if (paste && sel.ranges.length > 1) {
  7410. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7411. if (sel.ranges.length % lastCopied.text.length == 0) {
  7412. multiPaste = [];
  7413. for (var i = 0; i < lastCopied.text.length; i++)
  7414. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7415. }
  7416. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7417. multiPaste = map(textLines, function (l) { return [l]; });
  7418. }
  7419. }
  7420. var updateInput = cm.curOp.updateInput;
  7421. // Normal behavior is to insert the new text into every selection
  7422. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7423. var range = sel.ranges[i$1];
  7424. var from = range.from(), to = range.to();
  7425. if (range.empty()) {
  7426. if (deleted && deleted > 0) // Handle deletion
  7427. { from = Pos(from.line, from.ch - deleted); }
  7428. else if (cm.state.overwrite && !paste) // Handle overwrite
  7429. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7430. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7431. { from = to = Pos(from.line, 0); }
  7432. }
  7433. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7434. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7435. makeChange(cm.doc, changeEvent);
  7436. signalLater(cm, "inputRead", cm, changeEvent);
  7437. }
  7438. if (inserted && !paste)
  7439. { triggerElectric(cm, inserted); }
  7440. ensureCursorVisible(cm);
  7441. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7442. cm.curOp.typing = true;
  7443. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7444. }
  7445. function handlePaste(e, cm) {
  7446. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7447. if (pasted) {
  7448. e.preventDefault();
  7449. if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
  7450. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7451. return true
  7452. }
  7453. }
  7454. function triggerElectric(cm, inserted) {
  7455. // When an 'electric' character is inserted, immediately trigger a reindent
  7456. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7457. var sel = cm.doc.sel;
  7458. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7459. var range = sel.ranges[i];
  7460. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7461. var mode = cm.getModeAt(range.head);
  7462. var indented = false;
  7463. if (mode.electricChars) {
  7464. for (var j = 0; j < mode.electricChars.length; j++)
  7465. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7466. indented = indentLine(cm, range.head.line, "smart");
  7467. break
  7468. } }
  7469. } else if (mode.electricInput) {
  7470. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7471. { indented = indentLine(cm, range.head.line, "smart"); }
  7472. }
  7473. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7474. }
  7475. }
  7476. function copyableRanges(cm) {
  7477. var text = [], ranges = [];
  7478. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7479. var line = cm.doc.sel.ranges[i].head.line;
  7480. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7481. ranges.push(lineRange);
  7482. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7483. }
  7484. return {text: text, ranges: ranges}
  7485. }
  7486. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7487. field.setAttribute("autocorrect", autocorrect ? "on" : "off");
  7488. field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
  7489. field.setAttribute("spellcheck", !!spellcheck);
  7490. }
  7491. function hiddenTextarea() {
  7492. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  7493. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7494. // The textarea is kept positioned near the cursor to prevent the
  7495. // fact that it'll be scrolled into view on input from scrolling
  7496. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7497. // very slow. So make the area wide instead.
  7498. if (webkit) { te.style.width = "1000px"; }
  7499. else { te.setAttribute("wrap", "off"); }
  7500. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7501. if (ios) { te.style.border = "1px solid black"; }
  7502. return div
  7503. }
  7504. // The publicly visible API. Note that methodOp(f) means
  7505. // 'wrap f in an operation, performed on its `this` parameter'.
  7506. // This is not the complete set of editor methods. Most of the
  7507. // methods defined on the Doc type are also injected into
  7508. // CodeMirror.prototype, for backwards compatibility and
  7509. // convenience.
  7510. function addEditorMethods(CodeMirror) {
  7511. var optionHandlers = CodeMirror.optionHandlers;
  7512. var helpers = CodeMirror.helpers = {};
  7513. CodeMirror.prototype = {
  7514. constructor: CodeMirror,
  7515. focus: function(){win(this).focus(); this.display.input.focus();},
  7516. setOption: function(option, value) {
  7517. var options = this.options, old = options[option];
  7518. if (options[option] == value && option != "mode") { return }
  7519. options[option] = value;
  7520. if (optionHandlers.hasOwnProperty(option))
  7521. { operation(this, optionHandlers[option])(this, value, old); }
  7522. signal(this, "optionChange", this, option);
  7523. },
  7524. getOption: function(option) {return this.options[option]},
  7525. getDoc: function() {return this.doc},
  7526. addKeyMap: function(map, bottom) {
  7527. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7528. },
  7529. removeKeyMap: function(map) {
  7530. var maps = this.state.keyMaps;
  7531. for (var i = 0; i < maps.length; ++i)
  7532. { if (maps[i] == map || maps[i].name == map) {
  7533. maps.splice(i, 1);
  7534. return true
  7535. } }
  7536. },
  7537. addOverlay: methodOp(function(spec, options) {
  7538. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7539. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7540. insertSorted(this.state.overlays,
  7541. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7542. priority: (options && options.priority) || 0},
  7543. function (overlay) { return overlay.priority; });
  7544. this.state.modeGen++;
  7545. regChange(this);
  7546. }),
  7547. removeOverlay: methodOp(function(spec) {
  7548. var overlays = this.state.overlays;
  7549. for (var i = 0; i < overlays.length; ++i) {
  7550. var cur = overlays[i].modeSpec;
  7551. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7552. overlays.splice(i, 1);
  7553. this.state.modeGen++;
  7554. regChange(this);
  7555. return
  7556. }
  7557. }
  7558. }),
  7559. indentLine: methodOp(function(n, dir, aggressive) {
  7560. if (typeof dir != "string" && typeof dir != "number") {
  7561. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7562. else { dir = dir ? "add" : "subtract"; }
  7563. }
  7564. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7565. }),
  7566. indentSelection: methodOp(function(how) {
  7567. var ranges = this.doc.sel.ranges, end = -1;
  7568. for (var i = 0; i < ranges.length; i++) {
  7569. var range = ranges[i];
  7570. if (!range.empty()) {
  7571. var from = range.from(), to = range.to();
  7572. var start = Math.max(end, from.line);
  7573. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7574. for (var j = start; j < end; ++j)
  7575. { indentLine(this, j, how); }
  7576. var newRanges = this.doc.sel.ranges;
  7577. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7578. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7579. } else if (range.head.line > end) {
  7580. indentLine(this, range.head.line, how, true);
  7581. end = range.head.line;
  7582. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7583. }
  7584. }
  7585. }),
  7586. // Fetch the parser token for a given character. Useful for hacks
  7587. // that want to inspect the mode state (say, for completion).
  7588. getTokenAt: function(pos, precise) {
  7589. return takeToken(this, pos, precise)
  7590. },
  7591. getLineTokens: function(line, precise) {
  7592. return takeToken(this, Pos(line), precise, true)
  7593. },
  7594. getTokenTypeAt: function(pos) {
  7595. pos = clipPos(this.doc, pos);
  7596. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7597. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7598. var type;
  7599. if (ch == 0) { type = styles[2]; }
  7600. else { for (;;) {
  7601. var mid = (before + after) >> 1;
  7602. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7603. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7604. else { type = styles[mid * 2 + 2]; break }
  7605. } }
  7606. var cut = type ? type.indexOf("overlay ") : -1;
  7607. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7608. },
  7609. getModeAt: function(pos) {
  7610. var mode = this.doc.mode;
  7611. if (!mode.innerMode) { return mode }
  7612. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7613. },
  7614. getHelper: function(pos, type) {
  7615. return this.getHelpers(pos, type)[0]
  7616. },
  7617. getHelpers: function(pos, type) {
  7618. var found = [];
  7619. if (!helpers.hasOwnProperty(type)) { return found }
  7620. var help = helpers[type], mode = this.getModeAt(pos);
  7621. if (typeof mode[type] == "string") {
  7622. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7623. } else if (mode[type]) {
  7624. for (var i = 0; i < mode[type].length; i++) {
  7625. var val = help[mode[type][i]];
  7626. if (val) { found.push(val); }
  7627. }
  7628. } else if (mode.helperType && help[mode.helperType]) {
  7629. found.push(help[mode.helperType]);
  7630. } else if (help[mode.name]) {
  7631. found.push(help[mode.name]);
  7632. }
  7633. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7634. var cur = help._global[i$1];
  7635. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7636. { found.push(cur.val); }
  7637. }
  7638. return found
  7639. },
  7640. getStateAfter: function(line, precise) {
  7641. var doc = this.doc;
  7642. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7643. return getContextBefore(this, line + 1, precise).state
  7644. },
  7645. cursorCoords: function(start, mode) {
  7646. var pos, range = this.doc.sel.primary();
  7647. if (start == null) { pos = range.head; }
  7648. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7649. else { pos = start ? range.from() : range.to(); }
  7650. return cursorCoords(this, pos, mode || "page")
  7651. },
  7652. charCoords: function(pos, mode) {
  7653. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7654. },
  7655. coordsChar: function(coords, mode) {
  7656. coords = fromCoordSystem(this, coords, mode || "page");
  7657. return coordsChar(this, coords.left, coords.top)
  7658. },
  7659. lineAtHeight: function(height, mode) {
  7660. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7661. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7662. },
  7663. heightAtLine: function(line, mode, includeWidgets) {
  7664. var end = false, lineObj;
  7665. if (typeof line == "number") {
  7666. var last = this.doc.first + this.doc.size - 1;
  7667. if (line < this.doc.first) { line = this.doc.first; }
  7668. else if (line > last) { line = last; end = true; }
  7669. lineObj = getLine(this.doc, line);
  7670. } else {
  7671. lineObj = line;
  7672. }
  7673. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7674. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7675. },
  7676. defaultTextHeight: function() { return textHeight(this.display) },
  7677. defaultCharWidth: function() { return charWidth(this.display) },
  7678. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7679. addWidget: function(pos, node, scroll, vert, horiz) {
  7680. var display = this.display;
  7681. pos = cursorCoords(this, clipPos(this.doc, pos));
  7682. var top = pos.bottom, left = pos.left;
  7683. node.style.position = "absolute";
  7684. node.setAttribute("cm-ignore-events", "true");
  7685. this.display.input.setUneditable(node);
  7686. display.sizer.appendChild(node);
  7687. if (vert == "over") {
  7688. top = pos.top;
  7689. } else if (vert == "above" || vert == "near") {
  7690. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7691. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7692. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7693. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7694. { top = pos.top - node.offsetHeight; }
  7695. else if (pos.bottom + node.offsetHeight <= vspace)
  7696. { top = pos.bottom; }
  7697. if (left + node.offsetWidth > hspace)
  7698. { left = hspace - node.offsetWidth; }
  7699. }
  7700. node.style.top = top + "px";
  7701. node.style.left = node.style.right = "";
  7702. if (horiz == "right") {
  7703. left = display.sizer.clientWidth - node.offsetWidth;
  7704. node.style.right = "0px";
  7705. } else {
  7706. if (horiz == "left") { left = 0; }
  7707. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7708. node.style.left = left + "px";
  7709. }
  7710. if (scroll)
  7711. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7712. },
  7713. triggerOnKeyDown: methodOp(onKeyDown),
  7714. triggerOnKeyPress: methodOp(onKeyPress),
  7715. triggerOnKeyUp: onKeyUp,
  7716. triggerOnMouseDown: methodOp(onMouseDown),
  7717. execCommand: function(cmd) {
  7718. if (commands.hasOwnProperty(cmd))
  7719. { return commands[cmd].call(null, this) }
  7720. },
  7721. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7722. findPosH: function(from, amount, unit, visually) {
  7723. var dir = 1;
  7724. if (amount < 0) { dir = -1; amount = -amount; }
  7725. var cur = clipPos(this.doc, from);
  7726. for (var i = 0; i < amount; ++i) {
  7727. cur = findPosH(this.doc, cur, dir, unit, visually);
  7728. if (cur.hitSide) { break }
  7729. }
  7730. return cur
  7731. },
  7732. moveH: methodOp(function(dir, unit) {
  7733. var this$1 = this;
  7734. this.extendSelectionsBy(function (range) {
  7735. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7736. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7737. else
  7738. { return dir < 0 ? range.from() : range.to() }
  7739. }, sel_move);
  7740. }),
  7741. deleteH: methodOp(function(dir, unit) {
  7742. var sel = this.doc.sel, doc = this.doc;
  7743. if (sel.somethingSelected())
  7744. { doc.replaceSelection("", null, "+delete"); }
  7745. else
  7746. { deleteNearSelection(this, function (range) {
  7747. var other = findPosH(doc, range.head, dir, unit, false);
  7748. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7749. }); }
  7750. }),
  7751. findPosV: function(from, amount, unit, goalColumn) {
  7752. var dir = 1, x = goalColumn;
  7753. if (amount < 0) { dir = -1; amount = -amount; }
  7754. var cur = clipPos(this.doc, from);
  7755. for (var i = 0; i < amount; ++i) {
  7756. var coords = cursorCoords(this, cur, "div");
  7757. if (x == null) { x = coords.left; }
  7758. else { coords.left = x; }
  7759. cur = findPosV(this, coords, dir, unit);
  7760. if (cur.hitSide) { break }
  7761. }
  7762. return cur
  7763. },
  7764. moveV: methodOp(function(dir, unit) {
  7765. var this$1 = this;
  7766. var doc = this.doc, goals = [];
  7767. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7768. doc.extendSelectionsBy(function (range) {
  7769. if (collapse)
  7770. { return dir < 0 ? range.from() : range.to() }
  7771. var headPos = cursorCoords(this$1, range.head, "div");
  7772. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7773. goals.push(headPos.left);
  7774. var pos = findPosV(this$1, headPos, dir, unit);
  7775. if (unit == "page" && range == doc.sel.primary())
  7776. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7777. return pos
  7778. }, sel_move);
  7779. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7780. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7781. }),
  7782. // Find the word at the given position (as returned by coordsChar).
  7783. findWordAt: function(pos) {
  7784. var doc = this.doc, line = getLine(doc, pos.line).text;
  7785. var start = pos.ch, end = pos.ch;
  7786. if (line) {
  7787. var helper = this.getHelper(pos, "wordChars");
  7788. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7789. var startChar = line.charAt(start);
  7790. var check = isWordChar(startChar, helper)
  7791. ? function (ch) { return isWordChar(ch, helper); }
  7792. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7793. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7794. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7795. while (end < line.length && check(line.charAt(end))) { ++end; }
  7796. }
  7797. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7798. },
  7799. toggleOverwrite: function(value) {
  7800. if (value != null && value == this.state.overwrite) { return }
  7801. if (this.state.overwrite = !this.state.overwrite)
  7802. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7803. else
  7804. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7805. signal(this, "overwriteToggle", this, this.state.overwrite);
  7806. },
  7807. hasFocus: function() { return this.display.input.getField() == activeElt(root(this)) },
  7808. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7809. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7810. getScrollInfo: function() {
  7811. var scroller = this.display.scroller;
  7812. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7813. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7814. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7815. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7816. },
  7817. scrollIntoView: methodOp(function(range, margin) {
  7818. if (range == null) {
  7819. range = {from: this.doc.sel.primary().head, to: null};
  7820. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7821. } else if (typeof range == "number") {
  7822. range = {from: Pos(range, 0), to: null};
  7823. } else if (range.from == null) {
  7824. range = {from: range, to: null};
  7825. }
  7826. if (!range.to) { range.to = range.from; }
  7827. range.margin = margin || 0;
  7828. if (range.from.line != null) {
  7829. scrollToRange(this, range);
  7830. } else {
  7831. scrollToCoordsRange(this, range.from, range.to, range.margin);
  7832. }
  7833. }),
  7834. setSize: methodOp(function(width, height) {
  7835. var this$1 = this;
  7836. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7837. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7838. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7839. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7840. var lineNo = this.display.viewFrom;
  7841. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7842. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7843. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7844. ++lineNo;
  7845. });
  7846. this.curOp.forceUpdate = true;
  7847. signal(this, "refresh", this);
  7848. }),
  7849. operation: function(f){return runInOp(this, f)},
  7850. startOperation: function(){return startOperation(this)},
  7851. endOperation: function(){return endOperation(this)},
  7852. refresh: methodOp(function() {
  7853. var oldHeight = this.display.cachedTextHeight;
  7854. regChange(this);
  7855. this.curOp.forceUpdate = true;
  7856. clearCaches(this);
  7857. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7858. updateGutterSpace(this.display);
  7859. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  7860. { estimateLineHeights(this); }
  7861. signal(this, "refresh", this);
  7862. }),
  7863. swapDoc: methodOp(function(doc) {
  7864. var old = this.doc;
  7865. old.cm = null;
  7866. // Cancel the current text selection if any (#5821)
  7867. if (this.state.selectingText) { this.state.selectingText(); }
  7868. attachDoc(this, doc);
  7869. clearCaches(this);
  7870. this.display.input.reset();
  7871. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7872. this.curOp.forceScroll = true;
  7873. signalLater(this, "swapDoc", this, old);
  7874. return old
  7875. }),
  7876. phrase: function(phraseText) {
  7877. var phrases = this.options.phrases;
  7878. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7879. },
  7880. getInputField: function(){return this.display.input.getField()},
  7881. getWrapperElement: function(){return this.display.wrapper},
  7882. getScrollerElement: function(){return this.display.scroller},
  7883. getGutterElement: function(){return this.display.gutters}
  7884. };
  7885. eventMixin(CodeMirror);
  7886. CodeMirror.registerHelper = function(type, name, value) {
  7887. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7888. helpers[type][name] = value;
  7889. };
  7890. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7891. CodeMirror.registerHelper(type, name, value);
  7892. helpers[type]._global.push({pred: predicate, val: value});
  7893. };
  7894. }
  7895. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7896. // right), unit can be "codepoint", "char", "column" (like char, but
  7897. // doesn't cross line boundaries), "word" (across next word), or
  7898. // "group" (to the start of next group of word or
  7899. // non-word-non-whitespace chars). The visually param controls
  7900. // whether, in right-to-left text, direction 1 means to move towards
  7901. // the next index in the string, or towards the character to the right
  7902. // of the current position. The resulting position will have a
  7903. // hitSide=true property if it reached the end of the document.
  7904. function findPosH(doc, pos, dir, unit, visually) {
  7905. var oldPos = pos;
  7906. var origDir = dir;
  7907. var lineObj = getLine(doc, pos.line);
  7908. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  7909. function findNextLine() {
  7910. var l = pos.line + lineDir;
  7911. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7912. pos = new Pos(l, pos.ch, pos.sticky);
  7913. return lineObj = getLine(doc, l)
  7914. }
  7915. function moveOnce(boundToLine) {
  7916. var next;
  7917. if (unit == "codepoint") {
  7918. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  7919. if (isNaN(ch)) {
  7920. next = null;
  7921. } else {
  7922. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  7923. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  7924. }
  7925. } else if (visually) {
  7926. next = moveVisually(doc.cm, lineObj, pos, dir);
  7927. } else {
  7928. next = moveLogically(lineObj, pos, dir);
  7929. }
  7930. if (next == null) {
  7931. if (!boundToLine && findNextLine())
  7932. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  7933. else
  7934. { return false }
  7935. } else {
  7936. pos = next;
  7937. }
  7938. return true
  7939. }
  7940. if (unit == "char" || unit == "codepoint") {
  7941. moveOnce();
  7942. } else if (unit == "column") {
  7943. moveOnce(true);
  7944. } else if (unit == "word" || unit == "group") {
  7945. var sawType = null, group = unit == "group";
  7946. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7947. for (var first = true;; first = false) {
  7948. if (dir < 0 && !moveOnce(!first)) { break }
  7949. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7950. var type = isWordChar(cur, helper) ? "w"
  7951. : group && cur == "\n" ? "n"
  7952. : !group || /\s/.test(cur) ? null
  7953. : "p";
  7954. if (group && !first && !type) { type = "s"; }
  7955. if (sawType && sawType != type) {
  7956. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7957. break
  7958. }
  7959. if (type) { sawType = type; }
  7960. if (dir > 0 && !moveOnce(!first)) { break }
  7961. }
  7962. }
  7963. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7964. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7965. return result
  7966. }
  7967. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7968. // "page" or "line". The resulting position will have a hitSide=true
  7969. // property if it reached the end of the document.
  7970. function findPosV(cm, pos, dir, unit) {
  7971. var doc = cm.doc, x = pos.left, y;
  7972. if (unit == "page") {
  7973. var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
  7974. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7975. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7976. } else if (unit == "line") {
  7977. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7978. }
  7979. var target;
  7980. for (;;) {
  7981. target = coordsChar(cm, x, y);
  7982. if (!target.outside) { break }
  7983. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7984. y += dir * 5;
  7985. }
  7986. return target
  7987. }
  7988. // CONTENTEDITABLE INPUT STYLE
  7989. var ContentEditableInput = function(cm) {
  7990. this.cm = cm;
  7991. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7992. this.polling = new Delayed();
  7993. this.composing = null;
  7994. this.gracePeriod = false;
  7995. this.readDOMTimeout = null;
  7996. };
  7997. ContentEditableInput.prototype.init = function (display) {
  7998. var this$1 = this;
  7999. var input = this, cm = input.cm;
  8000. var div = input.div = display.lineDiv;
  8001. div.contentEditable = true;
  8002. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  8003. function belongsToInput(e) {
  8004. for (var t = e.target; t; t = t.parentNode) {
  8005. if (t == div) { return true }
  8006. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  8007. }
  8008. return false
  8009. }
  8010. on(div, "paste", function (e) {
  8011. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8012. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  8013. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  8014. });
  8015. on(div, "compositionstart", function (e) {
  8016. this$1.composing = {data: e.data, done: false};
  8017. });
  8018. on(div, "compositionupdate", function (e) {
  8019. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  8020. });
  8021. on(div, "compositionend", function (e) {
  8022. if (this$1.composing) {
  8023. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  8024. this$1.composing.done = true;
  8025. }
  8026. });
  8027. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8028. on(div, "input", function () {
  8029. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8030. });
  8031. function onCopyCut(e) {
  8032. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8033. if (cm.somethingSelected()) {
  8034. setLastCopied({lineWise: false, text: cm.getSelections()});
  8035. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8036. } else if (!cm.options.lineWiseCopyCut) {
  8037. return
  8038. } else {
  8039. var ranges = copyableRanges(cm);
  8040. setLastCopied({lineWise: true, text: ranges.text});
  8041. if (e.type == "cut") {
  8042. cm.operation(function () {
  8043. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8044. cm.replaceSelection("", null, "cut");
  8045. });
  8046. }
  8047. }
  8048. if (e.clipboardData) {
  8049. e.clipboardData.clearData();
  8050. var content = lastCopied.text.join("\n");
  8051. // iOS exposes the clipboard API, but seems to discard content inserted into it
  8052. e.clipboardData.setData("Text", content);
  8053. if (e.clipboardData.getData("Text") == content) {
  8054. e.preventDefault();
  8055. return
  8056. }
  8057. }
  8058. // Old-fashioned briefly-focus-a-textarea hack
  8059. var kludge = hiddenTextarea(), te = kludge.firstChild;
  8060. disableBrowserMagic(te);
  8061. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8062. te.value = lastCopied.text.join("\n");
  8063. var hadFocus = activeElt(rootNode(div));
  8064. selectInput(te);
  8065. setTimeout(function () {
  8066. cm.display.lineSpace.removeChild(kludge);
  8067. hadFocus.focus();
  8068. if (hadFocus == div) { input.showPrimarySelection(); }
  8069. }, 50);
  8070. }
  8071. on(div, "copy", onCopyCut);
  8072. on(div, "cut", onCopyCut);
  8073. };
  8074. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8075. // Label for screenreaders, accessibility
  8076. if(label) {
  8077. this.div.setAttribute('aria-label', label);
  8078. } else {
  8079. this.div.removeAttribute('aria-label');
  8080. }
  8081. };
  8082. ContentEditableInput.prototype.prepareSelection = function () {
  8083. var result = prepareSelection(this.cm, false);
  8084. result.focus = activeElt(rootNode(this.div)) == this.div;
  8085. return result
  8086. };
  8087. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8088. if (!info || !this.cm.display.view.length) { return }
  8089. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8090. this.showMultipleSelections(info);
  8091. };
  8092. ContentEditableInput.prototype.getSelection = function () {
  8093. return this.cm.display.wrapper.ownerDocument.getSelection()
  8094. };
  8095. ContentEditableInput.prototype.showPrimarySelection = function () {
  8096. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8097. var from = prim.from(), to = prim.to();
  8098. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8099. sel.removeAllRanges();
  8100. return
  8101. }
  8102. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8103. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8104. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8105. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8106. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8107. { return }
  8108. var view = cm.display.view;
  8109. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8110. {node: view[0].measure.map[2], offset: 0};
  8111. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8112. if (!end) {
  8113. var measure = view[view.length - 1].measure;
  8114. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8115. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8116. }
  8117. if (!start || !end) {
  8118. sel.removeAllRanges();
  8119. return
  8120. }
  8121. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8122. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8123. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8124. if (rng) {
  8125. if (!gecko && cm.state.focused) {
  8126. sel.collapse(start.node, start.offset);
  8127. if (!rng.collapsed) {
  8128. sel.removeAllRanges();
  8129. sel.addRange(rng);
  8130. }
  8131. } else {
  8132. sel.removeAllRanges();
  8133. sel.addRange(rng);
  8134. }
  8135. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8136. else if (gecko) { this.startGracePeriod(); }
  8137. }
  8138. this.rememberSelection();
  8139. };
  8140. ContentEditableInput.prototype.startGracePeriod = function () {
  8141. var this$1 = this;
  8142. clearTimeout(this.gracePeriod);
  8143. this.gracePeriod = setTimeout(function () {
  8144. this$1.gracePeriod = false;
  8145. if (this$1.selectionChanged())
  8146. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8147. }, 20);
  8148. };
  8149. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8150. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8151. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8152. };
  8153. ContentEditableInput.prototype.rememberSelection = function () {
  8154. var sel = this.getSelection();
  8155. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8156. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8157. };
  8158. ContentEditableInput.prototype.selectionInEditor = function () {
  8159. var sel = this.getSelection();
  8160. if (!sel.rangeCount) { return false }
  8161. var node = sel.getRangeAt(0).commonAncestorContainer;
  8162. return contains(this.div, node)
  8163. };
  8164. ContentEditableInput.prototype.focus = function () {
  8165. if (this.cm.options.readOnly != "nocursor") {
  8166. if (!this.selectionInEditor() || activeElt(rootNode(this.div)) != this.div)
  8167. { this.showSelection(this.prepareSelection(), true); }
  8168. this.div.focus();
  8169. }
  8170. };
  8171. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8172. ContentEditableInput.prototype.getField = function () { return this.div };
  8173. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8174. ContentEditableInput.prototype.receivedFocus = function () {
  8175. var this$1 = this;
  8176. var input = this;
  8177. if (this.selectionInEditor())
  8178. { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  8179. else
  8180. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8181. function poll() {
  8182. if (input.cm.state.focused) {
  8183. input.pollSelection();
  8184. input.polling.set(input.cm.options.pollInterval, poll);
  8185. }
  8186. }
  8187. this.polling.set(this.cm.options.pollInterval, poll);
  8188. };
  8189. ContentEditableInput.prototype.selectionChanged = function () {
  8190. var sel = this.getSelection();
  8191. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8192. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8193. };
  8194. ContentEditableInput.prototype.pollSelection = function () {
  8195. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8196. var sel = this.getSelection(), cm = this.cm;
  8197. // On Android Chrome (version 56, at least), backspacing into an
  8198. // uneditable block element will put the cursor in that element,
  8199. // and then, because it's not editable, hide the virtual keyboard.
  8200. // Because Android doesn't allow us to actually detect backspace
  8201. // presses in a sane way, this code checks for when that happens
  8202. // and simulates a backspace press in this case.
  8203. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8204. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8205. this.blur();
  8206. this.focus();
  8207. return
  8208. }
  8209. if (this.composing) { return }
  8210. this.rememberSelection();
  8211. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8212. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8213. if (anchor && head) { runInOp(cm, function () {
  8214. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8215. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8216. }); }
  8217. };
  8218. ContentEditableInput.prototype.pollContent = function () {
  8219. if (this.readDOMTimeout != null) {
  8220. clearTimeout(this.readDOMTimeout);
  8221. this.readDOMTimeout = null;
  8222. }
  8223. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8224. var from = sel.from(), to = sel.to();
  8225. if (from.ch == 0 && from.line > cm.firstLine())
  8226. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8227. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8228. { to = Pos(to.line + 1, 0); }
  8229. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8230. var fromIndex, fromLine, fromNode;
  8231. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8232. fromLine = lineNo(display.view[0].line);
  8233. fromNode = display.view[0].node;
  8234. } else {
  8235. fromLine = lineNo(display.view[fromIndex].line);
  8236. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8237. }
  8238. var toIndex = findViewIndex(cm, to.line);
  8239. var toLine, toNode;
  8240. if (toIndex == display.view.length - 1) {
  8241. toLine = display.viewTo - 1;
  8242. toNode = display.lineDiv.lastChild;
  8243. } else {
  8244. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8245. toNode = display.view[toIndex + 1].node.previousSibling;
  8246. }
  8247. if (!fromNode) { return false }
  8248. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8249. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8250. while (newText.length > 1 && oldText.length > 1) {
  8251. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8252. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8253. else { break }
  8254. }
  8255. var cutFront = 0, cutEnd = 0;
  8256. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8257. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8258. { ++cutFront; }
  8259. var newBot = lst(newText), oldBot = lst(oldText);
  8260. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8261. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8262. while (cutEnd < maxCutEnd &&
  8263. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8264. { ++cutEnd; }
  8265. // Try to move start of change to start of selection if ambiguous
  8266. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8267. while (cutFront && cutFront > from.ch &&
  8268. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8269. cutFront--;
  8270. cutEnd++;
  8271. }
  8272. }
  8273. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8274. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8275. var chFrom = Pos(fromLine, cutFront);
  8276. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8277. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8278. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8279. return true
  8280. }
  8281. };
  8282. ContentEditableInput.prototype.ensurePolled = function () {
  8283. this.forceCompositionEnd();
  8284. };
  8285. ContentEditableInput.prototype.reset = function () {
  8286. this.forceCompositionEnd();
  8287. };
  8288. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8289. if (!this.composing) { return }
  8290. clearTimeout(this.readDOMTimeout);
  8291. this.composing = null;
  8292. this.updateFromDOM();
  8293. this.div.blur();
  8294. this.div.focus();
  8295. };
  8296. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8297. var this$1 = this;
  8298. if (this.readDOMTimeout != null) { return }
  8299. this.readDOMTimeout = setTimeout(function () {
  8300. this$1.readDOMTimeout = null;
  8301. if (this$1.composing) {
  8302. if (this$1.composing.done) { this$1.composing = null; }
  8303. else { return }
  8304. }
  8305. this$1.updateFromDOM();
  8306. }, 80);
  8307. };
  8308. ContentEditableInput.prototype.updateFromDOM = function () {
  8309. var this$1 = this;
  8310. if (this.cm.isReadOnly() || !this.pollContent())
  8311. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8312. };
  8313. ContentEditableInput.prototype.setUneditable = function (node) {
  8314. node.contentEditable = "false";
  8315. };
  8316. ContentEditableInput.prototype.onKeyPress = function (e) {
  8317. if (e.charCode == 0 || this.composing) { return }
  8318. e.preventDefault();
  8319. if (!this.cm.isReadOnly())
  8320. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8321. };
  8322. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8323. this.div.contentEditable = String(val != "nocursor");
  8324. };
  8325. ContentEditableInput.prototype.onContextMenu = function () {};
  8326. ContentEditableInput.prototype.resetPosition = function () {};
  8327. ContentEditableInput.prototype.needsContentAttribute = true;
  8328. function posToDOM(cm, pos) {
  8329. var view = findViewForLine(cm, pos.line);
  8330. if (!view || view.hidden) { return null }
  8331. var line = getLine(cm.doc, pos.line);
  8332. var info = mapFromLineView(view, line, pos.line);
  8333. var order = getOrder(line, cm.doc.direction), side = "left";
  8334. if (order) {
  8335. var partPos = getBidiPartAt(order, pos.ch);
  8336. side = partPos % 2 ? "right" : "left";
  8337. }
  8338. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8339. result.offset = result.collapse == "right" ? result.end : result.start;
  8340. return result
  8341. }
  8342. function isInGutter(node) {
  8343. for (var scan = node; scan; scan = scan.parentNode)
  8344. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8345. return false
  8346. }
  8347. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8348. function domTextBetween(cm, from, to, fromLine, toLine) {
  8349. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8350. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8351. function close() {
  8352. if (closing) {
  8353. text += lineSep;
  8354. if (extraLinebreak) { text += lineSep; }
  8355. closing = extraLinebreak = false;
  8356. }
  8357. }
  8358. function addText(str) {
  8359. if (str) {
  8360. close();
  8361. text += str;
  8362. }
  8363. }
  8364. function walk(node) {
  8365. if (node.nodeType == 1) {
  8366. var cmText = node.getAttribute("cm-text");
  8367. if (cmText) {
  8368. addText(cmText);
  8369. return
  8370. }
  8371. var markerID = node.getAttribute("cm-marker"), range;
  8372. if (markerID) {
  8373. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8374. if (found.length && (range = found[0].find(0)))
  8375. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8376. return
  8377. }
  8378. if (node.getAttribute("contenteditable") == "false") { return }
  8379. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8380. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8381. if (isBlock) { close(); }
  8382. for (var i = 0; i < node.childNodes.length; i++)
  8383. { walk(node.childNodes[i]); }
  8384. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8385. if (isBlock) { closing = true; }
  8386. } else if (node.nodeType == 3) {
  8387. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8388. }
  8389. }
  8390. for (;;) {
  8391. walk(from);
  8392. if (from == to) { break }
  8393. from = from.nextSibling;
  8394. extraLinebreak = false;
  8395. }
  8396. return text
  8397. }
  8398. function domToPos(cm, node, offset) {
  8399. var lineNode;
  8400. if (node == cm.display.lineDiv) {
  8401. lineNode = cm.display.lineDiv.childNodes[offset];
  8402. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8403. node = null; offset = 0;
  8404. } else {
  8405. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8406. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8407. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8408. }
  8409. }
  8410. for (var i = 0; i < cm.display.view.length; i++) {
  8411. var lineView = cm.display.view[i];
  8412. if (lineView.node == lineNode)
  8413. { return locateNodeInLineView(lineView, node, offset) }
  8414. }
  8415. }
  8416. function locateNodeInLineView(lineView, node, offset) {
  8417. var wrapper = lineView.text.firstChild, bad = false;
  8418. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8419. if (node == wrapper) {
  8420. bad = true;
  8421. node = wrapper.childNodes[offset];
  8422. offset = 0;
  8423. if (!node) {
  8424. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8425. return badPos(Pos(lineNo(line), line.text.length), bad)
  8426. }
  8427. }
  8428. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8429. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8430. textNode = node.firstChild;
  8431. if (offset) { offset = textNode.nodeValue.length; }
  8432. }
  8433. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8434. var measure = lineView.measure, maps = measure.maps;
  8435. function find(textNode, topNode, offset) {
  8436. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8437. var map = i < 0 ? measure.map : maps[i];
  8438. for (var j = 0; j < map.length; j += 3) {
  8439. var curNode = map[j + 2];
  8440. if (curNode == textNode || curNode == topNode) {
  8441. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8442. var ch = map[j] + offset;
  8443. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8444. return Pos(line, ch)
  8445. }
  8446. }
  8447. }
  8448. }
  8449. var found = find(textNode, topNode, offset);
  8450. if (found) { return badPos(found, bad) }
  8451. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8452. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8453. found = find(after, after.firstChild, 0);
  8454. if (found)
  8455. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8456. else
  8457. { dist += after.textContent.length; }
  8458. }
  8459. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8460. found = find(before, before.firstChild, -1);
  8461. if (found)
  8462. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8463. else
  8464. { dist$1 += before.textContent.length; }
  8465. }
  8466. }
  8467. // TEXTAREA INPUT STYLE
  8468. var TextareaInput = function(cm) {
  8469. this.cm = cm;
  8470. // See input.poll and input.reset
  8471. this.prevInput = "";
  8472. // Flag that indicates whether we expect input to appear real soon
  8473. // now (after some event like 'keypress' or 'input') and are
  8474. // polling intensively.
  8475. this.pollingFast = false;
  8476. // Self-resetting timeout for the poller
  8477. this.polling = new Delayed();
  8478. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8479. this.hasSelection = false;
  8480. this.composing = null;
  8481. this.resetting = false;
  8482. };
  8483. TextareaInput.prototype.init = function (display) {
  8484. var this$1 = this;
  8485. var input = this, cm = this.cm;
  8486. this.createField(display);
  8487. var te = this.textarea;
  8488. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8489. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8490. if (ios) { te.style.width = "0px"; }
  8491. on(te, "input", function () {
  8492. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8493. input.poll();
  8494. });
  8495. on(te, "paste", function (e) {
  8496. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8497. cm.state.pasteIncoming = +new Date;
  8498. input.fastPoll();
  8499. });
  8500. function prepareCopyCut(e) {
  8501. if (signalDOMEvent(cm, e)) { return }
  8502. if (cm.somethingSelected()) {
  8503. setLastCopied({lineWise: false, text: cm.getSelections()});
  8504. } else if (!cm.options.lineWiseCopyCut) {
  8505. return
  8506. } else {
  8507. var ranges = copyableRanges(cm);
  8508. setLastCopied({lineWise: true, text: ranges.text});
  8509. if (e.type == "cut") {
  8510. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8511. } else {
  8512. input.prevInput = "";
  8513. te.value = ranges.text.join("\n");
  8514. selectInput(te);
  8515. }
  8516. }
  8517. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8518. }
  8519. on(te, "cut", prepareCopyCut);
  8520. on(te, "copy", prepareCopyCut);
  8521. on(display.scroller, "paste", function (e) {
  8522. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8523. if (!te.dispatchEvent) {
  8524. cm.state.pasteIncoming = +new Date;
  8525. input.focus();
  8526. return
  8527. }
  8528. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8529. var event = new Event("paste");
  8530. event.clipboardData = e.clipboardData;
  8531. te.dispatchEvent(event);
  8532. });
  8533. // Prevent normal selection in the editor (we handle our own)
  8534. on(display.lineSpace, "selectstart", function (e) {
  8535. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8536. });
  8537. on(te, "compositionstart", function () {
  8538. var start = cm.getCursor("from");
  8539. if (input.composing) { input.composing.range.clear(); }
  8540. input.composing = {
  8541. start: start,
  8542. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8543. };
  8544. });
  8545. on(te, "compositionend", function () {
  8546. if (input.composing) {
  8547. input.poll();
  8548. input.composing.range.clear();
  8549. input.composing = null;
  8550. }
  8551. });
  8552. };
  8553. TextareaInput.prototype.createField = function (_display) {
  8554. // Wraps and hides input textarea
  8555. this.wrapper = hiddenTextarea();
  8556. // The semihidden textarea that is focused when the editor is
  8557. // focused, and receives input.
  8558. this.textarea = this.wrapper.firstChild;
  8559. var opts = this.cm.options;
  8560. disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
  8561. };
  8562. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8563. // Label for screenreaders, accessibility
  8564. if(label) {
  8565. this.textarea.setAttribute('aria-label', label);
  8566. } else {
  8567. this.textarea.removeAttribute('aria-label');
  8568. }
  8569. };
  8570. TextareaInput.prototype.prepareSelection = function () {
  8571. // Redraw the selection and/or cursor
  8572. var cm = this.cm, display = cm.display, doc = cm.doc;
  8573. var result = prepareSelection(cm);
  8574. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8575. if (cm.options.moveInputWithCursor) {
  8576. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8577. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8578. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8579. headPos.top + lineOff.top - wrapOff.top));
  8580. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8581. headPos.left + lineOff.left - wrapOff.left));
  8582. }
  8583. return result
  8584. };
  8585. TextareaInput.prototype.showSelection = function (drawn) {
  8586. var cm = this.cm, display = cm.display;
  8587. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8588. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8589. if (drawn.teTop != null) {
  8590. this.wrapper.style.top = drawn.teTop + "px";
  8591. this.wrapper.style.left = drawn.teLeft + "px";
  8592. }
  8593. };
  8594. // Reset the input to correspond to the selection (or to be empty,
  8595. // when not typing and nothing is selected)
  8596. TextareaInput.prototype.reset = function (typing) {
  8597. if (this.contextMenuPending || this.composing && typing) { return }
  8598. var cm = this.cm;
  8599. this.resetting = true;
  8600. if (cm.somethingSelected()) {
  8601. this.prevInput = "";
  8602. var content = cm.getSelection();
  8603. this.textarea.value = content;
  8604. if (cm.state.focused) { selectInput(this.textarea); }
  8605. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8606. } else if (!typing) {
  8607. this.prevInput = this.textarea.value = "";
  8608. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8609. }
  8610. this.resetting = false;
  8611. };
  8612. TextareaInput.prototype.getField = function () { return this.textarea };
  8613. TextareaInput.prototype.supportsTouch = function () { return false };
  8614. TextareaInput.prototype.focus = function () {
  8615. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(rootNode(this.textarea)) != this.textarea)) {
  8616. try { this.textarea.focus(); }
  8617. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8618. }
  8619. };
  8620. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8621. TextareaInput.prototype.resetPosition = function () {
  8622. this.wrapper.style.top = this.wrapper.style.left = 0;
  8623. };
  8624. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8625. // Poll for input changes, using the normal rate of polling. This
  8626. // runs as long as the editor is focused.
  8627. TextareaInput.prototype.slowPoll = function () {
  8628. var this$1 = this;
  8629. if (this.pollingFast) { return }
  8630. this.polling.set(this.cm.options.pollInterval, function () {
  8631. this$1.poll();
  8632. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8633. });
  8634. };
  8635. // When an event has just come in that is likely to add or change
  8636. // something in the input textarea, we poll faster, to ensure that
  8637. // the change appears on the screen quickly.
  8638. TextareaInput.prototype.fastPoll = function () {
  8639. var missed = false, input = this;
  8640. input.pollingFast = true;
  8641. function p() {
  8642. var changed = input.poll();
  8643. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8644. else {input.pollingFast = false; input.slowPoll();}
  8645. }
  8646. input.polling.set(20, p);
  8647. };
  8648. // Read input from the textarea, and update the document to match.
  8649. // When something is selected, it is present in the textarea, and
  8650. // selected (unless it is huge, in which case a placeholder is
  8651. // used). When nothing is selected, the cursor sits after previously
  8652. // seen text (can be empty), which is stored in prevInput (we must
  8653. // not reset the textarea when typing, because that breaks IME).
  8654. TextareaInput.prototype.poll = function () {
  8655. var this$1 = this;
  8656. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8657. // Since this is called a *lot*, try to bail out as cheaply as
  8658. // possible when it is clear that nothing happened. hasSelection
  8659. // will be the case when there is a lot of text in the textarea,
  8660. // in which case reading its value would be expensive.
  8661. if (this.contextMenuPending || this.resetting || !cm.state.focused ||
  8662. (hasSelection(input) && !prevInput && !this.composing) ||
  8663. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8664. { return false }
  8665. var text = input.value;
  8666. // If nothing changed, bail.
  8667. if (text == prevInput && !cm.somethingSelected()) { return false }
  8668. // Work around nonsensical selection resetting in IE9/10, and
  8669. // inexplicable appearance of private area unicode characters on
  8670. // some key combos in Mac (#2689).
  8671. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8672. mac && /[\uf700-\uf7ff]/.test(text)) {
  8673. cm.display.input.reset();
  8674. return false
  8675. }
  8676. if (cm.doc.sel == cm.display.selForContextMenu) {
  8677. var first = text.charCodeAt(0);
  8678. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8679. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8680. }
  8681. // Find the part of the input that is actually new
  8682. var same = 0, l = Math.min(prevInput.length, text.length);
  8683. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8684. runInOp(cm, function () {
  8685. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8686. null, this$1.composing ? "*compose" : null);
  8687. // Don't leave long text in the textarea, since it makes further polling slow
  8688. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8689. else { this$1.prevInput = text; }
  8690. if (this$1.composing) {
  8691. this$1.composing.range.clear();
  8692. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8693. {className: "CodeMirror-composing"});
  8694. }
  8695. });
  8696. return true
  8697. };
  8698. TextareaInput.prototype.ensurePolled = function () {
  8699. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8700. };
  8701. TextareaInput.prototype.onKeyPress = function () {
  8702. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8703. this.fastPoll();
  8704. };
  8705. TextareaInput.prototype.onContextMenu = function (e) {
  8706. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8707. if (input.contextMenuPending) { input.contextMenuPending(); }
  8708. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8709. if (!pos || presto) { return } // Opera is difficult.
  8710. // Reset the current text selection only if the click is done outside of the selection
  8711. // and 'resetSelectionOnContextMenu' option is true.
  8712. var reset = cm.options.resetSelectionOnContextMenu;
  8713. if (reset && cm.doc.sel.contains(pos) == -1)
  8714. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8715. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8716. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8717. input.wrapper.style.cssText = "position: static";
  8718. 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);";
  8719. var oldScrollY;
  8720. if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
  8721. display.input.focus();
  8722. if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
  8723. display.input.reset();
  8724. // Adds "Select all" to context menu in FF
  8725. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8726. input.contextMenuPending = rehide;
  8727. display.selForContextMenu = cm.doc.sel;
  8728. clearTimeout(display.detectingSelectAll);
  8729. // Select-all will be greyed out if there's nothing to select, so
  8730. // this adds a zero-width space so that we can later check whether
  8731. // it got selected.
  8732. function prepareSelectAllHack() {
  8733. if (te.selectionStart != null) {
  8734. var selected = cm.somethingSelected();
  8735. var extval = "\u200b" + (selected ? te.value : "");
  8736. te.value = "\u21da"; // Used to catch context-menu undo
  8737. te.value = extval;
  8738. input.prevInput = selected ? "" : "\u200b";
  8739. te.selectionStart = 1; te.selectionEnd = extval.length;
  8740. // Re-set this, in case some other handler touched the
  8741. // selection in the meantime.
  8742. display.selForContextMenu = cm.doc.sel;
  8743. }
  8744. }
  8745. function rehide() {
  8746. if (input.contextMenuPending != rehide) { return }
  8747. input.contextMenuPending = false;
  8748. input.wrapper.style.cssText = oldWrapperCSS;
  8749. te.style.cssText = oldCSS;
  8750. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8751. // Try to detect the user choosing select-all
  8752. if (te.selectionStart != null) {
  8753. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8754. var i = 0, poll = function () {
  8755. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8756. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8757. operation(cm, selectAll)(cm);
  8758. } else if (i++ < 10) {
  8759. display.detectingSelectAll = setTimeout(poll, 500);
  8760. } else {
  8761. display.selForContextMenu = null;
  8762. display.input.reset();
  8763. }
  8764. };
  8765. display.detectingSelectAll = setTimeout(poll, 200);
  8766. }
  8767. }
  8768. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8769. if (captureRightClick) {
  8770. e_stop(e);
  8771. var mouseup = function () {
  8772. off(window, "mouseup", mouseup);
  8773. setTimeout(rehide, 20);
  8774. };
  8775. on(window, "mouseup", mouseup);
  8776. } else {
  8777. setTimeout(rehide, 50);
  8778. }
  8779. };
  8780. TextareaInput.prototype.readOnlyChanged = function (val) {
  8781. if (!val) { this.reset(); }
  8782. this.textarea.disabled = val == "nocursor";
  8783. this.textarea.readOnly = !!val;
  8784. };
  8785. TextareaInput.prototype.setUneditable = function () {};
  8786. TextareaInput.prototype.needsContentAttribute = false;
  8787. function fromTextArea(textarea, options) {
  8788. options = options ? copyObj(options) : {};
  8789. options.value = textarea.value;
  8790. if (!options.tabindex && textarea.tabIndex)
  8791. { options.tabindex = textarea.tabIndex; }
  8792. if (!options.placeholder && textarea.placeholder)
  8793. { options.placeholder = textarea.placeholder; }
  8794. // Set autofocus to true if this textarea is focused, or if it has
  8795. // autofocus and no other element is focused.
  8796. if (options.autofocus == null) {
  8797. var hasFocus = activeElt(rootNode(textarea));
  8798. options.autofocus = hasFocus == textarea ||
  8799. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8800. }
  8801. function save() {textarea.value = cm.getValue();}
  8802. var realSubmit;
  8803. if (textarea.form) {
  8804. on(textarea.form, "submit", save);
  8805. // Deplorable hack to make the submit method do the right thing.
  8806. if (!options.leaveSubmitMethodAlone) {
  8807. var form = textarea.form;
  8808. realSubmit = form.submit;
  8809. try {
  8810. var wrappedSubmit = form.submit = function () {
  8811. save();
  8812. form.submit = realSubmit;
  8813. form.submit();
  8814. form.submit = wrappedSubmit;
  8815. };
  8816. } catch(e) {}
  8817. }
  8818. }
  8819. options.finishInit = function (cm) {
  8820. cm.save = save;
  8821. cm.getTextArea = function () { return textarea; };
  8822. cm.toTextArea = function () {
  8823. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8824. save();
  8825. textarea.parentNode.removeChild(cm.getWrapperElement());
  8826. textarea.style.display = "";
  8827. if (textarea.form) {
  8828. off(textarea.form, "submit", save);
  8829. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  8830. { textarea.form.submit = realSubmit; }
  8831. }
  8832. };
  8833. };
  8834. textarea.style.display = "none";
  8835. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8836. options);
  8837. return cm
  8838. }
  8839. function addLegacyProps(CodeMirror) {
  8840. CodeMirror.off = off;
  8841. CodeMirror.on = on;
  8842. CodeMirror.wheelEventPixels = wheelEventPixels;
  8843. CodeMirror.Doc = Doc;
  8844. CodeMirror.splitLines = splitLinesAuto;
  8845. CodeMirror.countColumn = countColumn;
  8846. CodeMirror.findColumn = findColumn;
  8847. CodeMirror.isWordChar = isWordCharBasic;
  8848. CodeMirror.Pass = Pass;
  8849. CodeMirror.signal = signal;
  8850. CodeMirror.Line = Line;
  8851. CodeMirror.changeEnd = changeEnd;
  8852. CodeMirror.scrollbarModel = scrollbarModel;
  8853. CodeMirror.Pos = Pos;
  8854. CodeMirror.cmpPos = cmp;
  8855. CodeMirror.modes = modes;
  8856. CodeMirror.mimeModes = mimeModes;
  8857. CodeMirror.resolveMode = resolveMode;
  8858. CodeMirror.getMode = getMode;
  8859. CodeMirror.modeExtensions = modeExtensions;
  8860. CodeMirror.extendMode = extendMode;
  8861. CodeMirror.copyState = copyState;
  8862. CodeMirror.startState = startState;
  8863. CodeMirror.innerMode = innerMode;
  8864. CodeMirror.commands = commands;
  8865. CodeMirror.keyMap = keyMap;
  8866. CodeMirror.keyName = keyName;
  8867. CodeMirror.isModifierKey = isModifierKey;
  8868. CodeMirror.lookupKey = lookupKey;
  8869. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8870. CodeMirror.StringStream = StringStream;
  8871. CodeMirror.SharedTextMarker = SharedTextMarker;
  8872. CodeMirror.TextMarker = TextMarker;
  8873. CodeMirror.LineWidget = LineWidget;
  8874. CodeMirror.e_preventDefault = e_preventDefault;
  8875. CodeMirror.e_stopPropagation = e_stopPropagation;
  8876. CodeMirror.e_stop = e_stop;
  8877. CodeMirror.addClass = addClass;
  8878. CodeMirror.contains = contains;
  8879. CodeMirror.rmClass = rmClass;
  8880. CodeMirror.keyNames = keyNames;
  8881. }
  8882. // EDITOR CONSTRUCTOR
  8883. defineOptions(CodeMirror);
  8884. addEditorMethods(CodeMirror);
  8885. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8886. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8887. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8888. { CodeMirror.prototype[prop] = (function(method) {
  8889. return function() {return method.apply(this.doc, arguments)}
  8890. })(Doc.prototype[prop]); } }
  8891. eventMixin(Doc);
  8892. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8893. // Extra arguments are stored as the mode's dependencies, which is
  8894. // used by (legacy) mechanisms like loadmode.js to automatically
  8895. // load a mode. (Preferred mechanism is the require/define calls.)
  8896. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8897. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8898. defineMode.apply(this, arguments);
  8899. };
  8900. CodeMirror.defineMIME = defineMIME;
  8901. // Minimal default mode.
  8902. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8903. CodeMirror.defineMIME("text/plain", "null");
  8904. // EXTENSIONS
  8905. CodeMirror.defineExtension = function (name, func) {
  8906. CodeMirror.prototype[name] = func;
  8907. };
  8908. CodeMirror.defineDocExtension = function (name, func) {
  8909. Doc.prototype[name] = func;
  8910. };
  8911. CodeMirror.fromTextArea = fromTextArea;
  8912. addLegacyProps(CodeMirror);
  8913. CodeMirror.version = "5.65.16";
  8914. return CodeMirror;
  8915. })));