国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
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.

9873 lines
392KB

  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(doc) {
  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 activeElement;
  106. try {
  107. activeElement = doc.activeElement;
  108. } catch(e) {
  109. activeElement = doc.body || null;
  110. }
  111. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  112. { activeElement = activeElement.shadowRoot.activeElement; }
  113. return activeElement
  114. }
  115. function addClass(node, cls) {
  116. var current = node.className;
  117. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  118. }
  119. function joinClasses(a, b) {
  120. var as = a.split(" ");
  121. for (var i = 0; i < as.length; i++)
  122. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  123. return b
  124. }
  125. var selectInput = function(node) { node.select(); };
  126. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  127. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  128. else if (ie) // Suppress mysterious IE10 errors
  129. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  130. function doc(cm) { return cm.display.wrapper.ownerDocument }
  131. function win(cm) { return doc(cm).defaultView }
  132. function bind(f) {
  133. var args = Array.prototype.slice.call(arguments, 1);
  134. return function(){return f.apply(null, args)}
  135. }
  136. function copyObj(obj, target, overwrite) {
  137. if (!target) { target = {}; }
  138. for (var prop in obj)
  139. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  140. { target[prop] = obj[prop]; } }
  141. return target
  142. }
  143. // Counts the column offset in a string, taking tabs into account.
  144. // Used mostly to find indentation.
  145. function countColumn(string, end, tabSize, startIndex, startValue) {
  146. if (end == null) {
  147. end = string.search(/[^\s\u00a0]/);
  148. if (end == -1) { end = string.length; }
  149. }
  150. for (var i = startIndex || 0, n = startValue || 0;;) {
  151. var nextTab = string.indexOf("\t", i);
  152. if (nextTab < 0 || nextTab >= end)
  153. { return n + (end - i) }
  154. n += nextTab - i;
  155. n += tabSize - (n % tabSize);
  156. i = nextTab + 1;
  157. }
  158. }
  159. var Delayed = function() {
  160. this.id = null;
  161. this.f = null;
  162. this.time = 0;
  163. this.handler = bind(this.onTimeout, this);
  164. };
  165. Delayed.prototype.onTimeout = function (self) {
  166. self.id = 0;
  167. if (self.time <= +new Date) {
  168. self.f();
  169. } else {
  170. setTimeout(self.handler, self.time - +new Date);
  171. }
  172. };
  173. Delayed.prototype.set = function (ms, f) {
  174. this.f = f;
  175. var time = +new Date + ms;
  176. if (!this.id || time < this.time) {
  177. clearTimeout(this.id);
  178. this.id = setTimeout(this.handler, ms);
  179. this.time = time;
  180. }
  181. };
  182. function indexOf(array, elt) {
  183. for (var i = 0; i < array.length; ++i)
  184. { if (array[i] == elt) { return i } }
  185. return -1
  186. }
  187. // Number of pixels added to scroller and sizer to hide scrollbar
  188. var scrollerGap = 50;
  189. // Returned or thrown by various protocols to signal 'I'm not
  190. // handling this'.
  191. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  192. // Reused option objects for setSelection & friends
  193. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  194. // The inverse of countColumn -- find the offset that corresponds to
  195. // a particular column.
  196. function findColumn(string, goal, tabSize) {
  197. for (var pos = 0, col = 0;;) {
  198. var nextTab = string.indexOf("\t", pos);
  199. if (nextTab == -1) { nextTab = string.length; }
  200. var skipped = nextTab - pos;
  201. if (nextTab == string.length || col + skipped >= goal)
  202. { return pos + Math.min(skipped, goal - col) }
  203. col += nextTab - pos;
  204. col += tabSize - (col % tabSize);
  205. pos = nextTab + 1;
  206. if (col >= goal) { return pos }
  207. }
  208. }
  209. var spaceStrs = [""];
  210. function spaceStr(n) {
  211. while (spaceStrs.length <= n)
  212. { spaceStrs.push(lst(spaceStrs) + " "); }
  213. return spaceStrs[n]
  214. }
  215. function lst(arr) { return arr[arr.length-1] }
  216. function map(array, f) {
  217. var out = [];
  218. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  219. return out
  220. }
  221. function insertSorted(array, value, score) {
  222. var pos = 0, priority = score(value);
  223. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  224. array.splice(pos, 0, value);
  225. }
  226. function nothing() {}
  227. function createObj(base, props) {
  228. var inst;
  229. if (Object.create) {
  230. inst = Object.create(base);
  231. } else {
  232. nothing.prototype = base;
  233. inst = new nothing();
  234. }
  235. if (props) { copyObj(props, inst); }
  236. return inst
  237. }
  238. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  239. function isWordCharBasic(ch) {
  240. return /\w/.test(ch) || ch > "\x80" &&
  241. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  242. }
  243. function isWordChar(ch, helper) {
  244. if (!helper) { return isWordCharBasic(ch) }
  245. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  246. return helper.test(ch)
  247. }
  248. function isEmpty(obj) {
  249. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  250. return true
  251. }
  252. // Extending unicode characters. A series of a non-extending char +
  253. // any number of extending chars is treated as a single unit as far
  254. // as editing and measuring is concerned. This is not fully correct,
  255. // since some scripts/fonts/browsers also treat other configurations
  256. // of code points as a group.
  257. 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]/;
  258. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  259. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  260. function skipExtendingChars(str, pos, dir) {
  261. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  262. return pos
  263. }
  264. // Returns the value from the range [`from`; `to`] that satisfies
  265. // `pred` and is closest to `from`. Assumes that at least `to`
  266. // satisfies `pred`. Supports `from` being greater than `to`.
  267. function findFirst(pred, from, to) {
  268. // At any point we are certain `to` satisfies `pred`, don't know
  269. // whether `from` does.
  270. var dir = from > to ? -1 : 1;
  271. for (;;) {
  272. if (from == to) { return from }
  273. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  274. if (mid == from) { return pred(mid) ? from : to }
  275. if (pred(mid)) { to = mid; }
  276. else { from = mid + dir; }
  277. }
  278. }
  279. // BIDI HELPERS
  280. function iterateBidiSections(order, from, to, f) {
  281. if (!order) { return f(from, to, "ltr", 0) }
  282. var found = false;
  283. for (var i = 0; i < order.length; ++i) {
  284. var part = order[i];
  285. if (part.from < to && part.to > from || from == to && part.to == from) {
  286. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  287. found = true;
  288. }
  289. }
  290. if (!found) { f(from, to, "ltr"); }
  291. }
  292. var bidiOther = null;
  293. function getBidiPartAt(order, ch, sticky) {
  294. var found;
  295. bidiOther = null;
  296. for (var i = 0; i < order.length; ++i) {
  297. var cur = order[i];
  298. if (cur.from < ch && cur.to > ch) { return i }
  299. if (cur.to == ch) {
  300. if (cur.from != cur.to && sticky == "before") { found = i; }
  301. else { bidiOther = i; }
  302. }
  303. if (cur.from == ch) {
  304. if (cur.from != cur.to && sticky != "before") { found = i; }
  305. else { bidiOther = i; }
  306. }
  307. }
  308. return found != null ? found : bidiOther
  309. }
  310. // Bidirectional ordering algorithm
  311. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  312. // that this (partially) implements.
  313. // One-char codes used for character types:
  314. // L (L): Left-to-Right
  315. // R (R): Right-to-Left
  316. // r (AL): Right-to-Left Arabic
  317. // 1 (EN): European Number
  318. // + (ES): European Number Separator
  319. // % (ET): European Number Terminator
  320. // n (AN): Arabic Number
  321. // , (CS): Common Number Separator
  322. // m (NSM): Non-Spacing Mark
  323. // b (BN): Boundary Neutral
  324. // s (B): Paragraph Separator
  325. // t (S): Segment Separator
  326. // w (WS): Whitespace
  327. // N (ON): Other Neutrals
  328. // Returns null if characters are ordered as they appear
  329. // (left-to-right), or an array of sections ({from, to, level}
  330. // objects) in the order in which they occur visually.
  331. var bidiOrdering = (function() {
  332. // Character types for codepoints 0 to 0xff
  333. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  334. // Character types for codepoints 0x600 to 0x6f9
  335. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  336. function charType(code) {
  337. if (code <= 0xf7) { return lowTypes.charAt(code) }
  338. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  339. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  340. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  341. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  342. else if (code == 0x200c) { return "b" }
  343. else { return "L" }
  344. }
  345. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  346. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  347. function BidiSpan(level, from, to) {
  348. this.level = level;
  349. this.from = from; this.to = to;
  350. }
  351. return function(str, direction) {
  352. var outerType = direction == "ltr" ? "L" : "R";
  353. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  354. var len = str.length, types = [];
  355. for (var i = 0; i < len; ++i)
  356. { types.push(charType(str.charCodeAt(i))); }
  357. // W1. Examine each non-spacing mark (NSM) in the level run, and
  358. // change the type of the NSM to the type of the previous
  359. // character. If the NSM is at the start of the level run, it will
  360. // get the type of sor.
  361. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  362. var type = types[i$1];
  363. if (type == "m") { types[i$1] = prev; }
  364. else { prev = type; }
  365. }
  366. // W2. Search backwards from each instance of a European number
  367. // until the first strong type (R, L, AL, or sor) is found. If an
  368. // AL is found, change the type of the European number to Arabic
  369. // number.
  370. // W3. Change all ALs to R.
  371. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  372. var type$1 = types[i$2];
  373. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  374. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  375. }
  376. // W4. A single European separator between two European numbers
  377. // changes to a European number. A single common separator between
  378. // two numbers of the same type changes to that type.
  379. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  380. var type$2 = types[i$3];
  381. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  382. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  383. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  384. prev$1 = type$2;
  385. }
  386. // W5. A sequence of European terminators adjacent to European
  387. // numbers changes to all European numbers.
  388. // W6. Otherwise, separators and terminators change to Other
  389. // Neutral.
  390. for (var i$4 = 0; i$4 < len; ++i$4) {
  391. var type$3 = types[i$4];
  392. if (type$3 == ",") { types[i$4] = "N"; }
  393. else if (type$3 == "%") {
  394. var end = (void 0);
  395. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  396. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  397. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  398. i$4 = end - 1;
  399. }
  400. }
  401. // W7. Search backwards from each instance of a European number
  402. // until the first strong type (R, L, or sor) is found. If an L is
  403. // found, then change the type of the European number to L.
  404. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  405. var type$4 = types[i$5];
  406. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  407. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  408. }
  409. // N1. A sequence of neutrals takes the direction of the
  410. // surrounding strong text if the text on both sides has the same
  411. // direction. European and Arabic numbers act as if they were R in
  412. // terms of their influence on neutrals. Start-of-level-run (sor)
  413. // and end-of-level-run (eor) are used at level run boundaries.
  414. // N2. Any remaining neutrals take the embedding direction.
  415. for (var i$6 = 0; i$6 < len; ++i$6) {
  416. if (isNeutral.test(types[i$6])) {
  417. var end$1 = (void 0);
  418. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  419. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  420. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  421. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  422. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  423. i$6 = end$1 - 1;
  424. }
  425. }
  426. // Here we depart from the documented algorithm, in order to avoid
  427. // building up an actual levels array. Since there are only three
  428. // levels (0, 1, 2) in an implementation that doesn't take
  429. // explicit embedding into account, we can build up the order on
  430. // the fly, without following the level-based algorithm.
  431. var order = [], m;
  432. for (var i$7 = 0; i$7 < len;) {
  433. if (countsAsLeft.test(types[i$7])) {
  434. var start = i$7;
  435. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  436. order.push(new BidiSpan(0, start, i$7));
  437. } else {
  438. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  439. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  440. for (var j$2 = pos; j$2 < i$7;) {
  441. if (countsAsNum.test(types[j$2])) {
  442. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  443. var nstart = j$2;
  444. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  445. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  446. at += isRTL;
  447. pos = j$2;
  448. } else { ++j$2; }
  449. }
  450. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  451. }
  452. }
  453. if (direction == "ltr") {
  454. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  455. order[0].from = m[0].length;
  456. order.unshift(new BidiSpan(0, 0, m[0].length));
  457. }
  458. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  459. lst(order).to -= m[0].length;
  460. order.push(new BidiSpan(0, len - m[0].length, len));
  461. }
  462. }
  463. return direction == "rtl" ? order.reverse() : order
  464. }
  465. })();
  466. // Get the bidi ordering for the given line (and cache it). Returns
  467. // false for lines that are fully left-to-right, and an array of
  468. // BidiSpan objects otherwise.
  469. function getOrder(line, direction) {
  470. var order = line.order;
  471. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  472. return order
  473. }
  474. // EVENT HANDLING
  475. // Lightweight event framework. on/off also work on DOM nodes,
  476. // registering native DOM handlers.
  477. var noHandlers = [];
  478. var on = function(emitter, type, f) {
  479. if (emitter.addEventListener) {
  480. emitter.addEventListener(type, f, false);
  481. } else if (emitter.attachEvent) {
  482. emitter.attachEvent("on" + type, f);
  483. } else {
  484. var map = emitter._handlers || (emitter._handlers = {});
  485. map[type] = (map[type] || noHandlers).concat(f);
  486. }
  487. };
  488. function getHandlers(emitter, type) {
  489. return emitter._handlers && emitter._handlers[type] || noHandlers
  490. }
  491. function off(emitter, type, f) {
  492. if (emitter.removeEventListener) {
  493. emitter.removeEventListener(type, f, false);
  494. } else if (emitter.detachEvent) {
  495. emitter.detachEvent("on" + type, f);
  496. } else {
  497. var map = emitter._handlers, arr = map && map[type];
  498. if (arr) {
  499. var index = indexOf(arr, f);
  500. if (index > -1)
  501. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  502. }
  503. }
  504. }
  505. function signal(emitter, type /*, values...*/) {
  506. var handlers = getHandlers(emitter, type);
  507. if (!handlers.length) { return }
  508. var args = Array.prototype.slice.call(arguments, 2);
  509. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  510. }
  511. // The DOM events that CodeMirror handles can be overridden by
  512. // registering a (non-DOM) handler on the editor for the event name,
  513. // and preventDefault-ing the event in that handler.
  514. function signalDOMEvent(cm, e, override) {
  515. if (typeof e == "string")
  516. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  517. signal(cm, override || e.type, cm, e);
  518. return e_defaultPrevented(e) || e.codemirrorIgnore
  519. }
  520. function signalCursorActivity(cm) {
  521. var arr = cm._handlers && cm._handlers.cursorActivity;
  522. if (!arr) { return }
  523. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  524. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  525. { set.push(arr[i]); } }
  526. }
  527. function hasHandler(emitter, type) {
  528. return getHandlers(emitter, type).length > 0
  529. }
  530. // Add on and off methods to a constructor's prototype, to make
  531. // registering events on such objects more convenient.
  532. function eventMixin(ctor) {
  533. ctor.prototype.on = function(type, f) {on(this, type, f);};
  534. ctor.prototype.off = function(type, f) {off(this, type, f);};
  535. }
  536. // Due to the fact that we still support jurassic IE versions, some
  537. // compatibility wrappers are needed.
  538. function e_preventDefault(e) {
  539. if (e.preventDefault) { e.preventDefault(); }
  540. else { e.returnValue = false; }
  541. }
  542. function e_stopPropagation(e) {
  543. if (e.stopPropagation) { e.stopPropagation(); }
  544. else { e.cancelBubble = true; }
  545. }
  546. function e_defaultPrevented(e) {
  547. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  548. }
  549. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  550. function e_target(e) {return e.target || e.srcElement}
  551. function e_button(e) {
  552. var b = e.which;
  553. if (b == null) {
  554. if (e.button & 1) { b = 1; }
  555. else if (e.button & 2) { b = 3; }
  556. else if (e.button & 4) { b = 2; }
  557. }
  558. if (mac && e.ctrlKey && b == 1) { b = 3; }
  559. return b
  560. }
  561. // Detect drag-and-drop
  562. var dragAndDrop = function() {
  563. // There is *some* kind of drag-and-drop support in IE6-8, but I
  564. // couldn't get it to work yet.
  565. if (ie && ie_version < 9) { return false }
  566. var div = elt('div');
  567. return "draggable" in div || "dragDrop" in div
  568. }();
  569. var zwspSupported;
  570. function zeroWidthElement(measure) {
  571. if (zwspSupported == null) {
  572. var test = elt("span", "\u200b");
  573. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  574. if (measure.firstChild.offsetHeight != 0)
  575. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  576. }
  577. var node = zwspSupported ? elt("span", "\u200b") :
  578. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  579. node.setAttribute("cm-text", "");
  580. return node
  581. }
  582. // Feature-detect IE's crummy client rect reporting for bidi text
  583. var badBidiRects;
  584. function hasBadBidiRects(measure) {
  585. if (badBidiRects != null) { return badBidiRects }
  586. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  587. var r0 = range(txt, 0, 1).getBoundingClientRect();
  588. var r1 = range(txt, 1, 2).getBoundingClientRect();
  589. removeChildren(measure);
  590. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  591. return badBidiRects = (r1.right - r0.right < 3)
  592. }
  593. // See if "".split is the broken IE version, if so, provide an
  594. // alternative way to split lines.
  595. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  596. var pos = 0, result = [], l = string.length;
  597. while (pos <= l) {
  598. var nl = string.indexOf("\n", pos);
  599. if (nl == -1) { nl = string.length; }
  600. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  601. var rt = line.indexOf("\r");
  602. if (rt != -1) {
  603. result.push(line.slice(0, rt));
  604. pos += rt + 1;
  605. } else {
  606. result.push(line);
  607. pos = nl + 1;
  608. }
  609. }
  610. return result
  611. } : function (string) { return string.split(/\r\n?|\n/); };
  612. var hasSelection = window.getSelection ? function (te) {
  613. try { return te.selectionStart != te.selectionEnd }
  614. catch(e) { return false }
  615. } : function (te) {
  616. var range;
  617. try {range = te.ownerDocument.selection.createRange();}
  618. catch(e) {}
  619. if (!range || range.parentElement() != te) { return false }
  620. return range.compareEndPoints("StartToEnd", range) != 0
  621. };
  622. var hasCopyEvent = (function () {
  623. var e = elt("div");
  624. if ("oncopy" in e) { return true }
  625. e.setAttribute("oncopy", "return;");
  626. return typeof e.oncopy == "function"
  627. })();
  628. var badZoomedRects = null;
  629. function hasBadZoomedRects(measure) {
  630. if (badZoomedRects != null) { return badZoomedRects }
  631. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  632. var normal = node.getBoundingClientRect();
  633. var fromRange = range(node, 0, 1).getBoundingClientRect();
  634. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  635. }
  636. // Known modes, by name and by MIME
  637. var modes = {}, mimeModes = {};
  638. // Extra arguments are stored as the mode's dependencies, which is
  639. // used by (legacy) mechanisms like loadmode.js to automatically
  640. // load a mode. (Preferred mechanism is the require/define calls.)
  641. function defineMode(name, mode) {
  642. if (arguments.length > 2)
  643. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  644. modes[name] = mode;
  645. }
  646. function defineMIME(mime, spec) {
  647. mimeModes[mime] = spec;
  648. }
  649. // Given a MIME type, a {name, ...options} config object, or a name
  650. // string, return a mode config object.
  651. function resolveMode(spec) {
  652. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  653. spec = mimeModes[spec];
  654. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  655. var found = mimeModes[spec.name];
  656. if (typeof found == "string") { found = {name: found}; }
  657. spec = createObj(found, spec);
  658. spec.name = found.name;
  659. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  660. return resolveMode("application/xml")
  661. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  662. return resolveMode("application/json")
  663. }
  664. if (typeof spec == "string") { return {name: spec} }
  665. else { return spec || {name: "null"} }
  666. }
  667. // Given a mode spec (anything that resolveMode accepts), find and
  668. // initialize an actual mode object.
  669. function getMode(options, spec) {
  670. spec = resolveMode(spec);
  671. var mfactory = modes[spec.name];
  672. if (!mfactory) { return getMode(options, "text/plain") }
  673. var modeObj = mfactory(options, spec);
  674. if (modeExtensions.hasOwnProperty(spec.name)) {
  675. var exts = modeExtensions[spec.name];
  676. for (var prop in exts) {
  677. if (!exts.hasOwnProperty(prop)) { continue }
  678. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  679. modeObj[prop] = exts[prop];
  680. }
  681. }
  682. modeObj.name = spec.name;
  683. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  684. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  685. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  686. return modeObj
  687. }
  688. // This can be used to attach properties to mode objects from
  689. // outside the actual mode definition.
  690. var modeExtensions = {};
  691. function extendMode(mode, properties) {
  692. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  693. copyObj(properties, exts);
  694. }
  695. function copyState(mode, state) {
  696. if (state === true) { return state }
  697. if (mode.copyState) { return mode.copyState(state) }
  698. var nstate = {};
  699. for (var n in state) {
  700. var val = state[n];
  701. if (val instanceof Array) { val = val.concat([]); }
  702. nstate[n] = val;
  703. }
  704. return nstate
  705. }
  706. // Given a mode and a state (for that mode), find the inner mode and
  707. // state at the position that the state refers to.
  708. function innerMode(mode, state) {
  709. var info;
  710. while (mode.innerMode) {
  711. info = mode.innerMode(state);
  712. if (!info || info.mode == mode) { break }
  713. state = info.state;
  714. mode = info.mode;
  715. }
  716. return info || {mode: mode, state: state}
  717. }
  718. function startState(mode, a1, a2) {
  719. return mode.startState ? mode.startState(a1, a2) : true
  720. }
  721. // STRING STREAM
  722. // Fed to the mode parsers, provides helper functions to make
  723. // parsers more succinct.
  724. var StringStream = function(string, tabSize, lineOracle) {
  725. this.pos = this.start = 0;
  726. this.string = string;
  727. this.tabSize = tabSize || 8;
  728. this.lastColumnPos = this.lastColumnValue = 0;
  729. this.lineStart = 0;
  730. this.lineOracle = lineOracle;
  731. };
  732. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  733. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  734. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  735. StringStream.prototype.next = function () {
  736. if (this.pos < this.string.length)
  737. { return this.string.charAt(this.pos++) }
  738. };
  739. StringStream.prototype.eat = function (match) {
  740. var ch = this.string.charAt(this.pos);
  741. var ok;
  742. if (typeof match == "string") { ok = ch == match; }
  743. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  744. if (ok) {++this.pos; return ch}
  745. };
  746. StringStream.prototype.eatWhile = function (match) {
  747. var start = this.pos;
  748. while (this.eat(match)){}
  749. return this.pos > start
  750. };
  751. StringStream.prototype.eatSpace = function () {
  752. var start = this.pos;
  753. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  754. return this.pos > start
  755. };
  756. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  757. StringStream.prototype.skipTo = function (ch) {
  758. var found = this.string.indexOf(ch, this.pos);
  759. if (found > -1) {this.pos = found; return true}
  760. };
  761. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  762. StringStream.prototype.column = function () {
  763. if (this.lastColumnPos < this.start) {
  764. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  765. this.lastColumnPos = this.start;
  766. }
  767. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  768. };
  769. StringStream.prototype.indentation = function () {
  770. return countColumn(this.string, null, this.tabSize) -
  771. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  772. };
  773. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  774. if (typeof pattern == "string") {
  775. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  776. var substr = this.string.substr(this.pos, pattern.length);
  777. if (cased(substr) == cased(pattern)) {
  778. if (consume !== false) { this.pos += pattern.length; }
  779. return true
  780. }
  781. } else {
  782. var match = this.string.slice(this.pos).match(pattern);
  783. if (match && match.index > 0) { return null }
  784. if (match && consume !== false) { this.pos += match[0].length; }
  785. return match
  786. }
  787. };
  788. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  789. StringStream.prototype.hideFirstChars = function (n, inner) {
  790. this.lineStart += n;
  791. try { return inner() }
  792. finally { this.lineStart -= n; }
  793. };
  794. StringStream.prototype.lookAhead = function (n) {
  795. var oracle = this.lineOracle;
  796. return oracle && oracle.lookAhead(n)
  797. };
  798. StringStream.prototype.baseToken = function () {
  799. var oracle = this.lineOracle;
  800. return oracle && oracle.baseToken(this.pos)
  801. };
  802. // Find the line object corresponding to the given line number.
  803. function getLine(doc, n) {
  804. n -= doc.first;
  805. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  806. var chunk = doc;
  807. while (!chunk.lines) {
  808. for (var i = 0;; ++i) {
  809. var child = chunk.children[i], sz = child.chunkSize();
  810. if (n < sz) { chunk = child; break }
  811. n -= sz;
  812. }
  813. }
  814. return chunk.lines[n]
  815. }
  816. // Get the part of a document between two positions, as an array of
  817. // strings.
  818. function getBetween(doc, start, end) {
  819. var out = [], n = start.line;
  820. doc.iter(start.line, end.line + 1, function (line) {
  821. var text = line.text;
  822. if (n == end.line) { text = text.slice(0, end.ch); }
  823. if (n == start.line) { text = text.slice(start.ch); }
  824. out.push(text);
  825. ++n;
  826. });
  827. return out
  828. }
  829. // Get the lines between from and to, as array of strings.
  830. function getLines(doc, from, to) {
  831. var out = [];
  832. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  833. return out
  834. }
  835. // Update the height of a line, propagating the height change
  836. // upwards to parent nodes.
  837. function updateLineHeight(line, height) {
  838. var diff = height - line.height;
  839. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  840. }
  841. // Given a line object, find its line number by walking up through
  842. // its parent links.
  843. function lineNo(line) {
  844. if (line.parent == null) { return null }
  845. var cur = line.parent, no = indexOf(cur.lines, line);
  846. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  847. for (var i = 0;; ++i) {
  848. if (chunk.children[i] == cur) { break }
  849. no += chunk.children[i].chunkSize();
  850. }
  851. }
  852. return no + cur.first
  853. }
  854. // Find the line at the given vertical position, using the height
  855. // information in the document tree.
  856. function lineAtHeight(chunk, h) {
  857. var n = chunk.first;
  858. outer: do {
  859. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  860. var child = chunk.children[i$1], ch = child.height;
  861. if (h < ch) { chunk = child; continue outer }
  862. h -= ch;
  863. n += child.chunkSize();
  864. }
  865. return n
  866. } while (!chunk.lines)
  867. var i = 0;
  868. for (; i < chunk.lines.length; ++i) {
  869. var line = chunk.lines[i], lh = line.height;
  870. if (h < lh) { break }
  871. h -= lh;
  872. }
  873. return n + i
  874. }
  875. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  876. function lineNumberFor(options, i) {
  877. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  878. }
  879. // A Pos instance represents a position within the text.
  880. function Pos(line, ch, sticky) {
  881. if ( sticky === void 0 ) sticky = null;
  882. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  883. this.line = line;
  884. this.ch = ch;
  885. this.sticky = sticky;
  886. }
  887. // Compare two positions, return 0 if they are the same, a negative
  888. // number when a is less, and a positive number otherwise.
  889. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  890. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  891. function copyPos(x) {return Pos(x.line, x.ch)}
  892. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  893. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  894. // Most of the external API clips given positions to make sure they
  895. // actually exist within the document.
  896. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  897. function clipPos(doc, pos) {
  898. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  899. var last = doc.first + doc.size - 1;
  900. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  901. return clipToLen(pos, getLine(doc, pos.line).text.length)
  902. }
  903. function clipToLen(pos, linelen) {
  904. var ch = pos.ch;
  905. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  906. else if (ch < 0) { return Pos(pos.line, 0) }
  907. else { return pos }
  908. }
  909. function clipPosArray(doc, array) {
  910. var out = [];
  911. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  912. return out
  913. }
  914. var SavedContext = function(state, lookAhead) {
  915. this.state = state;
  916. this.lookAhead = lookAhead;
  917. };
  918. var Context = function(doc, state, line, lookAhead) {
  919. this.state = state;
  920. this.doc = doc;
  921. this.line = line;
  922. this.maxLookAhead = lookAhead || 0;
  923. this.baseTokens = null;
  924. this.baseTokenPos = 1;
  925. };
  926. Context.prototype.lookAhead = function (n) {
  927. var line = this.doc.getLine(this.line + n);
  928. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  929. return line
  930. };
  931. Context.prototype.baseToken = function (n) {
  932. if (!this.baseTokens) { return null }
  933. while (this.baseTokens[this.baseTokenPos] <= n)
  934. { this.baseTokenPos += 2; }
  935. var type = this.baseTokens[this.baseTokenPos + 1];
  936. return {type: type && type.replace(/( |^)overlay .*/, ""),
  937. size: this.baseTokens[this.baseTokenPos] - n}
  938. };
  939. Context.prototype.nextLine = function () {
  940. this.line++;
  941. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  942. };
  943. Context.fromSaved = function (doc, saved, line) {
  944. if (saved instanceof SavedContext)
  945. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  946. else
  947. { return new Context(doc, copyState(doc.mode, saved), line) }
  948. };
  949. Context.prototype.save = function (copy) {
  950. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  951. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  952. };
  953. // Compute a style array (an array starting with a mode generation
  954. // -- for invalidation -- followed by pairs of end positions and
  955. // style strings), which is used to highlight the tokens on the
  956. // line.
  957. function highlightLine(cm, line, context, forceToEnd) {
  958. // A styles array always starts with a number identifying the
  959. // mode/overlays that it is based on (for easy invalidation).
  960. var st = [cm.state.modeGen], lineClasses = {};
  961. // Compute the base array of styles
  962. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  963. lineClasses, forceToEnd);
  964. var state = context.state;
  965. // Run overlays, adjust style array.
  966. var loop = function ( o ) {
  967. context.baseTokens = st;
  968. var overlay = cm.state.overlays[o], i = 1, at = 0;
  969. context.state = true;
  970. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  971. var start = i;
  972. // Ensure there's a token end at the current position, and that i points at it
  973. while (at < end) {
  974. var i_end = st[i];
  975. if (i_end > end)
  976. { st.splice(i, 1, end, st[i+1], i_end); }
  977. i += 2;
  978. at = Math.min(end, i_end);
  979. }
  980. if (!style) { return }
  981. if (overlay.opaque) {
  982. st.splice(start, i - start, end, "overlay " + style);
  983. i = start + 2;
  984. } else {
  985. for (; start < i; start += 2) {
  986. var cur = st[start+1];
  987. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  988. }
  989. }
  990. }, lineClasses);
  991. context.state = state;
  992. context.baseTokens = null;
  993. context.baseTokenPos = 1;
  994. };
  995. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  996. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  997. }
  998. function getLineStyles(cm, line, updateFrontier) {
  999. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1000. var context = getContextBefore(cm, lineNo(line));
  1001. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1002. var result = highlightLine(cm, line, context);
  1003. if (resetState) { context.state = resetState; }
  1004. line.stateAfter = context.save(!resetState);
  1005. line.styles = result.styles;
  1006. if (result.classes) { line.styleClasses = result.classes; }
  1007. else if (line.styleClasses) { line.styleClasses = null; }
  1008. if (updateFrontier === cm.doc.highlightFrontier)
  1009. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1010. }
  1011. return line.styles
  1012. }
  1013. function getContextBefore(cm, n, precise) {
  1014. var doc = cm.doc, display = cm.display;
  1015. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1016. var start = findStartLine(cm, n, precise);
  1017. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1018. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1019. doc.iter(start, n, function (line) {
  1020. processLine(cm, line.text, context);
  1021. var pos = context.line;
  1022. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1023. context.nextLine();
  1024. });
  1025. if (precise) { doc.modeFrontier = context.line; }
  1026. return context
  1027. }
  1028. // Lightweight form of highlight -- proceed over this line and
  1029. // update state, but don't save a style array. Used for lines that
  1030. // aren't currently visible.
  1031. function processLine(cm, text, context, startAt) {
  1032. var mode = cm.doc.mode;
  1033. var stream = new StringStream(text, cm.options.tabSize, context);
  1034. stream.start = stream.pos = startAt || 0;
  1035. if (text == "") { callBlankLine(mode, context.state); }
  1036. while (!stream.eol()) {
  1037. readToken(mode, stream, context.state);
  1038. stream.start = stream.pos;
  1039. }
  1040. }
  1041. function callBlankLine(mode, state) {
  1042. if (mode.blankLine) { return mode.blankLine(state) }
  1043. if (!mode.innerMode) { return }
  1044. var inner = innerMode(mode, state);
  1045. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1046. }
  1047. function readToken(mode, stream, state, inner) {
  1048. for (var i = 0; i < 10; i++) {
  1049. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1050. var style = mode.token(stream, state);
  1051. if (stream.pos > stream.start) { return style }
  1052. }
  1053. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1054. }
  1055. var Token = function(stream, type, state) {
  1056. this.start = stream.start; this.end = stream.pos;
  1057. this.string = stream.current();
  1058. this.type = type || null;
  1059. this.state = state;
  1060. };
  1061. // Utility for getTokenAt and getLineTokens
  1062. function takeToken(cm, pos, precise, asArray) {
  1063. var doc = cm.doc, mode = doc.mode, style;
  1064. pos = clipPos(doc, pos);
  1065. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1066. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1067. if (asArray) { tokens = []; }
  1068. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1069. stream.start = stream.pos;
  1070. style = readToken(mode, stream, context.state);
  1071. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1072. }
  1073. return asArray ? tokens : new Token(stream, style, context.state)
  1074. }
  1075. function extractLineClasses(type, output) {
  1076. if (type) { for (;;) {
  1077. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1078. if (!lineClass) { break }
  1079. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1080. var prop = lineClass[1] ? "bgClass" : "textClass";
  1081. if (output[prop] == null)
  1082. { output[prop] = lineClass[2]; }
  1083. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1084. { output[prop] += " " + lineClass[2]; }
  1085. } }
  1086. return type
  1087. }
  1088. // Run the given mode's parser over a line, calling f for each token.
  1089. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1090. var flattenSpans = mode.flattenSpans;
  1091. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1092. var curStart = 0, curStyle = null;
  1093. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1094. var inner = cm.options.addModeClass && [null];
  1095. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1096. while (!stream.eol()) {
  1097. if (stream.pos > cm.options.maxHighlightLength) {
  1098. flattenSpans = false;
  1099. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1100. stream.pos = text.length;
  1101. style = null;
  1102. } else {
  1103. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1104. }
  1105. if (inner) {
  1106. var mName = inner[0].name;
  1107. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1108. }
  1109. if (!flattenSpans || curStyle != style) {
  1110. while (curStart < stream.start) {
  1111. curStart = Math.min(stream.start, curStart + 5000);
  1112. f(curStart, curStyle);
  1113. }
  1114. curStyle = style;
  1115. }
  1116. stream.start = stream.pos;
  1117. }
  1118. while (curStart < stream.pos) {
  1119. // Webkit seems to refuse to render text nodes longer than 57444
  1120. // characters, and returns inaccurate measurements in nodes
  1121. // starting around 5000 chars.
  1122. var pos = Math.min(stream.pos, curStart + 5000);
  1123. f(pos, curStyle);
  1124. curStart = pos;
  1125. }
  1126. }
  1127. // Finds the line to start with when starting a parse. Tries to
  1128. // find a line with a stateAfter, so that it can start with a
  1129. // valid state. If that fails, it returns the line with the
  1130. // smallest indentation, which tends to need the least context to
  1131. // parse correctly.
  1132. function findStartLine(cm, n, precise) {
  1133. var minindent, minline, doc = cm.doc;
  1134. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1135. for (var search = n; search > lim; --search) {
  1136. if (search <= doc.first) { return doc.first }
  1137. var line = getLine(doc, search - 1), after = line.stateAfter;
  1138. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1139. { return search }
  1140. var indented = countColumn(line.text, null, cm.options.tabSize);
  1141. if (minline == null || minindent > indented) {
  1142. minline = search - 1;
  1143. minindent = indented;
  1144. }
  1145. }
  1146. return minline
  1147. }
  1148. function retreatFrontier(doc, n) {
  1149. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1150. if (doc.highlightFrontier < n - 10) { return }
  1151. var start = doc.first;
  1152. for (var line = n - 1; line > start; line--) {
  1153. var saved = getLine(doc, line).stateAfter;
  1154. // change is on 3
  1155. // state on line 1 looked ahead 2 -- so saw 3
  1156. // test 1 + 2 < 3 should cover this
  1157. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1158. start = line + 1;
  1159. break
  1160. }
  1161. }
  1162. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1163. }
  1164. // Optimize some code when these features are not used.
  1165. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1166. function seeReadOnlySpans() {
  1167. sawReadOnlySpans = true;
  1168. }
  1169. function seeCollapsedSpans() {
  1170. sawCollapsedSpans = true;
  1171. }
  1172. // TEXTMARKER SPANS
  1173. function MarkedSpan(marker, from, to) {
  1174. this.marker = marker;
  1175. this.from = from; this.to = to;
  1176. }
  1177. // Search an array of spans for a span matching the given marker.
  1178. function getMarkedSpanFor(spans, marker) {
  1179. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1180. var span = spans[i];
  1181. if (span.marker == marker) { return span }
  1182. } }
  1183. }
  1184. // Remove a span from an array, returning undefined if no spans are
  1185. // left (we don't store arrays for lines without spans).
  1186. function removeMarkedSpan(spans, span) {
  1187. var r;
  1188. for (var i = 0; i < spans.length; ++i)
  1189. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1190. return r
  1191. }
  1192. // Add a span to a line.
  1193. function addMarkedSpan(line, span, op) {
  1194. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1195. if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
  1196. line.markedSpans.push(span);
  1197. } else {
  1198. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1199. if (inThisOp) { inThisOp.add(line.markedSpans); }
  1200. }
  1201. span.marker.attachLine(line);
  1202. }
  1203. // Used for the algorithm that adjusts markers for a change in the
  1204. // document. These functions cut an array of spans at a given
  1205. // character position, returning an array of remaining chunks (or
  1206. // undefined if nothing remains).
  1207. function markedSpansBefore(old, startCh, isInsert) {
  1208. var nw;
  1209. if (old) { for (var i = 0; i < old.length; ++i) {
  1210. var span = old[i], marker = span.marker;
  1211. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1212. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1213. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1214. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1215. }
  1216. } }
  1217. return nw
  1218. }
  1219. function markedSpansAfter(old, endCh, isInsert) {
  1220. var nw;
  1221. if (old) { for (var i = 0; i < old.length; ++i) {
  1222. var span = old[i], marker = span.marker;
  1223. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1224. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1225. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1226. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1227. span.to == null ? null : span.to - endCh));
  1228. }
  1229. } }
  1230. return nw
  1231. }
  1232. // Given a change object, compute the new set of marker spans that
  1233. // cover the line in which the change took place. Removes spans
  1234. // entirely within the change, reconnects spans belonging to the
  1235. // same marker that appear on both sides of the change, and cuts off
  1236. // spans partially within the change. Returns an array of span
  1237. // arrays with one element for each line in (after) the change.
  1238. function stretchSpansOverChange(doc, change) {
  1239. if (change.full) { return null }
  1240. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1241. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1242. if (!oldFirst && !oldLast) { return null }
  1243. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1244. // Get the spans that 'stick out' on both sides
  1245. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1246. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1247. // Next, merge those two ends
  1248. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1249. if (first) {
  1250. // Fix up .to properties of first
  1251. for (var i = 0; i < first.length; ++i) {
  1252. var span = first[i];
  1253. if (span.to == null) {
  1254. var found = getMarkedSpanFor(last, span.marker);
  1255. if (!found) { span.to = startCh; }
  1256. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1257. }
  1258. }
  1259. }
  1260. if (last) {
  1261. // Fix up .from in last (or move them into first in case of sameLine)
  1262. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1263. var span$1 = last[i$1];
  1264. if (span$1.to != null) { span$1.to += offset; }
  1265. if (span$1.from == null) {
  1266. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1267. if (!found$1) {
  1268. span$1.from = offset;
  1269. if (sameLine) { (first || (first = [])).push(span$1); }
  1270. }
  1271. } else {
  1272. span$1.from += offset;
  1273. if (sameLine) { (first || (first = [])).push(span$1); }
  1274. }
  1275. }
  1276. }
  1277. // Make sure we didn't create any zero-length spans
  1278. if (first) { first = clearEmptySpans(first); }
  1279. if (last && last != first) { last = clearEmptySpans(last); }
  1280. var newMarkers = [first];
  1281. if (!sameLine) {
  1282. // Fill gap with whole-line-spans
  1283. var gap = change.text.length - 2, gapMarkers;
  1284. if (gap > 0 && first)
  1285. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1286. { if (first[i$2].to == null)
  1287. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1288. for (var i$3 = 0; i$3 < gap; ++i$3)
  1289. { newMarkers.push(gapMarkers); }
  1290. newMarkers.push(last);
  1291. }
  1292. return newMarkers
  1293. }
  1294. // Remove spans that are empty and don't have a clearWhenEmpty
  1295. // option of false.
  1296. function clearEmptySpans(spans) {
  1297. for (var i = 0; i < spans.length; ++i) {
  1298. var span = spans[i];
  1299. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1300. { spans.splice(i--, 1); }
  1301. }
  1302. if (!spans.length) { return null }
  1303. return spans
  1304. }
  1305. // Used to 'clip' out readOnly ranges when making a change.
  1306. function removeReadOnlyRanges(doc, from, to) {
  1307. var markers = null;
  1308. doc.iter(from.line, to.line + 1, function (line) {
  1309. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1310. var mark = line.markedSpans[i].marker;
  1311. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1312. { (markers || (markers = [])).push(mark); }
  1313. } }
  1314. });
  1315. if (!markers) { return null }
  1316. var parts = [{from: from, to: to}];
  1317. for (var i = 0; i < markers.length; ++i) {
  1318. var mk = markers[i], m = mk.find(0);
  1319. for (var j = 0; j < parts.length; ++j) {
  1320. var p = parts[j];
  1321. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1322. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1323. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1324. { newParts.push({from: p.from, to: m.from}); }
  1325. if (dto > 0 || !mk.inclusiveRight && !dto)
  1326. { newParts.push({from: m.to, to: p.to}); }
  1327. parts.splice.apply(parts, newParts);
  1328. j += newParts.length - 3;
  1329. }
  1330. }
  1331. return parts
  1332. }
  1333. // Connect or disconnect spans from a line.
  1334. function detachMarkedSpans(line) {
  1335. var spans = line.markedSpans;
  1336. if (!spans) { return }
  1337. for (var i = 0; i < spans.length; ++i)
  1338. { spans[i].marker.detachLine(line); }
  1339. line.markedSpans = null;
  1340. }
  1341. function attachMarkedSpans(line, spans) {
  1342. if (!spans) { return }
  1343. for (var i = 0; i < spans.length; ++i)
  1344. { spans[i].marker.attachLine(line); }
  1345. line.markedSpans = spans;
  1346. }
  1347. // Helpers used when computing which overlapping collapsed span
  1348. // counts as the larger one.
  1349. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1350. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1351. // Returns a number indicating which of two overlapping collapsed
  1352. // spans is larger (and thus includes the other). Falls back to
  1353. // comparing ids when the spans cover exactly the same range.
  1354. function compareCollapsedMarkers(a, b) {
  1355. var lenDiff = a.lines.length - b.lines.length;
  1356. if (lenDiff != 0) { return lenDiff }
  1357. var aPos = a.find(), bPos = b.find();
  1358. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1359. if (fromCmp) { return -fromCmp }
  1360. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1361. if (toCmp) { return toCmp }
  1362. return b.id - a.id
  1363. }
  1364. // Find out whether a line ends or starts in a collapsed span. If
  1365. // so, return the marker for that span.
  1366. function collapsedSpanAtSide(line, start) {
  1367. var sps = sawCollapsedSpans && line.markedSpans, found;
  1368. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1369. sp = sps[i];
  1370. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1371. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1372. { found = sp.marker; }
  1373. } }
  1374. return found
  1375. }
  1376. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1377. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1378. function collapsedSpanAround(line, ch) {
  1379. var sps = sawCollapsedSpans && line.markedSpans, found;
  1380. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1381. var sp = sps[i];
  1382. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1383. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1384. } }
  1385. return found
  1386. }
  1387. // Test whether there exists a collapsed span that partially
  1388. // overlaps (covers the start or end, but not both) of a new span.
  1389. // Such overlap is not allowed.
  1390. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1391. var line = getLine(doc, lineNo);
  1392. var sps = sawCollapsedSpans && line.markedSpans;
  1393. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1394. var sp = sps[i];
  1395. if (!sp.marker.collapsed) { continue }
  1396. var found = sp.marker.find(0);
  1397. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1398. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1399. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1400. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1401. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1402. { return true }
  1403. } }
  1404. }
  1405. // A visual line is a line as drawn on the screen. Folding, for
  1406. // example, can cause multiple logical lines to appear on the same
  1407. // visual line. This finds the start of the visual line that the
  1408. // given line is part of (usually that is the line itself).
  1409. function visualLine(line) {
  1410. var merged;
  1411. while (merged = collapsedSpanAtStart(line))
  1412. { line = merged.find(-1, true).line; }
  1413. return line
  1414. }
  1415. function visualLineEnd(line) {
  1416. var merged;
  1417. while (merged = collapsedSpanAtEnd(line))
  1418. { line = merged.find(1, true).line; }
  1419. return line
  1420. }
  1421. // Returns an array of logical lines that continue the visual line
  1422. // started by the argument, or undefined if there are no such lines.
  1423. function visualLineContinued(line) {
  1424. var merged, lines;
  1425. while (merged = collapsedSpanAtEnd(line)) {
  1426. line = merged.find(1, true).line
  1427. ;(lines || (lines = [])).push(line);
  1428. }
  1429. return lines
  1430. }
  1431. // Get the line number of the start of the visual line that the
  1432. // given line number is part of.
  1433. function visualLineNo(doc, lineN) {
  1434. var line = getLine(doc, lineN), vis = visualLine(line);
  1435. if (line == vis) { return lineN }
  1436. return lineNo(vis)
  1437. }
  1438. // Get the line number of the start of the next visual line after
  1439. // the given line.
  1440. function visualLineEndNo(doc, lineN) {
  1441. if (lineN > doc.lastLine()) { return lineN }
  1442. var line = getLine(doc, lineN), merged;
  1443. if (!lineIsHidden(doc, line)) { return lineN }
  1444. while (merged = collapsedSpanAtEnd(line))
  1445. { line = merged.find(1, true).line; }
  1446. return lineNo(line) + 1
  1447. }
  1448. // Compute whether a line is hidden. Lines count as hidden when they
  1449. // are part of a visual line that starts with another line, or when
  1450. // they are entirely covered by collapsed, non-widget span.
  1451. function lineIsHidden(doc, line) {
  1452. var sps = sawCollapsedSpans && line.markedSpans;
  1453. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1454. sp = sps[i];
  1455. if (!sp.marker.collapsed) { continue }
  1456. if (sp.from == null) { return true }
  1457. if (sp.marker.widgetNode) { continue }
  1458. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1459. { return true }
  1460. } }
  1461. }
  1462. function lineIsHiddenInner(doc, line, span) {
  1463. if (span.to == null) {
  1464. var end = span.marker.find(1, true);
  1465. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1466. }
  1467. if (span.marker.inclusiveRight && span.to == line.text.length)
  1468. { return true }
  1469. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1470. sp = line.markedSpans[i];
  1471. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1472. (sp.to == null || sp.to != span.from) &&
  1473. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1474. lineIsHiddenInner(doc, line, sp)) { return true }
  1475. }
  1476. }
  1477. // Find the height above the given line.
  1478. function heightAtLine(lineObj) {
  1479. lineObj = visualLine(lineObj);
  1480. var h = 0, chunk = lineObj.parent;
  1481. for (var i = 0; i < chunk.lines.length; ++i) {
  1482. var line = chunk.lines[i];
  1483. if (line == lineObj) { break }
  1484. else { h += line.height; }
  1485. }
  1486. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1487. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1488. var cur = p.children[i$1];
  1489. if (cur == chunk) { break }
  1490. else { h += cur.height; }
  1491. }
  1492. }
  1493. return h
  1494. }
  1495. // Compute the character length of a line, taking into account
  1496. // collapsed ranges (see markText) that might hide parts, and join
  1497. // other lines onto it.
  1498. function lineLength(line) {
  1499. if (line.height == 0) { return 0 }
  1500. var len = line.text.length, merged, cur = line;
  1501. while (merged = collapsedSpanAtStart(cur)) {
  1502. var found = merged.find(0, true);
  1503. cur = found.from.line;
  1504. len += found.from.ch - found.to.ch;
  1505. }
  1506. cur = line;
  1507. while (merged = collapsedSpanAtEnd(cur)) {
  1508. var found$1 = merged.find(0, true);
  1509. len -= cur.text.length - found$1.from.ch;
  1510. cur = found$1.to.line;
  1511. len += cur.text.length - found$1.to.ch;
  1512. }
  1513. return len
  1514. }
  1515. // Find the longest line in the document.
  1516. function findMaxLine(cm) {
  1517. var d = cm.display, doc = cm.doc;
  1518. d.maxLine = getLine(doc, doc.first);
  1519. d.maxLineLength = lineLength(d.maxLine);
  1520. d.maxLineChanged = true;
  1521. doc.iter(function (line) {
  1522. var len = lineLength(line);
  1523. if (len > d.maxLineLength) {
  1524. d.maxLineLength = len;
  1525. d.maxLine = line;
  1526. }
  1527. });
  1528. }
  1529. // LINE DATA STRUCTURE
  1530. // Line objects. These hold state related to a line, including
  1531. // highlighting info (the styles array).
  1532. var Line = function(text, markedSpans, estimateHeight) {
  1533. this.text = text;
  1534. attachMarkedSpans(this, markedSpans);
  1535. this.height = estimateHeight ? estimateHeight(this) : 1;
  1536. };
  1537. Line.prototype.lineNo = function () { return lineNo(this) };
  1538. eventMixin(Line);
  1539. // Change the content (text, markers) of a line. Automatically
  1540. // invalidates cached information and tries to re-estimate the
  1541. // line's height.
  1542. function updateLine(line, text, markedSpans, estimateHeight) {
  1543. line.text = text;
  1544. if (line.stateAfter) { line.stateAfter = null; }
  1545. if (line.styles) { line.styles = null; }
  1546. if (line.order != null) { line.order = null; }
  1547. detachMarkedSpans(line);
  1548. attachMarkedSpans(line, markedSpans);
  1549. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1550. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1551. }
  1552. // Detach a line from the document tree and its markers.
  1553. function cleanUpLine(line) {
  1554. line.parent = null;
  1555. detachMarkedSpans(line);
  1556. }
  1557. // Convert a style as returned by a mode (either null, or a string
  1558. // containing one or more styles) to a CSS style. This is cached,
  1559. // and also looks for line-wide styles.
  1560. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1561. function interpretTokenStyle(style, options) {
  1562. if (!style || /^\s*$/.test(style)) { return null }
  1563. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1564. return cache[style] ||
  1565. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1566. }
  1567. // Render the DOM representation of the text of a line. Also builds
  1568. // up a 'line map', which points at the DOM nodes that represent
  1569. // specific stretches of text, and is used by the measuring code.
  1570. // The returned object contains the DOM node, this map, and
  1571. // information about line-wide styles that were set by the mode.
  1572. function buildLineContent(cm, lineView) {
  1573. // The padding-right forces the element to have a 'border', which
  1574. // is needed on Webkit to be able to get line-level bounding
  1575. // rectangles for it (in measureChar).
  1576. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1577. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1578. col: 0, pos: 0, cm: cm,
  1579. trailingSpace: false,
  1580. splitSpaces: cm.getOption("lineWrapping")};
  1581. lineView.measure = {};
  1582. // Iterate over the logical lines that make up this visual line.
  1583. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1584. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1585. builder.pos = 0;
  1586. builder.addToken = buildToken;
  1587. // Optionally wire in some hacks into the token-rendering
  1588. // algorithm, to deal with browser quirks.
  1589. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1590. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1591. builder.map = [];
  1592. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1593. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1594. if (line.styleClasses) {
  1595. if (line.styleClasses.bgClass)
  1596. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1597. if (line.styleClasses.textClass)
  1598. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1599. }
  1600. // Ensure at least a single node is present, for measuring.
  1601. if (builder.map.length == 0)
  1602. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1603. // Store the map and a cache object for the current logical line
  1604. if (i == 0) {
  1605. lineView.measure.map = builder.map;
  1606. lineView.measure.cache = {};
  1607. } else {
  1608. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1609. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1610. }
  1611. }
  1612. // See issue #2901
  1613. if (webkit) {
  1614. var last = builder.content.lastChild;
  1615. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1616. { builder.content.className = "cm-tab-wrap-hack"; }
  1617. }
  1618. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1619. if (builder.pre.className)
  1620. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1621. return builder
  1622. }
  1623. function defaultSpecialCharPlaceholder(ch) {
  1624. var token = elt("span", "\u2022", "cm-invalidchar");
  1625. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1626. token.setAttribute("aria-label", token.title);
  1627. return token
  1628. }
  1629. // Build up the DOM representation for a single token, and add it to
  1630. // the line map. Takes care to render special characters separately.
  1631. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1632. if (!text) { return }
  1633. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1634. var special = builder.cm.state.specialChars, mustWrap = false;
  1635. var content;
  1636. if (!special.test(text)) {
  1637. builder.col += text.length;
  1638. content = document.createTextNode(displayText);
  1639. builder.map.push(builder.pos, builder.pos + text.length, content);
  1640. if (ie && ie_version < 9) { mustWrap = true; }
  1641. builder.pos += text.length;
  1642. } else {
  1643. content = document.createDocumentFragment();
  1644. var pos = 0;
  1645. while (true) {
  1646. special.lastIndex = pos;
  1647. var m = special.exec(text);
  1648. var skipped = m ? m.index - pos : text.length - pos;
  1649. if (skipped) {
  1650. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1651. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1652. else { content.appendChild(txt); }
  1653. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1654. builder.col += skipped;
  1655. builder.pos += skipped;
  1656. }
  1657. if (!m) { break }
  1658. pos += skipped + 1;
  1659. var txt$1 = (void 0);
  1660. if (m[0] == "\t") {
  1661. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1662. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1663. txt$1.setAttribute("role", "presentation");
  1664. txt$1.setAttribute("cm-text", "\t");
  1665. builder.col += tabWidth;
  1666. } else if (m[0] == "\r" || m[0] == "\n") {
  1667. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1668. txt$1.setAttribute("cm-text", m[0]);
  1669. builder.col += 1;
  1670. } else {
  1671. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1672. txt$1.setAttribute("cm-text", m[0]);
  1673. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1674. else { content.appendChild(txt$1); }
  1675. builder.col += 1;
  1676. }
  1677. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1678. builder.pos++;
  1679. }
  1680. }
  1681. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1682. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1683. var fullStyle = style || "";
  1684. if (startStyle) { fullStyle += startStyle; }
  1685. if (endStyle) { fullStyle += endStyle; }
  1686. var token = elt("span", [content], fullStyle, css);
  1687. if (attributes) {
  1688. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1689. { token.setAttribute(attr, attributes[attr]); } }
  1690. }
  1691. return builder.content.appendChild(token)
  1692. }
  1693. builder.content.appendChild(content);
  1694. }
  1695. // Change some spaces to NBSP to prevent the browser from collapsing
  1696. // trailing spaces at the end of a line when rendering text (issue #1362).
  1697. function splitSpaces(text, trailingBefore) {
  1698. if (text.length > 1 && !/ /.test(text)) { return text }
  1699. var spaceBefore = trailingBefore, result = "";
  1700. for (var i = 0; i < text.length; i++) {
  1701. var ch = text.charAt(i);
  1702. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1703. { ch = "\u00a0"; }
  1704. result += ch;
  1705. spaceBefore = ch == " ";
  1706. }
  1707. return result
  1708. }
  1709. // Work around nonsense dimensions being reported for stretches of
  1710. // right-to-left text.
  1711. function buildTokenBadBidi(inner, order) {
  1712. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1713. style = style ? style + " cm-force-border" : "cm-force-border";
  1714. var start = builder.pos, end = start + text.length;
  1715. for (;;) {
  1716. // Find the part that overlaps with the start of this text
  1717. var part = (void 0);
  1718. for (var i = 0; i < order.length; i++) {
  1719. part = order[i];
  1720. if (part.to > start && part.from <= start) { break }
  1721. }
  1722. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1723. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1724. startStyle = null;
  1725. text = text.slice(part.to - start);
  1726. start = part.to;
  1727. }
  1728. }
  1729. }
  1730. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1731. var widget = !ignoreWidget && marker.widgetNode;
  1732. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1733. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1734. if (!widget)
  1735. { widget = builder.content.appendChild(document.createElement("span")); }
  1736. widget.setAttribute("cm-marker", marker.id);
  1737. }
  1738. if (widget) {
  1739. builder.cm.display.input.setUneditable(widget);
  1740. builder.content.appendChild(widget);
  1741. }
  1742. builder.pos += size;
  1743. builder.trailingSpace = false;
  1744. }
  1745. // Outputs a number of spans to make up a line, taking highlighting
  1746. // and marked text into account.
  1747. function insertLineContent(line, builder, styles) {
  1748. var spans = line.markedSpans, allText = line.text, at = 0;
  1749. if (!spans) {
  1750. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1751. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1752. return
  1753. }
  1754. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1755. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1756. for (;;) {
  1757. if (nextChange == pos) { // Update current marker set
  1758. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1759. attributes = null;
  1760. collapsed = null; nextChange = Infinity;
  1761. var foundBookmarks = [], endStyles = (void 0);
  1762. for (var j = 0; j < spans.length; ++j) {
  1763. var sp = spans[j], m = sp.marker;
  1764. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1765. foundBookmarks.push(m);
  1766. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1767. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1768. nextChange = sp.to;
  1769. spanEndStyle = "";
  1770. }
  1771. if (m.className) { spanStyle += " " + m.className; }
  1772. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1773. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1774. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1775. // support for the old title property
  1776. // https://github.com/codemirror/CodeMirror/pull/5673
  1777. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1778. if (m.attributes) {
  1779. for (var attr in m.attributes)
  1780. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1781. }
  1782. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1783. { collapsed = sp; }
  1784. } else if (sp.from > pos && nextChange > sp.from) {
  1785. nextChange = sp.from;
  1786. }
  1787. }
  1788. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1789. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1790. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1791. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1792. if (collapsed && (collapsed.from || 0) == pos) {
  1793. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1794. collapsed.marker, collapsed.from == null);
  1795. if (collapsed.to == null) { return }
  1796. if (collapsed.to == pos) { collapsed = false; }
  1797. }
  1798. }
  1799. if (pos >= len) { break }
  1800. var upto = Math.min(len, nextChange);
  1801. while (true) {
  1802. if (text) {
  1803. var end = pos + text.length;
  1804. if (!collapsed) {
  1805. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1806. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1807. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1808. }
  1809. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1810. pos = end;
  1811. spanStartStyle = "";
  1812. }
  1813. text = allText.slice(at, at = styles[i++]);
  1814. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1815. }
  1816. }
  1817. }
  1818. // These objects are used to represent the visible (currently drawn)
  1819. // part of the document. A LineView may correspond to multiple
  1820. // logical lines, if those are connected by collapsed ranges.
  1821. function LineView(doc, line, lineN) {
  1822. // The starting line
  1823. this.line = line;
  1824. // Continuing lines, if any
  1825. this.rest = visualLineContinued(line);
  1826. // Number of logical lines in this visual line
  1827. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1828. this.node = this.text = null;
  1829. this.hidden = lineIsHidden(doc, line);
  1830. }
  1831. // Create a range of LineView objects for the given lines.
  1832. function buildViewArray(cm, from, to) {
  1833. var array = [], nextPos;
  1834. for (var pos = from; pos < to; pos = nextPos) {
  1835. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1836. nextPos = pos + view.size;
  1837. array.push(view);
  1838. }
  1839. return array
  1840. }
  1841. var operationGroup = null;
  1842. function pushOperation(op) {
  1843. if (operationGroup) {
  1844. operationGroup.ops.push(op);
  1845. } else {
  1846. op.ownsGroup = operationGroup = {
  1847. ops: [op],
  1848. delayedCallbacks: []
  1849. };
  1850. }
  1851. }
  1852. function fireCallbacksForOps(group) {
  1853. // Calls delayed callbacks and cursorActivity handlers until no
  1854. // new ones appear
  1855. var callbacks = group.delayedCallbacks, i = 0;
  1856. do {
  1857. for (; i < callbacks.length; i++)
  1858. { callbacks[i].call(null); }
  1859. for (var j = 0; j < group.ops.length; j++) {
  1860. var op = group.ops[j];
  1861. if (op.cursorActivityHandlers)
  1862. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1863. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1864. }
  1865. } while (i < callbacks.length)
  1866. }
  1867. function finishOperation(op, endCb) {
  1868. var group = op.ownsGroup;
  1869. if (!group) { return }
  1870. try { fireCallbacksForOps(group); }
  1871. finally {
  1872. operationGroup = null;
  1873. endCb(group);
  1874. }
  1875. }
  1876. var orphanDelayedCallbacks = null;
  1877. // Often, we want to signal events at a point where we are in the
  1878. // middle of some work, but don't want the handler to start calling
  1879. // other methods on the editor, which might be in an inconsistent
  1880. // state or simply not expect any other events to happen.
  1881. // signalLater looks whether there are any handlers, and schedules
  1882. // them to be executed when the last operation ends, or, if no
  1883. // operation is active, when a timeout fires.
  1884. function signalLater(emitter, type /*, values...*/) {
  1885. var arr = getHandlers(emitter, type);
  1886. if (!arr.length) { return }
  1887. var args = Array.prototype.slice.call(arguments, 2), list;
  1888. if (operationGroup) {
  1889. list = operationGroup.delayedCallbacks;
  1890. } else if (orphanDelayedCallbacks) {
  1891. list = orphanDelayedCallbacks;
  1892. } else {
  1893. list = orphanDelayedCallbacks = [];
  1894. setTimeout(fireOrphanDelayed, 0);
  1895. }
  1896. var loop = function ( i ) {
  1897. list.push(function () { return arr[i].apply(null, args); });
  1898. };
  1899. for (var i = 0; i < arr.length; ++i)
  1900. loop( i );
  1901. }
  1902. function fireOrphanDelayed() {
  1903. var delayed = orphanDelayedCallbacks;
  1904. orphanDelayedCallbacks = null;
  1905. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1906. }
  1907. // When an aspect of a line changes, a string is added to
  1908. // lineView.changes. This updates the relevant part of the line's
  1909. // DOM structure.
  1910. function updateLineForChanges(cm, lineView, lineN, dims) {
  1911. for (var j = 0; j < lineView.changes.length; j++) {
  1912. var type = lineView.changes[j];
  1913. if (type == "text") { updateLineText(cm, lineView); }
  1914. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1915. else if (type == "class") { updateLineClasses(cm, lineView); }
  1916. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1917. }
  1918. lineView.changes = null;
  1919. }
  1920. // Lines with gutter elements, widgets or a background class need to
  1921. // be wrapped, and have the extra elements added to the wrapper div
  1922. function ensureLineWrapped(lineView) {
  1923. if (lineView.node == lineView.text) {
  1924. lineView.node = elt("div", null, null, "position: relative");
  1925. if (lineView.text.parentNode)
  1926. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1927. lineView.node.appendChild(lineView.text);
  1928. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1929. }
  1930. return lineView.node
  1931. }
  1932. function updateLineBackground(cm, lineView) {
  1933. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1934. if (cls) { cls += " CodeMirror-linebackground"; }
  1935. if (lineView.background) {
  1936. if (cls) { lineView.background.className = cls; }
  1937. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1938. } else if (cls) {
  1939. var wrap = ensureLineWrapped(lineView);
  1940. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1941. cm.display.input.setUneditable(lineView.background);
  1942. }
  1943. }
  1944. // Wrapper around buildLineContent which will reuse the structure
  1945. // in display.externalMeasured when possible.
  1946. function getLineContent(cm, lineView) {
  1947. var ext = cm.display.externalMeasured;
  1948. if (ext && ext.line == lineView.line) {
  1949. cm.display.externalMeasured = null;
  1950. lineView.measure = ext.measure;
  1951. return ext.built
  1952. }
  1953. return buildLineContent(cm, lineView)
  1954. }
  1955. // Redraw the line's text. Interacts with the background and text
  1956. // classes because the mode may output tokens that influence these
  1957. // classes.
  1958. function updateLineText(cm, lineView) {
  1959. var cls = lineView.text.className;
  1960. var built = getLineContent(cm, lineView);
  1961. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1962. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1963. lineView.text = built.pre;
  1964. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1965. lineView.bgClass = built.bgClass;
  1966. lineView.textClass = built.textClass;
  1967. updateLineClasses(cm, lineView);
  1968. } else if (cls) {
  1969. lineView.text.className = cls;
  1970. }
  1971. }
  1972. function updateLineClasses(cm, lineView) {
  1973. updateLineBackground(cm, lineView);
  1974. if (lineView.line.wrapClass)
  1975. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1976. else if (lineView.node != lineView.text)
  1977. { lineView.node.className = ""; }
  1978. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1979. lineView.text.className = textClass || "";
  1980. }
  1981. function updateLineGutter(cm, lineView, lineN, dims) {
  1982. if (lineView.gutter) {
  1983. lineView.node.removeChild(lineView.gutter);
  1984. lineView.gutter = null;
  1985. }
  1986. if (lineView.gutterBackground) {
  1987. lineView.node.removeChild(lineView.gutterBackground);
  1988. lineView.gutterBackground = null;
  1989. }
  1990. if (lineView.line.gutterClass) {
  1991. var wrap = ensureLineWrapped(lineView);
  1992. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1993. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1994. cm.display.input.setUneditable(lineView.gutterBackground);
  1995. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1996. }
  1997. var markers = lineView.line.gutterMarkers;
  1998. if (cm.options.lineNumbers || markers) {
  1999. var wrap$1 = ensureLineWrapped(lineView);
  2000. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2001. gutterWrap.setAttribute("aria-hidden", "true");
  2002. cm.display.input.setUneditable(gutterWrap);
  2003. wrap$1.insertBefore(gutterWrap, lineView.text);
  2004. if (lineView.line.gutterClass)
  2005. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2006. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2007. { lineView.lineNumber = gutterWrap.appendChild(
  2008. elt("div", lineNumberFor(cm.options, lineN),
  2009. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2010. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2011. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2012. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2013. if (found)
  2014. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2015. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2016. } }
  2017. }
  2018. }
  2019. function updateLineWidgets(cm, lineView, dims) {
  2020. if (lineView.alignable) { lineView.alignable = null; }
  2021. var isWidget = classTest("CodeMirror-linewidget");
  2022. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2023. next = node.nextSibling;
  2024. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2025. }
  2026. insertLineWidgets(cm, lineView, dims);
  2027. }
  2028. // Build a line's DOM representation from scratch
  2029. function buildLineElement(cm, lineView, lineN, dims) {
  2030. var built = getLineContent(cm, lineView);
  2031. lineView.text = lineView.node = built.pre;
  2032. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2033. if (built.textClass) { lineView.textClass = built.textClass; }
  2034. updateLineClasses(cm, lineView);
  2035. updateLineGutter(cm, lineView, lineN, dims);
  2036. insertLineWidgets(cm, lineView, dims);
  2037. return lineView.node
  2038. }
  2039. // A lineView may contain multiple logical lines (when merged by
  2040. // collapsed spans). The widgets for all of them need to be drawn.
  2041. function insertLineWidgets(cm, lineView, dims) {
  2042. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2043. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2044. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2045. }
  2046. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2047. if (!line.widgets) { return }
  2048. var wrap = ensureLineWrapped(lineView);
  2049. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2050. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2051. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2052. positionLineWidget(widget, node, lineView, dims);
  2053. cm.display.input.setUneditable(node);
  2054. if (allowAbove && widget.above)
  2055. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2056. else
  2057. { wrap.appendChild(node); }
  2058. signalLater(widget, "redraw");
  2059. }
  2060. }
  2061. function positionLineWidget(widget, node, lineView, dims) {
  2062. if (widget.noHScroll) {
  2063. (lineView.alignable || (lineView.alignable = [])).push(node);
  2064. var width = dims.wrapperWidth;
  2065. node.style.left = dims.fixedPos + "px";
  2066. if (!widget.coverGutter) {
  2067. width -= dims.gutterTotalWidth;
  2068. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2069. }
  2070. node.style.width = width + "px";
  2071. }
  2072. if (widget.coverGutter) {
  2073. node.style.zIndex = 5;
  2074. node.style.position = "relative";
  2075. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2076. }
  2077. }
  2078. function widgetHeight(widget) {
  2079. if (widget.height != null) { return widget.height }
  2080. var cm = widget.doc.cm;
  2081. if (!cm) { return 0 }
  2082. if (!contains(document.body, widget.node)) {
  2083. var parentStyle = "position: relative;";
  2084. if (widget.coverGutter)
  2085. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2086. if (widget.noHScroll)
  2087. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2088. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2089. }
  2090. return widget.height = widget.node.parentNode.offsetHeight
  2091. }
  2092. // Return true when the given mouse event happened in a widget
  2093. function eventInWidget(display, e) {
  2094. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2095. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2096. (n.parentNode == display.sizer && n != display.mover))
  2097. { return true }
  2098. }
  2099. }
  2100. // POSITION MEASUREMENT
  2101. function paddingTop(display) {return display.lineSpace.offsetTop}
  2102. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2103. function paddingH(display) {
  2104. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2105. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2106. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2107. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2108. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2109. return data
  2110. }
  2111. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2112. function displayWidth(cm) {
  2113. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2114. }
  2115. function displayHeight(cm) {
  2116. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2117. }
  2118. // Ensure the lineView.wrapping.heights array is populated. This is
  2119. // an array of bottom offsets for the lines that make up a drawn
  2120. // line. When lineWrapping is on, there might be more than one
  2121. // height.
  2122. function ensureLineHeights(cm, lineView, rect) {
  2123. var wrapping = cm.options.lineWrapping;
  2124. var curWidth = wrapping && displayWidth(cm);
  2125. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2126. var heights = lineView.measure.heights = [];
  2127. if (wrapping) {
  2128. lineView.measure.width = curWidth;
  2129. var rects = lineView.text.firstChild.getClientRects();
  2130. for (var i = 0; i < rects.length - 1; i++) {
  2131. var cur = rects[i], next = rects[i + 1];
  2132. if (Math.abs(cur.bottom - next.bottom) > 2)
  2133. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2134. }
  2135. }
  2136. heights.push(rect.bottom - rect.top);
  2137. }
  2138. }
  2139. // Find a line map (mapping character offsets to text nodes) and a
  2140. // measurement cache for the given line number. (A line view might
  2141. // contain multiple lines when collapsed ranges are present.)
  2142. function mapFromLineView(lineView, line, lineN) {
  2143. if (lineView.line == line)
  2144. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2145. if (lineView.rest) {
  2146. for (var i = 0; i < lineView.rest.length; i++)
  2147. { if (lineView.rest[i] == line)
  2148. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2149. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2150. { if (lineNo(lineView.rest[i$1]) > lineN)
  2151. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2152. }
  2153. }
  2154. // Render a line into the hidden node display.externalMeasured. Used
  2155. // when measurement is needed for a line that's not in the viewport.
  2156. function updateExternalMeasurement(cm, line) {
  2157. line = visualLine(line);
  2158. var lineN = lineNo(line);
  2159. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2160. view.lineN = lineN;
  2161. var built = view.built = buildLineContent(cm, view);
  2162. view.text = built.pre;
  2163. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2164. return view
  2165. }
  2166. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2167. // for a given character.
  2168. function measureChar(cm, line, ch, bias) {
  2169. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2170. }
  2171. // Find a line view that corresponds to the given line number.
  2172. function findViewForLine(cm, lineN) {
  2173. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2174. { return cm.display.view[findViewIndex(cm, lineN)] }
  2175. var ext = cm.display.externalMeasured;
  2176. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2177. { return ext }
  2178. }
  2179. // Measurement can be split in two steps, the set-up work that
  2180. // applies to the whole line, and the measurement of the actual
  2181. // character. Functions like coordsChar, that need to do a lot of
  2182. // measurements in a row, can thus ensure that the set-up work is
  2183. // only done once.
  2184. function prepareMeasureForLine(cm, line) {
  2185. var lineN = lineNo(line);
  2186. var view = findViewForLine(cm, lineN);
  2187. if (view && !view.text) {
  2188. view = null;
  2189. } else if (view && view.changes) {
  2190. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2191. cm.curOp.forceUpdate = true;
  2192. }
  2193. if (!view)
  2194. { view = updateExternalMeasurement(cm, line); }
  2195. var info = mapFromLineView(view, line, lineN);
  2196. return {
  2197. line: line, view: view, rect: null,
  2198. map: info.map, cache: info.cache, before: info.before,
  2199. hasHeights: false
  2200. }
  2201. }
  2202. // Given a prepared measurement object, measures the position of an
  2203. // actual character (or fetches it from the cache).
  2204. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2205. if (prepared.before) { ch = -1; }
  2206. var key = ch + (bias || ""), found;
  2207. if (prepared.cache.hasOwnProperty(key)) {
  2208. found = prepared.cache[key];
  2209. } else {
  2210. if (!prepared.rect)
  2211. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2212. if (!prepared.hasHeights) {
  2213. ensureLineHeights(cm, prepared.view, prepared.rect);
  2214. prepared.hasHeights = true;
  2215. }
  2216. found = measureCharInner(cm, prepared, ch, bias);
  2217. if (!found.bogus) { prepared.cache[key] = found; }
  2218. }
  2219. return {left: found.left, right: found.right,
  2220. top: varHeight ? found.rtop : found.top,
  2221. bottom: varHeight ? found.rbottom : found.bottom}
  2222. }
  2223. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2224. function nodeAndOffsetInLineMap(map, ch, bias) {
  2225. var node, start, end, collapse, mStart, mEnd;
  2226. // First, search the line map for the text node corresponding to,
  2227. // or closest to, the target character.
  2228. for (var i = 0; i < map.length; i += 3) {
  2229. mStart = map[i];
  2230. mEnd = map[i + 1];
  2231. if (ch < mStart) {
  2232. start = 0; end = 1;
  2233. collapse = "left";
  2234. } else if (ch < mEnd) {
  2235. start = ch - mStart;
  2236. end = start + 1;
  2237. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2238. end = mEnd - mStart;
  2239. start = end - 1;
  2240. if (ch >= mEnd) { collapse = "right"; }
  2241. }
  2242. if (start != null) {
  2243. node = map[i + 2];
  2244. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2245. { collapse = bias; }
  2246. if (bias == "left" && start == 0)
  2247. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2248. node = map[(i -= 3) + 2];
  2249. collapse = "left";
  2250. } }
  2251. if (bias == "right" && start == mEnd - mStart)
  2252. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2253. node = map[(i += 3) + 2];
  2254. collapse = "right";
  2255. } }
  2256. break
  2257. }
  2258. }
  2259. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2260. }
  2261. function getUsefulRect(rects, bias) {
  2262. var rect = nullRect;
  2263. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2264. if ((rect = rects[i]).left != rect.right) { break }
  2265. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2266. if ((rect = rects[i$1]).left != rect.right) { break }
  2267. } }
  2268. return rect
  2269. }
  2270. function measureCharInner(cm, prepared, ch, bias) {
  2271. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2272. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2273. var rect;
  2274. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2275. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2276. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2277. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2278. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2279. { rect = node.parentNode.getBoundingClientRect(); }
  2280. else
  2281. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2282. if (rect.left || rect.right || start == 0) { break }
  2283. end = start;
  2284. start = start - 1;
  2285. collapse = "right";
  2286. }
  2287. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2288. } else { // If it is a widget, simply get the box for the whole widget.
  2289. if (start > 0) { collapse = bias = "right"; }
  2290. var rects;
  2291. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2292. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2293. else
  2294. { rect = node.getBoundingClientRect(); }
  2295. }
  2296. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2297. var rSpan = node.parentNode.getClientRects()[0];
  2298. if (rSpan)
  2299. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2300. else
  2301. { rect = nullRect; }
  2302. }
  2303. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2304. var mid = (rtop + rbot) / 2;
  2305. var heights = prepared.view.measure.heights;
  2306. var i = 0;
  2307. for (; i < heights.length - 1; i++)
  2308. { if (mid < heights[i]) { break } }
  2309. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2310. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2311. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2312. top: top, bottom: bot};
  2313. if (!rect.left && !rect.right) { result.bogus = true; }
  2314. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2315. return result
  2316. }
  2317. // Work around problem with bounding client rects on ranges being
  2318. // returned incorrectly when zoomed on IE10 and below.
  2319. function maybeUpdateRectForZooming(measure, rect) {
  2320. if (!window.screen || screen.logicalXDPI == null ||
  2321. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2322. { return rect }
  2323. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2324. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2325. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2326. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2327. }
  2328. function clearLineMeasurementCacheFor(lineView) {
  2329. if (lineView.measure) {
  2330. lineView.measure.cache = {};
  2331. lineView.measure.heights = null;
  2332. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2333. { lineView.measure.caches[i] = {}; } }
  2334. }
  2335. }
  2336. function clearLineMeasurementCache(cm) {
  2337. cm.display.externalMeasure = null;
  2338. removeChildren(cm.display.lineMeasure);
  2339. for (var i = 0; i < cm.display.view.length; i++)
  2340. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2341. }
  2342. function clearCaches(cm) {
  2343. clearLineMeasurementCache(cm);
  2344. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2345. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2346. cm.display.lineNumChars = null;
  2347. }
  2348. function pageScrollX(doc) {
  2349. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2350. // which causes page_Offset and bounding client rects to use
  2351. // different reference viewports and invalidate our calculations.
  2352. if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
  2353. return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
  2354. }
  2355. function pageScrollY(doc) {
  2356. if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
  2357. return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
  2358. }
  2359. function widgetTopHeight(lineObj) {
  2360. var ref = visualLine(lineObj);
  2361. var widgets = ref.widgets;
  2362. var height = 0;
  2363. if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
  2364. { height += widgetHeight(widgets[i]); } } }
  2365. return height
  2366. }
  2367. // Converts a {top, bottom, left, right} box from line-local
  2368. // coordinates into another coordinate system. Context may be one of
  2369. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2370. // or "page".
  2371. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2372. if (!includeWidgets) {
  2373. var height = widgetTopHeight(lineObj);
  2374. rect.top += height; rect.bottom += height;
  2375. }
  2376. if (context == "line") { return rect }
  2377. if (!context) { context = "local"; }
  2378. var yOff = heightAtLine(lineObj);
  2379. if (context == "local") { yOff += paddingTop(cm.display); }
  2380. else { yOff -= cm.display.viewOffset; }
  2381. if (context == "page" || context == "window") {
  2382. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2383. yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
  2384. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
  2385. rect.left += xOff; rect.right += xOff;
  2386. }
  2387. rect.top += yOff; rect.bottom += yOff;
  2388. return rect
  2389. }
  2390. // Coverts a box from "div" coords to another coordinate system.
  2391. // Context may be "window", "page", "div", or "local"./null.
  2392. function fromCoordSystem(cm, coords, context) {
  2393. if (context == "div") { return coords }
  2394. var left = coords.left, top = coords.top;
  2395. // First move into "page" coordinate system
  2396. if (context == "page") {
  2397. left -= pageScrollX(doc(cm));
  2398. top -= pageScrollY(doc(cm));
  2399. } else if (context == "local" || !context) {
  2400. var localBox = cm.display.sizer.getBoundingClientRect();
  2401. left += localBox.left;
  2402. top += localBox.top;
  2403. }
  2404. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2405. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2406. }
  2407. function charCoords(cm, pos, context, lineObj, bias) {
  2408. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2409. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2410. }
  2411. // Returns a box for a given cursor position, which may have an
  2412. // 'other' property containing the position of the secondary cursor
  2413. // on a bidi boundary.
  2414. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2415. // and after `char - 1` in writing order of `char - 1`
  2416. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2417. // and before `char` in writing order of `char`
  2418. // Examples (upper-case letters are RTL, lower-case are LTR):
  2419. // Pos(0, 1, ...)
  2420. // before after
  2421. // ab a|b a|b
  2422. // aB a|B aB|
  2423. // Ab |Ab A|b
  2424. // AB B|A B|A
  2425. // Every position after the last character on a line is considered to stick
  2426. // to the last character on the line.
  2427. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2428. lineObj = lineObj || getLine(cm.doc, pos.line);
  2429. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2430. function get(ch, right) {
  2431. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2432. if (right) { m.left = m.right; } else { m.right = m.left; }
  2433. return intoCoordSystem(cm, lineObj, m, context)
  2434. }
  2435. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2436. if (ch >= lineObj.text.length) {
  2437. ch = lineObj.text.length;
  2438. sticky = "before";
  2439. } else if (ch <= 0) {
  2440. ch = 0;
  2441. sticky = "after";
  2442. }
  2443. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2444. function getBidi(ch, partPos, invert) {
  2445. var part = order[partPos], right = part.level == 1;
  2446. return get(invert ? ch - 1 : ch, right != invert)
  2447. }
  2448. var partPos = getBidiPartAt(order, ch, sticky);
  2449. var other = bidiOther;
  2450. var val = getBidi(ch, partPos, sticky == "before");
  2451. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2452. return val
  2453. }
  2454. // Used to cheaply estimate the coordinates for a position. Used for
  2455. // intermediate scroll updates.
  2456. function estimateCoords(cm, pos) {
  2457. var left = 0;
  2458. pos = clipPos(cm.doc, pos);
  2459. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2460. var lineObj = getLine(cm.doc, pos.line);
  2461. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2462. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2463. }
  2464. // Positions returned by coordsChar contain some extra information.
  2465. // xRel is the relative x position of the input coordinates compared
  2466. // to the found position (so xRel > 0 means the coordinates are to
  2467. // the right of the character position, for example). When outside
  2468. // is true, that means the coordinates lie outside the line's
  2469. // vertical range.
  2470. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2471. var pos = Pos(line, ch, sticky);
  2472. pos.xRel = xRel;
  2473. if (outside) { pos.outside = outside; }
  2474. return pos
  2475. }
  2476. // Compute the character position closest to the given coordinates.
  2477. // Input must be lineSpace-local ("div" coordinate system).
  2478. function coordsChar(cm, x, y) {
  2479. var doc = cm.doc;
  2480. y += cm.display.viewOffset;
  2481. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2482. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2483. if (lineN > last)
  2484. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2485. if (x < 0) { x = 0; }
  2486. var lineObj = getLine(doc, lineN);
  2487. for (;;) {
  2488. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2489. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2490. if (!collapsed) { return found }
  2491. var rangeEnd = collapsed.find(1);
  2492. if (rangeEnd.line == lineN) { return rangeEnd }
  2493. lineObj = getLine(doc, lineN = rangeEnd.line);
  2494. }
  2495. }
  2496. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2497. y -= widgetTopHeight(lineObj);
  2498. var end = lineObj.text.length;
  2499. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2500. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2501. return {begin: begin, end: end}
  2502. }
  2503. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2504. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2505. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2506. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2507. }
  2508. // Returns true if the given side of a box is after the given
  2509. // coordinates, in top-to-bottom, left-to-right order.
  2510. function boxIsAfter(box, x, y, left) {
  2511. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2512. }
  2513. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2514. // Move y into line-local coordinate space
  2515. y -= heightAtLine(lineObj);
  2516. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2517. // When directly calling `measureCharPrepared`, we have to adjust
  2518. // for the widgets at this line.
  2519. var widgetHeight = widgetTopHeight(lineObj);
  2520. var begin = 0, end = lineObj.text.length, ltr = true;
  2521. var order = getOrder(lineObj, cm.doc.direction);
  2522. // If the line isn't plain left-to-right text, first figure out
  2523. // which bidi section the coordinates fall into.
  2524. if (order) {
  2525. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2526. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2527. ltr = part.level != 1;
  2528. // The awkward -1 offsets are needed because findFirst (called
  2529. // on these below) will treat its first bound as inclusive,
  2530. // second as exclusive, but we want to actually address the
  2531. // characters in the part's range
  2532. begin = ltr ? part.from : part.to - 1;
  2533. end = ltr ? part.to : part.from - 1;
  2534. }
  2535. // A binary search to find the first character whose bounding box
  2536. // starts after the coordinates. If we run across any whose box wrap
  2537. // the coordinates, store that.
  2538. var chAround = null, boxAround = null;
  2539. var ch = findFirst(function (ch) {
  2540. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2541. box.top += widgetHeight; box.bottom += widgetHeight;
  2542. if (!boxIsAfter(box, x, y, false)) { return false }
  2543. if (box.top <= y && box.left <= x) {
  2544. chAround = ch;
  2545. boxAround = box;
  2546. }
  2547. return true
  2548. }, begin, end);
  2549. var baseX, sticky, outside = false;
  2550. // If a box around the coordinates was found, use that
  2551. if (boxAround) {
  2552. // Distinguish coordinates nearer to the left or right side of the box
  2553. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2554. ch = chAround + (atStart ? 0 : 1);
  2555. sticky = atStart ? "after" : "before";
  2556. baseX = atLeft ? boxAround.left : boxAround.right;
  2557. } else {
  2558. // (Adjust for extended bound, if necessary.)
  2559. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2560. // To determine which side to associate with, get the box to the
  2561. // left of the character and compare it's vertical position to the
  2562. // coordinates
  2563. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2564. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2565. "after" : "before";
  2566. // Now get accurate coordinates for this place, in order to get a
  2567. // base X position
  2568. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2569. baseX = coords.left;
  2570. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2571. }
  2572. ch = skipExtendingChars(lineObj.text, ch, 1);
  2573. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2574. }
  2575. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2576. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2577. // situation, we can take this ordering to correspond to the visual
  2578. // ordering. This finds the first part whose end is after the given
  2579. // coordinates.
  2580. var index = findFirst(function (i) {
  2581. var part = order[i], ltr = part.level != 1;
  2582. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2583. "line", lineObj, preparedMeasure), x, y, true)
  2584. }, 0, order.length - 1);
  2585. var part = order[index];
  2586. // If this isn't the first part, the part's start is also after
  2587. // the coordinates, and the coordinates aren't on the same line as
  2588. // that start, move one part back.
  2589. if (index > 0) {
  2590. var ltr = part.level != 1;
  2591. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2592. "line", lineObj, preparedMeasure);
  2593. if (boxIsAfter(start, x, y, true) && start.top > y)
  2594. { part = order[index - 1]; }
  2595. }
  2596. return part
  2597. }
  2598. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2599. // In a wrapped line, rtl text on wrapping boundaries can do things
  2600. // that don't correspond to the ordering in our `order` array at
  2601. // all, so a binary search doesn't work, and we want to return a
  2602. // part that only spans one line so that the binary search in
  2603. // coordsCharInner is safe. As such, we first find the extent of the
  2604. // wrapped line, and then do a flat search in which we discard any
  2605. // spans that aren't on the line.
  2606. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2607. var begin = ref.begin;
  2608. var end = ref.end;
  2609. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2610. var part = null, closestDist = null;
  2611. for (var i = 0; i < order.length; i++) {
  2612. var p = order[i];
  2613. if (p.from >= end || p.to <= begin) { continue }
  2614. var ltr = p.level != 1;
  2615. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2616. // Weigh against spans ending before this, so that they are only
  2617. // picked if nothing ends after
  2618. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2619. if (!part || closestDist > dist) {
  2620. part = p;
  2621. closestDist = dist;
  2622. }
  2623. }
  2624. if (!part) { part = order[order.length - 1]; }
  2625. // Clip the part to the wrapped line.
  2626. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2627. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2628. return part
  2629. }
  2630. var measureText;
  2631. // Compute the default text height.
  2632. function textHeight(display) {
  2633. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2634. if (measureText == null) {
  2635. measureText = elt("pre", null, "CodeMirror-line-like");
  2636. // Measure a bunch of lines, for browsers that compute
  2637. // fractional heights.
  2638. for (var i = 0; i < 49; ++i) {
  2639. measureText.appendChild(document.createTextNode("x"));
  2640. measureText.appendChild(elt("br"));
  2641. }
  2642. measureText.appendChild(document.createTextNode("x"));
  2643. }
  2644. removeChildrenAndAdd(display.measure, measureText);
  2645. var height = measureText.offsetHeight / 50;
  2646. if (height > 3) { display.cachedTextHeight = height; }
  2647. removeChildren(display.measure);
  2648. return height || 1
  2649. }
  2650. // Compute the default character width.
  2651. function charWidth(display) {
  2652. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2653. var anchor = elt("span", "xxxxxxxxxx");
  2654. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2655. removeChildrenAndAdd(display.measure, pre);
  2656. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2657. if (width > 2) { display.cachedCharWidth = width; }
  2658. return width || 10
  2659. }
  2660. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2661. // view, so that we don't interleave reading and writing to the DOM.
  2662. function getDimensions(cm) {
  2663. var d = cm.display, left = {}, width = {};
  2664. var gutterLeft = d.gutters.clientLeft;
  2665. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2666. var id = cm.display.gutterSpecs[i].className;
  2667. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2668. width[id] = n.clientWidth;
  2669. }
  2670. return {fixedPos: compensateForHScroll(d),
  2671. gutterTotalWidth: d.gutters.offsetWidth,
  2672. gutterLeft: left,
  2673. gutterWidth: width,
  2674. wrapperWidth: d.wrapper.clientWidth}
  2675. }
  2676. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2677. // but using getBoundingClientRect to get a sub-pixel-accurate
  2678. // result.
  2679. function compensateForHScroll(display) {
  2680. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2681. }
  2682. // Returns a function that estimates the height of a line, to use as
  2683. // first approximation until the line becomes visible (and is thus
  2684. // properly measurable).
  2685. function estimateHeight(cm) {
  2686. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2687. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2688. return function (line) {
  2689. if (lineIsHidden(cm.doc, line)) { return 0 }
  2690. var widgetsHeight = 0;
  2691. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2692. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2693. } }
  2694. if (wrapping)
  2695. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2696. else
  2697. { return widgetsHeight + th }
  2698. }
  2699. }
  2700. function estimateLineHeights(cm) {
  2701. var doc = cm.doc, est = estimateHeight(cm);
  2702. doc.iter(function (line) {
  2703. var estHeight = est(line);
  2704. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2705. });
  2706. }
  2707. // Given a mouse event, find the corresponding position. If liberal
  2708. // is false, it checks whether a gutter or scrollbar was clicked,
  2709. // and returns null if it was. forRect is used by rectangular
  2710. // selections, and tries to estimate a character position even for
  2711. // coordinates beyond the right of the text.
  2712. function posFromMouse(cm, e, liberal, forRect) {
  2713. var display = cm.display;
  2714. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2715. var x, y, space = display.lineSpace.getBoundingClientRect();
  2716. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2717. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2718. catch (e$1) { return null }
  2719. var coords = coordsChar(cm, x, y), line;
  2720. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2721. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2722. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2723. }
  2724. return coords
  2725. }
  2726. // Find the view element corresponding to a given line. Return null
  2727. // when the line isn't visible.
  2728. function findViewIndex(cm, n) {
  2729. if (n >= cm.display.viewTo) { return null }
  2730. n -= cm.display.viewFrom;
  2731. if (n < 0) { return null }
  2732. var view = cm.display.view;
  2733. for (var i = 0; i < view.length; i++) {
  2734. n -= view[i].size;
  2735. if (n < 0) { return i }
  2736. }
  2737. }
  2738. // Updates the display.view data structure for a given change to the
  2739. // document. From and to are in pre-change coordinates. Lendiff is
  2740. // the amount of lines added or subtracted by the change. This is
  2741. // used for changes that span multiple lines, or change the way
  2742. // lines are divided into visual lines. regLineChange (below)
  2743. // registers single-line changes.
  2744. function regChange(cm, from, to, lendiff) {
  2745. if (from == null) { from = cm.doc.first; }
  2746. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2747. if (!lendiff) { lendiff = 0; }
  2748. var display = cm.display;
  2749. if (lendiff && to < display.viewTo &&
  2750. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2751. { display.updateLineNumbers = from; }
  2752. cm.curOp.viewChanged = true;
  2753. if (from >= display.viewTo) { // Change after
  2754. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2755. { resetView(cm); }
  2756. } else if (to <= display.viewFrom) { // Change before
  2757. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2758. resetView(cm);
  2759. } else {
  2760. display.viewFrom += lendiff;
  2761. display.viewTo += lendiff;
  2762. }
  2763. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2764. resetView(cm);
  2765. } else if (from <= display.viewFrom) { // Top overlap
  2766. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2767. if (cut) {
  2768. display.view = display.view.slice(cut.index);
  2769. display.viewFrom = cut.lineN;
  2770. display.viewTo += lendiff;
  2771. } else {
  2772. resetView(cm);
  2773. }
  2774. } else if (to >= display.viewTo) { // Bottom overlap
  2775. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2776. if (cut$1) {
  2777. display.view = display.view.slice(0, cut$1.index);
  2778. display.viewTo = cut$1.lineN;
  2779. } else {
  2780. resetView(cm);
  2781. }
  2782. } else { // Gap in the middle
  2783. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2784. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2785. if (cutTop && cutBot) {
  2786. display.view = display.view.slice(0, cutTop.index)
  2787. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2788. .concat(display.view.slice(cutBot.index));
  2789. display.viewTo += lendiff;
  2790. } else {
  2791. resetView(cm);
  2792. }
  2793. }
  2794. var ext = display.externalMeasured;
  2795. if (ext) {
  2796. if (to < ext.lineN)
  2797. { ext.lineN += lendiff; }
  2798. else if (from < ext.lineN + ext.size)
  2799. { display.externalMeasured = null; }
  2800. }
  2801. }
  2802. // Register a change to a single line. Type must be one of "text",
  2803. // "gutter", "class", "widget"
  2804. function regLineChange(cm, line, type) {
  2805. cm.curOp.viewChanged = true;
  2806. var display = cm.display, ext = cm.display.externalMeasured;
  2807. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2808. { display.externalMeasured = null; }
  2809. if (line < display.viewFrom || line >= display.viewTo) { return }
  2810. var lineView = display.view[findViewIndex(cm, line)];
  2811. if (lineView.node == null) { return }
  2812. var arr = lineView.changes || (lineView.changes = []);
  2813. if (indexOf(arr, type) == -1) { arr.push(type); }
  2814. }
  2815. // Clear the view.
  2816. function resetView(cm) {
  2817. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2818. cm.display.view = [];
  2819. cm.display.viewOffset = 0;
  2820. }
  2821. function viewCuttingPoint(cm, oldN, newN, dir) {
  2822. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2823. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2824. { return {index: index, lineN: newN} }
  2825. var n = cm.display.viewFrom;
  2826. for (var i = 0; i < index; i++)
  2827. { n += view[i].size; }
  2828. if (n != oldN) {
  2829. if (dir > 0) {
  2830. if (index == view.length - 1) { return null }
  2831. diff = (n + view[index].size) - oldN;
  2832. index++;
  2833. } else {
  2834. diff = n - oldN;
  2835. }
  2836. oldN += diff; newN += diff;
  2837. }
  2838. while (visualLineNo(cm.doc, newN) != newN) {
  2839. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2840. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2841. index += dir;
  2842. }
  2843. return {index: index, lineN: newN}
  2844. }
  2845. // Force the view to cover a given range, adding empty view element
  2846. // or clipping off existing ones as needed.
  2847. function adjustView(cm, from, to) {
  2848. var display = cm.display, view = display.view;
  2849. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2850. display.view = buildViewArray(cm, from, to);
  2851. display.viewFrom = from;
  2852. } else {
  2853. if (display.viewFrom > from)
  2854. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2855. else if (display.viewFrom < from)
  2856. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2857. display.viewFrom = from;
  2858. if (display.viewTo < to)
  2859. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2860. else if (display.viewTo > to)
  2861. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2862. }
  2863. display.viewTo = to;
  2864. }
  2865. // Count the number of lines in the view whose DOM representation is
  2866. // out of date (or nonexistent).
  2867. function countDirtyView(cm) {
  2868. var view = cm.display.view, dirty = 0;
  2869. for (var i = 0; i < view.length; i++) {
  2870. var lineView = view[i];
  2871. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2872. }
  2873. return dirty
  2874. }
  2875. function updateSelection(cm) {
  2876. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2877. }
  2878. function prepareSelection(cm, primary) {
  2879. if ( primary === void 0 ) primary = true;
  2880. var doc = cm.doc, result = {};
  2881. var curFragment = result.cursors = document.createDocumentFragment();
  2882. var selFragment = result.selection = document.createDocumentFragment();
  2883. var customCursor = cm.options.$customCursor;
  2884. if (customCursor) { primary = true; }
  2885. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2886. if (!primary && i == doc.sel.primIndex) { continue }
  2887. var range = doc.sel.ranges[i];
  2888. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2889. var collapsed = range.empty();
  2890. if (customCursor) {
  2891. var head = customCursor(cm, range);
  2892. if (head) { drawSelectionCursor(cm, head, curFragment); }
  2893. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  2894. drawSelectionCursor(cm, range.head, curFragment);
  2895. }
  2896. if (!collapsed)
  2897. { drawSelectionRange(cm, range, selFragment); }
  2898. }
  2899. return result
  2900. }
  2901. // Draws a cursor for the given range
  2902. function drawSelectionCursor(cm, head, output) {
  2903. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2904. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2905. cursor.style.left = pos.left + "px";
  2906. cursor.style.top = pos.top + "px";
  2907. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2908. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  2909. var charPos = charCoords(cm, head, "div", null, null);
  2910. var width = charPos.right - charPos.left;
  2911. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  2912. }
  2913. if (pos.other) {
  2914. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2915. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2916. otherCursor.style.display = "";
  2917. otherCursor.style.left = pos.other.left + "px";
  2918. otherCursor.style.top = pos.other.top + "px";
  2919. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2920. }
  2921. }
  2922. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2923. // Draws the given range as a highlighted selection
  2924. function drawSelectionRange(cm, range, output) {
  2925. var display = cm.display, doc = cm.doc;
  2926. var fragment = document.createDocumentFragment();
  2927. var padding = paddingH(cm.display), leftSide = padding.left;
  2928. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2929. var docLTR = doc.direction == "ltr";
  2930. function add(left, top, width, bottom) {
  2931. if (top < 0) { top = 0; }
  2932. top = Math.round(top);
  2933. bottom = Math.round(bottom);
  2934. 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")));
  2935. }
  2936. function drawForLine(line, fromArg, toArg) {
  2937. var lineObj = getLine(doc, line);
  2938. var lineLen = lineObj.text.length;
  2939. var start, end;
  2940. function coords(ch, bias) {
  2941. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2942. }
  2943. function wrapX(pos, dir, side) {
  2944. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2945. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2946. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2947. return coords(ch, prop)[prop]
  2948. }
  2949. var order = getOrder(lineObj, doc.direction);
  2950. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2951. var ltr = dir == "ltr";
  2952. var fromPos = coords(from, ltr ? "left" : "right");
  2953. var toPos = coords(to - 1, ltr ? "right" : "left");
  2954. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2955. var first = i == 0, last = !order || i == order.length - 1;
  2956. if (toPos.top - fromPos.top <= 3) { // Single line
  2957. var openLeft = (docLTR ? openStart : openEnd) && first;
  2958. var openRight = (docLTR ? openEnd : openStart) && last;
  2959. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2960. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2961. add(left, fromPos.top, right - left, fromPos.bottom);
  2962. } else { // Multiple lines
  2963. var topLeft, topRight, botLeft, botRight;
  2964. if (ltr) {
  2965. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2966. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2967. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2968. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2969. } else {
  2970. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2971. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2972. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2973. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2974. }
  2975. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2976. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2977. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2978. }
  2979. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2980. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2981. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2982. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2983. });
  2984. return {start: start, end: end}
  2985. }
  2986. var sFrom = range.from(), sTo = range.to();
  2987. if (sFrom.line == sTo.line) {
  2988. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2989. } else {
  2990. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2991. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2992. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2993. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2994. if (singleVLine) {
  2995. if (leftEnd.top < rightStart.top - 2) {
  2996. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2997. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2998. } else {
  2999. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3000. }
  3001. }
  3002. if (leftEnd.bottom < rightStart.top)
  3003. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3004. }
  3005. output.appendChild(fragment);
  3006. }
  3007. // Cursor-blinking
  3008. function restartBlink(cm) {
  3009. if (!cm.state.focused) { return }
  3010. var display = cm.display;
  3011. clearInterval(display.blinker);
  3012. var on = true;
  3013. display.cursorDiv.style.visibility = "";
  3014. if (cm.options.cursorBlinkRate > 0)
  3015. { display.blinker = setInterval(function () {
  3016. if (!cm.hasFocus()) { onBlur(cm); }
  3017. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3018. }, cm.options.cursorBlinkRate); }
  3019. else if (cm.options.cursorBlinkRate < 0)
  3020. { display.cursorDiv.style.visibility = "hidden"; }
  3021. }
  3022. function ensureFocus(cm) {
  3023. if (!cm.hasFocus()) {
  3024. cm.display.input.focus();
  3025. if (!cm.state.focused) { onFocus(cm); }
  3026. }
  3027. }
  3028. function delayBlurEvent(cm) {
  3029. cm.state.delayingBlurEvent = true;
  3030. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3031. cm.state.delayingBlurEvent = false;
  3032. if (cm.state.focused) { onBlur(cm); }
  3033. } }, 100);
  3034. }
  3035. function onFocus(cm, e) {
  3036. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3037. if (cm.options.readOnly == "nocursor") { return }
  3038. if (!cm.state.focused) {
  3039. signal(cm, "focus", cm, e);
  3040. cm.state.focused = true;
  3041. addClass(cm.display.wrapper, "CodeMirror-focused");
  3042. // This test prevents this from firing when a context
  3043. // menu is closed (since the input reset would kill the
  3044. // select-all detection hack)
  3045. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3046. cm.display.input.reset();
  3047. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3048. }
  3049. cm.display.input.receivedFocus();
  3050. }
  3051. restartBlink(cm);
  3052. }
  3053. function onBlur(cm, e) {
  3054. if (cm.state.delayingBlurEvent) { return }
  3055. if (cm.state.focused) {
  3056. signal(cm, "blur", cm, e);
  3057. cm.state.focused = false;
  3058. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3059. }
  3060. clearInterval(cm.display.blinker);
  3061. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3062. }
  3063. // Read the actual heights of the rendered lines, and update their
  3064. // stored heights to match.
  3065. function updateHeightsInViewport(cm) {
  3066. var display = cm.display;
  3067. var prevBottom = display.lineDiv.offsetTop;
  3068. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  3069. var oldHeight = display.lineDiv.getBoundingClientRect().top;
  3070. var mustScroll = 0;
  3071. for (var i = 0; i < display.view.length; i++) {
  3072. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3073. var height = (void 0), width = 0;
  3074. if (cur.hidden) { continue }
  3075. oldHeight += cur.line.height;
  3076. if (ie && ie_version < 8) {
  3077. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3078. height = bot - prevBottom;
  3079. prevBottom = bot;
  3080. } else {
  3081. var box = cur.node.getBoundingClientRect();
  3082. height = box.bottom - box.top;
  3083. // Check that lines don't extend past the right of the current
  3084. // editor width
  3085. if (!wrapping && cur.text.firstChild)
  3086. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3087. }
  3088. var diff = cur.line.height - height;
  3089. if (diff > .005 || diff < -.005) {
  3090. if (oldHeight < viewTop) { mustScroll -= diff; }
  3091. updateLineHeight(cur.line, height);
  3092. updateWidgetHeight(cur.line);
  3093. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3094. { updateWidgetHeight(cur.rest[j]); } }
  3095. }
  3096. if (width > cm.display.sizerWidth) {
  3097. var chWidth = Math.ceil(width / charWidth(cm.display));
  3098. if (chWidth > cm.display.maxLineLength) {
  3099. cm.display.maxLineLength = chWidth;
  3100. cm.display.maxLine = cur.line;
  3101. cm.display.maxLineChanged = true;
  3102. }
  3103. }
  3104. }
  3105. if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  3106. }
  3107. // Read and store the height of line widgets associated with the
  3108. // given line.
  3109. function updateWidgetHeight(line) {
  3110. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3111. var w = line.widgets[i], parent = w.node.parentNode;
  3112. if (parent) { w.height = parent.offsetHeight; }
  3113. } }
  3114. }
  3115. // Compute the lines that are visible in a given viewport (defaults
  3116. // the the current scroll position). viewport may contain top,
  3117. // height, and ensure (see op.scrollToPos) properties.
  3118. function visibleLines(display, doc, viewport) {
  3119. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3120. top = Math.floor(top - paddingTop(display));
  3121. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3122. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3123. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3124. // forces those lines into the viewport (if possible).
  3125. if (viewport && viewport.ensure) {
  3126. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3127. if (ensureFrom < from) {
  3128. from = ensureFrom;
  3129. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3130. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3131. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3132. to = ensureTo;
  3133. }
  3134. }
  3135. return {from: from, to: Math.max(to, from + 1)}
  3136. }
  3137. // SCROLLING THINGS INTO VIEW
  3138. // If an editor sits on the top or bottom of the window, partially
  3139. // scrolled out of view, this ensures that the cursor is visible.
  3140. function maybeScrollWindow(cm, rect) {
  3141. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3142. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3143. var doc = display.wrapper.ownerDocument;
  3144. if (rect.top + box.top < 0) { doScroll = true; }
  3145. else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
  3146. if (doScroll != null && !phantom) {
  3147. 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;"));
  3148. cm.display.lineSpace.appendChild(scrollNode);
  3149. scrollNode.scrollIntoView(doScroll);
  3150. cm.display.lineSpace.removeChild(scrollNode);
  3151. }
  3152. }
  3153. // Scroll a given position into view (immediately), verifying that
  3154. // it actually became visible (as line heights are accurately
  3155. // measured, the position of something may 'drift' during drawing).
  3156. function scrollPosIntoView(cm, pos, end, margin) {
  3157. if (margin == null) { margin = 0; }
  3158. var rect;
  3159. if (!cm.options.lineWrapping && pos == end) {
  3160. // Set pos and end to the cursor positions around the character pos sticks to
  3161. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3162. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3163. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3164. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3165. }
  3166. for (var limit = 0; limit < 5; limit++) {
  3167. var changed = false;
  3168. var coords = cursorCoords(cm, pos);
  3169. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3170. rect = {left: Math.min(coords.left, endCoords.left),
  3171. top: Math.min(coords.top, endCoords.top) - margin,
  3172. right: Math.max(coords.left, endCoords.left),
  3173. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3174. var scrollPos = calculateScrollPos(cm, rect);
  3175. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3176. if (scrollPos.scrollTop != null) {
  3177. updateScrollTop(cm, scrollPos.scrollTop);
  3178. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3179. }
  3180. if (scrollPos.scrollLeft != null) {
  3181. setScrollLeft(cm, scrollPos.scrollLeft);
  3182. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3183. }
  3184. if (!changed) { break }
  3185. }
  3186. return rect
  3187. }
  3188. // Scroll a given set of coordinates into view (immediately).
  3189. function scrollIntoView(cm, rect) {
  3190. var scrollPos = calculateScrollPos(cm, rect);
  3191. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3192. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3193. }
  3194. // Calculate a new scroll position needed to scroll the given
  3195. // rectangle into view. Returns an object with scrollTop and
  3196. // scrollLeft properties. When these are undefined, the
  3197. // vertical/horizontal position does not need to be adjusted.
  3198. function calculateScrollPos(cm, rect) {
  3199. var display = cm.display, snapMargin = textHeight(cm.display);
  3200. if (rect.top < 0) { rect.top = 0; }
  3201. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3202. var screen = displayHeight(cm), result = {};
  3203. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3204. var docBottom = cm.doc.height + paddingVert(display);
  3205. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3206. if (rect.top < screentop) {
  3207. result.scrollTop = atTop ? 0 : rect.top;
  3208. } else if (rect.bottom > screentop + screen) {
  3209. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3210. if (newTop != screentop) { result.scrollTop = newTop; }
  3211. }
  3212. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3213. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3214. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3215. var tooWide = rect.right - rect.left > screenw;
  3216. if (tooWide) { rect.right = rect.left + screenw; }
  3217. if (rect.left < 10)
  3218. { result.scrollLeft = 0; }
  3219. else if (rect.left < screenleft)
  3220. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3221. else if (rect.right > screenw + screenleft - 3)
  3222. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3223. return result
  3224. }
  3225. // Store a relative adjustment to the scroll position in the current
  3226. // operation (to be applied when the operation finishes).
  3227. function addToScrollTop(cm, top) {
  3228. if (top == null) { return }
  3229. resolveScrollToPos(cm);
  3230. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3231. }
  3232. // Make sure that at the end of the operation the current cursor is
  3233. // shown.
  3234. function ensureCursorVisible(cm) {
  3235. resolveScrollToPos(cm);
  3236. var cur = cm.getCursor();
  3237. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3238. }
  3239. function scrollToCoords(cm, x, y) {
  3240. if (x != null || y != null) { resolveScrollToPos(cm); }
  3241. if (x != null) { cm.curOp.scrollLeft = x; }
  3242. if (y != null) { cm.curOp.scrollTop = y; }
  3243. }
  3244. function scrollToRange(cm, range) {
  3245. resolveScrollToPos(cm);
  3246. cm.curOp.scrollToPos = range;
  3247. }
  3248. // When an operation has its scrollToPos property set, and another
  3249. // scroll action is applied before the end of the operation, this
  3250. // 'simulates' scrolling that position into view in a cheap way, so
  3251. // that the effect of intermediate scroll commands is not ignored.
  3252. function resolveScrollToPos(cm) {
  3253. var range = cm.curOp.scrollToPos;
  3254. if (range) {
  3255. cm.curOp.scrollToPos = null;
  3256. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3257. scrollToCoordsRange(cm, from, to, range.margin);
  3258. }
  3259. }
  3260. function scrollToCoordsRange(cm, from, to, margin) {
  3261. var sPos = calculateScrollPos(cm, {
  3262. left: Math.min(from.left, to.left),
  3263. top: Math.min(from.top, to.top) - margin,
  3264. right: Math.max(from.right, to.right),
  3265. bottom: Math.max(from.bottom, to.bottom) + margin
  3266. });
  3267. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3268. }
  3269. // Sync the scrollable area and scrollbars, ensure the viewport
  3270. // covers the visible area.
  3271. function updateScrollTop(cm, val) {
  3272. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3273. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3274. setScrollTop(cm, val, true);
  3275. if (gecko) { updateDisplaySimple(cm); }
  3276. startWorker(cm, 100);
  3277. }
  3278. function setScrollTop(cm, val, forceScroll) {
  3279. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3280. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3281. cm.doc.scrollTop = val;
  3282. cm.display.scrollbars.setScrollTop(val);
  3283. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3284. }
  3285. // Sync scroller and scrollbar, ensure the gutter elements are
  3286. // aligned.
  3287. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3288. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3289. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3290. cm.doc.scrollLeft = val;
  3291. alignHorizontally(cm);
  3292. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3293. cm.display.scrollbars.setScrollLeft(val);
  3294. }
  3295. // SCROLLBARS
  3296. // Prepare DOM reads needed to update the scrollbars. Done in one
  3297. // shot to minimize update/measure roundtrips.
  3298. function measureForScrollbars(cm) {
  3299. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3300. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3301. return {
  3302. clientHeight: d.scroller.clientHeight,
  3303. viewHeight: d.wrapper.clientHeight,
  3304. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3305. viewWidth: d.wrapper.clientWidth,
  3306. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3307. docHeight: docH,
  3308. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3309. nativeBarWidth: d.nativeBarWidth,
  3310. gutterWidth: gutterW
  3311. }
  3312. }
  3313. var NativeScrollbars = function(place, scroll, cm) {
  3314. this.cm = cm;
  3315. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3316. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3317. vert.tabIndex = horiz.tabIndex = -1;
  3318. place(vert); place(horiz);
  3319. on(vert, "scroll", function () {
  3320. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3321. });
  3322. on(horiz, "scroll", function () {
  3323. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3324. });
  3325. this.checkedZeroWidth = false;
  3326. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3327. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3328. };
  3329. NativeScrollbars.prototype.update = function (measure) {
  3330. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3331. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3332. var sWidth = measure.nativeBarWidth;
  3333. if (needsV) {
  3334. this.vert.style.display = "block";
  3335. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3336. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3337. // A bug in IE8 can cause this value to be negative, so guard it.
  3338. this.vert.firstChild.style.height =
  3339. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3340. } else {
  3341. this.vert.scrollTop = 0;
  3342. this.vert.style.display = "";
  3343. this.vert.firstChild.style.height = "0";
  3344. }
  3345. if (needsH) {
  3346. this.horiz.style.display = "block";
  3347. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3348. this.horiz.style.left = measure.barLeft + "px";
  3349. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3350. this.horiz.firstChild.style.width =
  3351. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3352. } else {
  3353. this.horiz.style.display = "";
  3354. this.horiz.firstChild.style.width = "0";
  3355. }
  3356. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3357. if (sWidth == 0) { this.zeroWidthHack(); }
  3358. this.checkedZeroWidth = true;
  3359. }
  3360. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3361. };
  3362. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3363. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3364. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3365. };
  3366. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3367. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3368. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3369. };
  3370. NativeScrollbars.prototype.zeroWidthHack = function () {
  3371. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3372. this.horiz.style.height = this.vert.style.width = w;
  3373. this.horiz.style.visibility = this.vert.style.visibility = "hidden";
  3374. this.disableHoriz = new Delayed;
  3375. this.disableVert = new Delayed;
  3376. };
  3377. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3378. bar.style.visibility = "";
  3379. function maybeDisable() {
  3380. // To find out whether the scrollbar is still visible, we
  3381. // check whether the element under the pixel in the bottom
  3382. // right corner of the scrollbar box is the scrollbar box
  3383. // itself (when the bar is still visible) or its filler child
  3384. // (when the bar is hidden). If it is still visible, we keep
  3385. // it enabled, if it's hidden, we disable pointer events.
  3386. var box = bar.getBoundingClientRect();
  3387. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3388. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3389. if (elt != bar) { bar.style.visibility = "hidden"; }
  3390. else { delay.set(1000, maybeDisable); }
  3391. }
  3392. delay.set(1000, maybeDisable);
  3393. };
  3394. NativeScrollbars.prototype.clear = function () {
  3395. var parent = this.horiz.parentNode;
  3396. parent.removeChild(this.horiz);
  3397. parent.removeChild(this.vert);
  3398. };
  3399. var NullScrollbars = function () {};
  3400. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3401. NullScrollbars.prototype.setScrollLeft = function () {};
  3402. NullScrollbars.prototype.setScrollTop = function () {};
  3403. NullScrollbars.prototype.clear = function () {};
  3404. function updateScrollbars(cm, measure) {
  3405. if (!measure) { measure = measureForScrollbars(cm); }
  3406. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3407. updateScrollbarsInner(cm, measure);
  3408. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3409. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3410. { updateHeightsInViewport(cm); }
  3411. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3412. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3413. }
  3414. }
  3415. // Re-synchronize the fake scrollbars with the actual size of the
  3416. // content.
  3417. function updateScrollbarsInner(cm, measure) {
  3418. var d = cm.display;
  3419. var sizes = d.scrollbars.update(measure);
  3420. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3421. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3422. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3423. if (sizes.right && sizes.bottom) {
  3424. d.scrollbarFiller.style.display = "block";
  3425. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3426. d.scrollbarFiller.style.width = sizes.right + "px";
  3427. } else { d.scrollbarFiller.style.display = ""; }
  3428. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3429. d.gutterFiller.style.display = "block";
  3430. d.gutterFiller.style.height = sizes.bottom + "px";
  3431. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3432. } else { d.gutterFiller.style.display = ""; }
  3433. }
  3434. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3435. function initScrollbars(cm) {
  3436. if (cm.display.scrollbars) {
  3437. cm.display.scrollbars.clear();
  3438. if (cm.display.scrollbars.addClass)
  3439. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3440. }
  3441. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3442. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3443. // Prevent clicks in the scrollbars from killing focus
  3444. on(node, "mousedown", function () {
  3445. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3446. });
  3447. node.setAttribute("cm-not-content", "true");
  3448. }, function (pos, axis) {
  3449. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3450. else { updateScrollTop(cm, pos); }
  3451. }, cm);
  3452. if (cm.display.scrollbars.addClass)
  3453. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3454. }
  3455. // Operations are used to wrap a series of changes to the editor
  3456. // state in such a way that each change won't have to update the
  3457. // cursor and display (which would be awkward, slow, and
  3458. // error-prone). Instead, display updates are batched and then all
  3459. // combined and executed at once.
  3460. var nextOpId = 0;
  3461. // Start a new operation.
  3462. function startOperation(cm) {
  3463. cm.curOp = {
  3464. cm: cm,
  3465. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3466. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3467. forceUpdate: false, // Used to force a redraw
  3468. updateInput: 0, // Whether to reset the input textarea
  3469. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3470. changeObjs: null, // Accumulated changes, for firing change events
  3471. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3472. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3473. selectionChanged: false, // Whether the selection needs to be redrawn
  3474. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3475. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3476. scrollToPos: null, // Used to scroll to a specific position
  3477. focus: false,
  3478. id: ++nextOpId, // Unique ID
  3479. markArrays: null // Used by addMarkedSpan
  3480. };
  3481. pushOperation(cm.curOp);
  3482. }
  3483. // Finish an operation, updating the display and signalling delayed events
  3484. function endOperation(cm) {
  3485. var op = cm.curOp;
  3486. if (op) { finishOperation(op, function (group) {
  3487. for (var i = 0; i < group.ops.length; i++)
  3488. { group.ops[i].cm.curOp = null; }
  3489. endOperations(group);
  3490. }); }
  3491. }
  3492. // The DOM updates done when an operation finishes are batched so
  3493. // that the minimum number of relayouts are required.
  3494. function endOperations(group) {
  3495. var ops = group.ops;
  3496. for (var i = 0; i < ops.length; i++) // Read DOM
  3497. { endOperation_R1(ops[i]); }
  3498. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3499. { endOperation_W1(ops[i$1]); }
  3500. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3501. { endOperation_R2(ops[i$2]); }
  3502. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3503. { endOperation_W2(ops[i$3]); }
  3504. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3505. { endOperation_finish(ops[i$4]); }
  3506. }
  3507. function endOperation_R1(op) {
  3508. var cm = op.cm, display = cm.display;
  3509. maybeClipScrollbars(cm);
  3510. if (op.updateMaxLine) { findMaxLine(cm); }
  3511. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3512. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3513. op.scrollToPos.to.line >= display.viewTo) ||
  3514. display.maxLineChanged && cm.options.lineWrapping;
  3515. op.update = op.mustUpdate &&
  3516. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3517. }
  3518. function endOperation_W1(op) {
  3519. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3520. }
  3521. function endOperation_R2(op) {
  3522. var cm = op.cm, display = cm.display;
  3523. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3524. op.barMeasure = measureForScrollbars(cm);
  3525. // If the max line changed since it was last measured, measure it,
  3526. // and ensure the document's width matches it.
  3527. // updateDisplay_W2 will use these properties to do the actual resizing
  3528. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3529. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3530. cm.display.sizerWidth = op.adjustWidthTo;
  3531. op.barMeasure.scrollWidth =
  3532. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3533. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3534. }
  3535. if (op.updatedDisplay || op.selectionChanged)
  3536. { op.preparedSelection = display.input.prepareSelection(); }
  3537. }
  3538. function endOperation_W2(op) {
  3539. var cm = op.cm;
  3540. if (op.adjustWidthTo != null) {
  3541. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3542. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3543. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3544. cm.display.maxLineChanged = false;
  3545. }
  3546. var takeFocus = op.focus && op.focus == activeElt(doc(cm));
  3547. if (op.preparedSelection)
  3548. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3549. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3550. { updateScrollbars(cm, op.barMeasure); }
  3551. if (op.updatedDisplay)
  3552. { setDocumentHeight(cm, op.barMeasure); }
  3553. if (op.selectionChanged) { restartBlink(cm); }
  3554. if (cm.state.focused && op.updateInput)
  3555. { cm.display.input.reset(op.typing); }
  3556. if (takeFocus) { ensureFocus(op.cm); }
  3557. }
  3558. function endOperation_finish(op) {
  3559. var cm = op.cm, display = cm.display, doc = cm.doc;
  3560. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3561. // Abort mouse wheel delta measurement, when scrolling explicitly
  3562. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3563. { display.wheelStartX = display.wheelStartY = null; }
  3564. // Propagate the scroll position to the actual DOM scroller
  3565. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3566. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3567. // If we need to scroll a specific position into view, do so.
  3568. if (op.scrollToPos) {
  3569. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3570. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3571. maybeScrollWindow(cm, rect);
  3572. }
  3573. // Fire events for markers that are hidden/unidden by editing or
  3574. // undoing
  3575. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3576. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3577. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3578. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3579. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3580. if (display.wrapper.offsetHeight)
  3581. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3582. // Fire change events, and delayed event handlers
  3583. if (op.changeObjs)
  3584. { signal(cm, "changes", cm, op.changeObjs); }
  3585. if (op.update)
  3586. { op.update.finish(); }
  3587. }
  3588. // Run the given function in an operation
  3589. function runInOp(cm, f) {
  3590. if (cm.curOp) { return f() }
  3591. startOperation(cm);
  3592. try { return f() }
  3593. finally { endOperation(cm); }
  3594. }
  3595. // Wraps a function in an operation. Returns the wrapped function.
  3596. function operation(cm, f) {
  3597. return function() {
  3598. if (cm.curOp) { return f.apply(cm, arguments) }
  3599. startOperation(cm);
  3600. try { return f.apply(cm, arguments) }
  3601. finally { endOperation(cm); }
  3602. }
  3603. }
  3604. // Used to add methods to editor and doc instances, wrapping them in
  3605. // operations.
  3606. function methodOp(f) {
  3607. return function() {
  3608. if (this.curOp) { return f.apply(this, arguments) }
  3609. startOperation(this);
  3610. try { return f.apply(this, arguments) }
  3611. finally { endOperation(this); }
  3612. }
  3613. }
  3614. function docMethodOp(f) {
  3615. return function() {
  3616. var cm = this.cm;
  3617. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3618. startOperation(cm);
  3619. try { return f.apply(this, arguments) }
  3620. finally { endOperation(cm); }
  3621. }
  3622. }
  3623. // HIGHLIGHT WORKER
  3624. function startWorker(cm, time) {
  3625. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3626. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3627. }
  3628. function highlightWorker(cm) {
  3629. var doc = cm.doc;
  3630. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3631. var end = +new Date + cm.options.workTime;
  3632. var context = getContextBefore(cm, doc.highlightFrontier);
  3633. var changedLines = [];
  3634. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3635. if (context.line >= cm.display.viewFrom) { // Visible
  3636. var oldStyles = line.styles;
  3637. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3638. var highlighted = highlightLine(cm, line, context, true);
  3639. if (resetState) { context.state = resetState; }
  3640. line.styles = highlighted.styles;
  3641. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3642. if (newCls) { line.styleClasses = newCls; }
  3643. else if (oldCls) { line.styleClasses = null; }
  3644. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3645. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3646. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3647. if (ischange) { changedLines.push(context.line); }
  3648. line.stateAfter = context.save();
  3649. context.nextLine();
  3650. } else {
  3651. if (line.text.length <= cm.options.maxHighlightLength)
  3652. { processLine(cm, line.text, context); }
  3653. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3654. context.nextLine();
  3655. }
  3656. if (+new Date > end) {
  3657. startWorker(cm, cm.options.workDelay);
  3658. return true
  3659. }
  3660. });
  3661. doc.highlightFrontier = context.line;
  3662. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3663. if (changedLines.length) { runInOp(cm, function () {
  3664. for (var i = 0; i < changedLines.length; i++)
  3665. { regLineChange(cm, changedLines[i], "text"); }
  3666. }); }
  3667. }
  3668. // DISPLAY DRAWING
  3669. var DisplayUpdate = function(cm, viewport, force) {
  3670. var display = cm.display;
  3671. this.viewport = viewport;
  3672. // Store some values that we'll need later (but don't want to force a relayout for)
  3673. this.visible = visibleLines(display, cm.doc, viewport);
  3674. this.editorIsHidden = !display.wrapper.offsetWidth;
  3675. this.wrapperHeight = display.wrapper.clientHeight;
  3676. this.wrapperWidth = display.wrapper.clientWidth;
  3677. this.oldDisplayWidth = displayWidth(cm);
  3678. this.force = force;
  3679. this.dims = getDimensions(cm);
  3680. this.events = [];
  3681. };
  3682. DisplayUpdate.prototype.signal = function (emitter, type) {
  3683. if (hasHandler(emitter, type))
  3684. { this.events.push(arguments); }
  3685. };
  3686. DisplayUpdate.prototype.finish = function () {
  3687. for (var i = 0; i < this.events.length; i++)
  3688. { signal.apply(null, this.events[i]); }
  3689. };
  3690. function maybeClipScrollbars(cm) {
  3691. var display = cm.display;
  3692. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3693. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3694. display.heightForcer.style.height = scrollGap(cm) + "px";
  3695. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3696. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3697. display.scrollbarsClipped = true;
  3698. }
  3699. }
  3700. function selectionSnapshot(cm) {
  3701. if (cm.hasFocus()) { return null }
  3702. var active = activeElt(doc(cm));
  3703. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3704. var result = {activeElt: active};
  3705. if (window.getSelection) {
  3706. var sel = win(cm).getSelection();
  3707. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3708. result.anchorNode = sel.anchorNode;
  3709. result.anchorOffset = sel.anchorOffset;
  3710. result.focusNode = sel.focusNode;
  3711. result.focusOffset = sel.focusOffset;
  3712. }
  3713. }
  3714. return result
  3715. }
  3716. function restoreSelection(snapshot) {
  3717. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return }
  3718. snapshot.activeElt.focus();
  3719. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3720. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3721. var doc = snapshot.activeElt.ownerDocument;
  3722. var sel = doc.defaultView.getSelection(), range = doc.createRange();
  3723. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3724. range.collapse(false);
  3725. sel.removeAllRanges();
  3726. sel.addRange(range);
  3727. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3728. }
  3729. }
  3730. // Does the actual updating of the line display. Bails out
  3731. // (returning false) when there is nothing to be done and forced is
  3732. // false.
  3733. function updateDisplayIfNeeded(cm, update) {
  3734. var display = cm.display, doc = cm.doc;
  3735. if (update.editorIsHidden) {
  3736. resetView(cm);
  3737. return false
  3738. }
  3739. // Bail out if the visible area is already rendered and nothing changed.
  3740. if (!update.force &&
  3741. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3742. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3743. display.renderedView == display.view && countDirtyView(cm) == 0)
  3744. { return false }
  3745. if (maybeUpdateLineNumberWidth(cm)) {
  3746. resetView(cm);
  3747. update.dims = getDimensions(cm);
  3748. }
  3749. // Compute a suitable new viewport (from & to)
  3750. var end = doc.first + doc.size;
  3751. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3752. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3753. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3754. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3755. if (sawCollapsedSpans) {
  3756. from = visualLineNo(cm.doc, from);
  3757. to = visualLineEndNo(cm.doc, to);
  3758. }
  3759. var different = from != display.viewFrom || to != display.viewTo ||
  3760. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3761. adjustView(cm, from, to);
  3762. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3763. // Position the mover div to align with the current scroll position
  3764. cm.display.mover.style.top = display.viewOffset + "px";
  3765. var toUpdate = countDirtyView(cm);
  3766. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3767. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3768. { return false }
  3769. // For big changes, we hide the enclosing element during the
  3770. // update, since that speeds up the operations on most browsers.
  3771. var selSnapshot = selectionSnapshot(cm);
  3772. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3773. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3774. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3775. display.renderedView = display.view;
  3776. // There might have been a widget with a focused element that got
  3777. // hidden or updated, if so re-focus it.
  3778. restoreSelection(selSnapshot);
  3779. // Prevent selection and cursors from interfering with the scroll
  3780. // width and height.
  3781. removeChildren(display.cursorDiv);
  3782. removeChildren(display.selectionDiv);
  3783. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3784. if (different) {
  3785. display.lastWrapHeight = update.wrapperHeight;
  3786. display.lastWrapWidth = update.wrapperWidth;
  3787. startWorker(cm, 400);
  3788. }
  3789. display.updateLineNumbers = null;
  3790. return true
  3791. }
  3792. function postUpdateDisplay(cm, update) {
  3793. var viewport = update.viewport;
  3794. for (var first = true;; first = false) {
  3795. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3796. // Clip forced viewport to actual scrollable area.
  3797. if (viewport && viewport.top != null)
  3798. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3799. // Updated line heights might result in the drawn area not
  3800. // actually covering the viewport. Keep looping until it does.
  3801. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3802. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3803. { break }
  3804. } else if (first) {
  3805. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3806. }
  3807. if (!updateDisplayIfNeeded(cm, update)) { break }
  3808. updateHeightsInViewport(cm);
  3809. var barMeasure = measureForScrollbars(cm);
  3810. updateSelection(cm);
  3811. updateScrollbars(cm, barMeasure);
  3812. setDocumentHeight(cm, barMeasure);
  3813. update.force = false;
  3814. }
  3815. update.signal(cm, "update", cm);
  3816. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3817. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3818. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3819. }
  3820. }
  3821. function updateDisplaySimple(cm, viewport) {
  3822. var update = new DisplayUpdate(cm, viewport);
  3823. if (updateDisplayIfNeeded(cm, update)) {
  3824. updateHeightsInViewport(cm);
  3825. postUpdateDisplay(cm, update);
  3826. var barMeasure = measureForScrollbars(cm);
  3827. updateSelection(cm);
  3828. updateScrollbars(cm, barMeasure);
  3829. setDocumentHeight(cm, barMeasure);
  3830. update.finish();
  3831. }
  3832. }
  3833. // Sync the actual display DOM structure with display.view, removing
  3834. // nodes for lines that are no longer in view, and creating the ones
  3835. // that are not there yet, and updating the ones that are out of
  3836. // date.
  3837. function patchDisplay(cm, updateNumbersFrom, dims) {
  3838. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3839. var container = display.lineDiv, cur = container.firstChild;
  3840. function rm(node) {
  3841. var next = node.nextSibling;
  3842. // Works around a throw-scroll bug in OS X Webkit
  3843. if (webkit && mac && cm.display.currentWheelTarget == node)
  3844. { node.style.display = "none"; }
  3845. else
  3846. { node.parentNode.removeChild(node); }
  3847. return next
  3848. }
  3849. var view = display.view, lineN = display.viewFrom;
  3850. // Loop over the elements in the view, syncing cur (the DOM nodes
  3851. // in display.lineDiv) with the view as we go.
  3852. for (var i = 0; i < view.length; i++) {
  3853. var lineView = view[i];
  3854. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3855. var node = buildLineElement(cm, lineView, lineN, dims);
  3856. container.insertBefore(node, cur);
  3857. } else { // Already drawn
  3858. while (cur != lineView.node) { cur = rm(cur); }
  3859. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3860. updateNumbersFrom <= lineN && lineView.lineNumber;
  3861. if (lineView.changes) {
  3862. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3863. updateLineForChanges(cm, lineView, lineN, dims);
  3864. }
  3865. if (updateNumber) {
  3866. removeChildren(lineView.lineNumber);
  3867. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3868. }
  3869. cur = lineView.node.nextSibling;
  3870. }
  3871. lineN += lineView.size;
  3872. }
  3873. while (cur) { cur = rm(cur); }
  3874. }
  3875. function updateGutterSpace(display) {
  3876. var width = display.gutters.offsetWidth;
  3877. display.sizer.style.marginLeft = width + "px";
  3878. // Send an event to consumers responding to changes in gutter width.
  3879. signalLater(display, "gutterChanged", display);
  3880. }
  3881. function setDocumentHeight(cm, measure) {
  3882. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3883. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3884. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3885. }
  3886. // Re-align line numbers and gutter marks to compensate for
  3887. // horizontal scrolling.
  3888. function alignHorizontally(cm) {
  3889. var display = cm.display, view = display.view;
  3890. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3891. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3892. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3893. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3894. if (cm.options.fixedGutter) {
  3895. if (view[i].gutter)
  3896. { view[i].gutter.style.left = left; }
  3897. if (view[i].gutterBackground)
  3898. { view[i].gutterBackground.style.left = left; }
  3899. }
  3900. var align = view[i].alignable;
  3901. if (align) { for (var j = 0; j < align.length; j++)
  3902. { align[j].style.left = left; } }
  3903. } }
  3904. if (cm.options.fixedGutter)
  3905. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3906. }
  3907. // Used to ensure that the line number gutter is still the right
  3908. // size for the current document size. Returns true when an update
  3909. // is needed.
  3910. function maybeUpdateLineNumberWidth(cm) {
  3911. if (!cm.options.lineNumbers) { return false }
  3912. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3913. if (last.length != display.lineNumChars) {
  3914. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3915. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3916. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3917. display.lineGutter.style.width = "";
  3918. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3919. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3920. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3921. display.lineGutter.style.width = display.lineNumWidth + "px";
  3922. updateGutterSpace(cm.display);
  3923. return true
  3924. }
  3925. return false
  3926. }
  3927. function getGutters(gutters, lineNumbers) {
  3928. var result = [], sawLineNumbers = false;
  3929. for (var i = 0; i < gutters.length; i++) {
  3930. var name = gutters[i], style = null;
  3931. if (typeof name != "string") { style = name.style; name = name.className; }
  3932. if (name == "CodeMirror-linenumbers") {
  3933. if (!lineNumbers) { continue }
  3934. else { sawLineNumbers = true; }
  3935. }
  3936. result.push({className: name, style: style});
  3937. }
  3938. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3939. return result
  3940. }
  3941. // Rebuild the gutter elements, ensure the margin to the left of the
  3942. // code matches their width.
  3943. function renderGutters(display) {
  3944. var gutters = display.gutters, specs = display.gutterSpecs;
  3945. removeChildren(gutters);
  3946. display.lineGutter = null;
  3947. for (var i = 0; i < specs.length; ++i) {
  3948. var ref = specs[i];
  3949. var className = ref.className;
  3950. var style = ref.style;
  3951. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3952. if (style) { gElt.style.cssText = style; }
  3953. if (className == "CodeMirror-linenumbers") {
  3954. display.lineGutter = gElt;
  3955. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3956. }
  3957. }
  3958. gutters.style.display = specs.length ? "" : "none";
  3959. updateGutterSpace(display);
  3960. }
  3961. function updateGutters(cm) {
  3962. renderGutters(cm.display);
  3963. regChange(cm);
  3964. alignHorizontally(cm);
  3965. }
  3966. // The display handles the DOM integration, both for input reading
  3967. // and content drawing. It holds references to DOM nodes and
  3968. // display-related state.
  3969. function Display(place, doc, input, options) {
  3970. var d = this;
  3971. this.input = input;
  3972. // Covers bottom-right square when both scrollbars are present.
  3973. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3974. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3975. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3976. // and h scrollbar is present.
  3977. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3978. d.gutterFiller.setAttribute("cm-not-content", "true");
  3979. // Will contain the actual code, positioned to cover the viewport.
  3980. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3981. // Elements are added to these to represent selection and cursors.
  3982. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3983. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3984. // A visibility: hidden element used to find the size of things.
  3985. d.measure = elt("div", null, "CodeMirror-measure");
  3986. // When lines outside of the viewport are measured, they are drawn in this.
  3987. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3988. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3989. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3990. null, "position: relative; outline: none");
  3991. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3992. // Moved around its parent to cover visible view.
  3993. d.mover = elt("div", [lines], null, "position: relative");
  3994. // Set to the height of the document, allowing scrolling.
  3995. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3996. d.sizerWidth = null;
  3997. // Behavior of elts with overflow: auto and padding is
  3998. // inconsistent across browsers. This is used to ensure the
  3999. // scrollable area is big enough.
  4000. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  4001. // Will contain the gutters, if any.
  4002. d.gutters = elt("div", null, "CodeMirror-gutters");
  4003. d.lineGutter = null;
  4004. // Actual scrollable element.
  4005. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4006. d.scroller.setAttribute("tabIndex", "-1");
  4007. // The element in which the editor lives.
  4008. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4009. // See #6982. FIXME remove when this has been fixed for a while in Chrome
  4010. if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; }
  4011. // This attribute is respected by automatic translation systems such as Google Translate,
  4012. // and may also be respected by tools used by human translators.
  4013. d.wrapper.setAttribute('translate', 'no');
  4014. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4015. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4016. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4017. if (place) {
  4018. if (place.appendChild) { place.appendChild(d.wrapper); }
  4019. else { place(d.wrapper); }
  4020. }
  4021. // Current rendered range (may be bigger than the view window).
  4022. d.viewFrom = d.viewTo = doc.first;
  4023. d.reportedViewFrom = d.reportedViewTo = doc.first;
  4024. // Information about the rendered lines.
  4025. d.view = [];
  4026. d.renderedView = null;
  4027. // Holds info about a single rendered line when it was rendered
  4028. // for measurement, while not in view.
  4029. d.externalMeasured = null;
  4030. // Empty space (in pixels) above the view
  4031. d.viewOffset = 0;
  4032. d.lastWrapHeight = d.lastWrapWidth = 0;
  4033. d.updateLineNumbers = null;
  4034. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4035. d.scrollbarsClipped = false;
  4036. // Used to only resize the line number gutter when necessary (when
  4037. // the amount of lines crosses a boundary that makes its width change)
  4038. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4039. // Set to true when a non-horizontal-scrolling line widget is
  4040. // added. As an optimization, line widget aligning is skipped when
  4041. // this is false.
  4042. d.alignWidgets = false;
  4043. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4044. // Tracks the maximum line length so that the horizontal scrollbar
  4045. // can be kept static when scrolling.
  4046. d.maxLine = null;
  4047. d.maxLineLength = 0;
  4048. d.maxLineChanged = false;
  4049. // Used for measuring wheel scrolling granularity
  4050. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4051. // True when shift is held down.
  4052. d.shift = false;
  4053. // Used to track whether anything happened since the context menu
  4054. // was opened.
  4055. d.selForContextMenu = null;
  4056. d.activeTouch = null;
  4057. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4058. renderGutters(d);
  4059. input.init(d);
  4060. }
  4061. // Since the delta values reported on mouse wheel events are
  4062. // unstandardized between browsers and even browser versions, and
  4063. // generally horribly unpredictable, this code starts by measuring
  4064. // the scroll effect that the first few mouse wheel events have,
  4065. // and, from that, detects the way it can convert deltas to pixel
  4066. // offsets afterwards.
  4067. //
  4068. // The reason we want to know the amount a wheel event will scroll
  4069. // is that it gives us a chance to update the display before the
  4070. // actual scrolling happens, reducing flickering.
  4071. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4072. // Fill in a browser-detected starting value on browsers where we
  4073. // know one. These don't have to be accurate -- the result of them
  4074. // being wrong would just be a slight flicker on the first wheel
  4075. // scroll (if it is large enough).
  4076. if (ie) { wheelPixelsPerUnit = -.53; }
  4077. else if (gecko) { wheelPixelsPerUnit = 15; }
  4078. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4079. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4080. function wheelEventDelta(e) {
  4081. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4082. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4083. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4084. else if (dy == null) { dy = e.wheelDelta; }
  4085. return {x: dx, y: dy}
  4086. }
  4087. function wheelEventPixels(e) {
  4088. var delta = wheelEventDelta(e);
  4089. delta.x *= wheelPixelsPerUnit;
  4090. delta.y *= wheelPixelsPerUnit;
  4091. return delta
  4092. }
  4093. function onScrollWheel(cm, e) {
  4094. // On Chrome 102, viewport updates somehow stop wheel-based
  4095. // scrolling. Turning off pointer events during the scroll seems
  4096. // to avoid the issue.
  4097. if (chrome && chrome_version == 102) {
  4098. if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
  4099. else { clearTimeout(cm.display.chromeScrollHack); }
  4100. cm.display.chromeScrollHack = setTimeout(function () {
  4101. cm.display.chromeScrollHack = null;
  4102. cm.display.sizer.style.pointerEvents = "";
  4103. }, 100);
  4104. }
  4105. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4106. var pixelsPerUnit = wheelPixelsPerUnit;
  4107. if (e.deltaMode === 0) {
  4108. dx = e.deltaX;
  4109. dy = e.deltaY;
  4110. pixelsPerUnit = 1;
  4111. }
  4112. var display = cm.display, scroll = display.scroller;
  4113. // Quit if there's nothing to scroll here
  4114. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4115. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4116. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4117. // Webkit browsers on OS X abort momentum scrolls when the target
  4118. // of the scroll event is removed from the scrollable element.
  4119. // This hack (see related code in patchDisplay) makes sure the
  4120. // element is kept around.
  4121. if (dy && mac && webkit) {
  4122. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4123. for (var i = 0; i < view.length; i++) {
  4124. if (view[i].node == cur) {
  4125. cm.display.currentWheelTarget = cur;
  4126. break outer
  4127. }
  4128. }
  4129. }
  4130. }
  4131. // On some browsers, horizontal scrolling will cause redraws to
  4132. // happen before the gutter has been realigned, causing it to
  4133. // wriggle around in a most unseemly way. When we have an
  4134. // estimated pixels/delta value, we just handle horizontal
  4135. // scrolling entirely here. It'll be slightly off from native, but
  4136. // better than glitching out.
  4137. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  4138. if (dy && canScrollY)
  4139. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  4140. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  4141. // Only prevent default scrolling if vertical scrolling is
  4142. // actually possible. Otherwise, it causes vertical scroll
  4143. // jitter on OSX trackpads when deltaX is small and deltaY
  4144. // is large (issue #3579)
  4145. if (!dy || (dy && canScrollY))
  4146. { e_preventDefault(e); }
  4147. display.wheelStartX = null; // Abort measurement, if in progress
  4148. return
  4149. }
  4150. // 'Project' the visible viewport to cover the area that is being
  4151. // scrolled into view (if we know enough to estimate it).
  4152. if (dy && pixelsPerUnit != null) {
  4153. var pixels = dy * pixelsPerUnit;
  4154. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4155. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4156. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4157. updateDisplaySimple(cm, {top: top, bottom: bot});
  4158. }
  4159. if (wheelSamples < 20 && e.deltaMode !== 0) {
  4160. if (display.wheelStartX == null) {
  4161. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4162. display.wheelDX = dx; display.wheelDY = dy;
  4163. setTimeout(function () {
  4164. if (display.wheelStartX == null) { return }
  4165. var movedX = scroll.scrollLeft - display.wheelStartX;
  4166. var movedY = scroll.scrollTop - display.wheelStartY;
  4167. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4168. (movedX && display.wheelDX && movedX / display.wheelDX);
  4169. display.wheelStartX = display.wheelStartY = null;
  4170. if (!sample) { return }
  4171. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4172. ++wheelSamples;
  4173. }, 200);
  4174. } else {
  4175. display.wheelDX += dx; display.wheelDY += dy;
  4176. }
  4177. }
  4178. }
  4179. // Selection objects are immutable. A new one is created every time
  4180. // the selection changes. A selection is one or more non-overlapping
  4181. // (and non-touching) ranges, sorted, and an integer that indicates
  4182. // which one is the primary selection (the one that's scrolled into
  4183. // view, that getCursor returns, etc).
  4184. var Selection = function(ranges, primIndex) {
  4185. this.ranges = ranges;
  4186. this.primIndex = primIndex;
  4187. };
  4188. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4189. Selection.prototype.equals = function (other) {
  4190. if (other == this) { return true }
  4191. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4192. for (var i = 0; i < this.ranges.length; i++) {
  4193. var here = this.ranges[i], there = other.ranges[i];
  4194. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4195. }
  4196. return true
  4197. };
  4198. Selection.prototype.deepCopy = function () {
  4199. var out = [];
  4200. for (var i = 0; i < this.ranges.length; i++)
  4201. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4202. return new Selection(out, this.primIndex)
  4203. };
  4204. Selection.prototype.somethingSelected = function () {
  4205. for (var i = 0; i < this.ranges.length; i++)
  4206. { if (!this.ranges[i].empty()) { return true } }
  4207. return false
  4208. };
  4209. Selection.prototype.contains = function (pos, end) {
  4210. if (!end) { end = pos; }
  4211. for (var i = 0; i < this.ranges.length; i++) {
  4212. var range = this.ranges[i];
  4213. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4214. { return i }
  4215. }
  4216. return -1
  4217. };
  4218. var Range = function(anchor, head) {
  4219. this.anchor = anchor; this.head = head;
  4220. };
  4221. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4222. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4223. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4224. // Take an unsorted, potentially overlapping set of ranges, and
  4225. // build a selection out of it. 'Consumes' ranges array (modifying
  4226. // it).
  4227. function normalizeSelection(cm, ranges, primIndex) {
  4228. var mayTouch = cm && cm.options.selectionsMayTouch;
  4229. var prim = ranges[primIndex];
  4230. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4231. primIndex = indexOf(ranges, prim);
  4232. for (var i = 1; i < ranges.length; i++) {
  4233. var cur = ranges[i], prev = ranges[i - 1];
  4234. var diff = cmp(prev.to(), cur.from());
  4235. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4236. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4237. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4238. if (i <= primIndex) { --primIndex; }
  4239. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4240. }
  4241. }
  4242. return new Selection(ranges, primIndex)
  4243. }
  4244. function simpleSelection(anchor, head) {
  4245. return new Selection([new Range(anchor, head || anchor)], 0)
  4246. }
  4247. // Compute the position of the end of a change (its 'to' property
  4248. // refers to the pre-change end).
  4249. function changeEnd(change) {
  4250. if (!change.text) { return change.to }
  4251. return Pos(change.from.line + change.text.length - 1,
  4252. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4253. }
  4254. // Adjust a position to refer to the post-change position of the
  4255. // same text, or the end of the change if the change covers it.
  4256. function adjustForChange(pos, change) {
  4257. if (cmp(pos, change.from) < 0) { return pos }
  4258. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4259. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4260. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4261. return Pos(line, ch)
  4262. }
  4263. function computeSelAfterChange(doc, change) {
  4264. var out = [];
  4265. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4266. var range = doc.sel.ranges[i];
  4267. out.push(new Range(adjustForChange(range.anchor, change),
  4268. adjustForChange(range.head, change)));
  4269. }
  4270. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4271. }
  4272. function offsetPos(pos, old, nw) {
  4273. if (pos.line == old.line)
  4274. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4275. else
  4276. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4277. }
  4278. // Used by replaceSelections to allow moving the selection to the
  4279. // start or around the replaced test. Hint may be "start" or "around".
  4280. function computeReplacedSel(doc, changes, hint) {
  4281. var out = [];
  4282. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4283. for (var i = 0; i < changes.length; i++) {
  4284. var change = changes[i];
  4285. var from = offsetPos(change.from, oldPrev, newPrev);
  4286. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4287. oldPrev = change.to;
  4288. newPrev = to;
  4289. if (hint == "around") {
  4290. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4291. out[i] = new Range(inv ? to : from, inv ? from : to);
  4292. } else {
  4293. out[i] = new Range(from, from);
  4294. }
  4295. }
  4296. return new Selection(out, doc.sel.primIndex)
  4297. }
  4298. // Used to get the editor into a consistent state again when options change.
  4299. function loadMode(cm) {
  4300. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4301. resetModeState(cm);
  4302. }
  4303. function resetModeState(cm) {
  4304. cm.doc.iter(function (line) {
  4305. if (line.stateAfter) { line.stateAfter = null; }
  4306. if (line.styles) { line.styles = null; }
  4307. });
  4308. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4309. startWorker(cm, 100);
  4310. cm.state.modeGen++;
  4311. if (cm.curOp) { regChange(cm); }
  4312. }
  4313. // DOCUMENT DATA STRUCTURE
  4314. // By default, updates that start and end at the beginning of a line
  4315. // are treated specially, in order to make the association of line
  4316. // widgets and marker elements with the text behave more intuitive.
  4317. function isWholeLineUpdate(doc, change) {
  4318. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4319. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4320. }
  4321. // Perform a change on the document data structure.
  4322. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4323. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4324. function update(line, text, spans) {
  4325. updateLine(line, text, spans, estimateHeight);
  4326. signalLater(line, "change", line, change);
  4327. }
  4328. function linesFor(start, end) {
  4329. var result = [];
  4330. for (var i = start; i < end; ++i)
  4331. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4332. return result
  4333. }
  4334. var from = change.from, to = change.to, text = change.text;
  4335. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4336. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4337. // Adjust the line structure
  4338. if (change.full) {
  4339. doc.insert(0, linesFor(0, text.length));
  4340. doc.remove(text.length, doc.size - text.length);
  4341. } else if (isWholeLineUpdate(doc, change)) {
  4342. // This is a whole-line replace. Treated specially to make
  4343. // sure line objects move the way they are supposed to.
  4344. var added = linesFor(0, text.length - 1);
  4345. update(lastLine, lastLine.text, lastSpans);
  4346. if (nlines) { doc.remove(from.line, nlines); }
  4347. if (added.length) { doc.insert(from.line, added); }
  4348. } else if (firstLine == lastLine) {
  4349. if (text.length == 1) {
  4350. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4351. } else {
  4352. var added$1 = linesFor(1, text.length - 1);
  4353. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4354. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4355. doc.insert(from.line + 1, added$1);
  4356. }
  4357. } else if (text.length == 1) {
  4358. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4359. doc.remove(from.line + 1, nlines);
  4360. } else {
  4361. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4362. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4363. var added$2 = linesFor(1, text.length - 1);
  4364. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4365. doc.insert(from.line + 1, added$2);
  4366. }
  4367. signalLater(doc, "change", doc, change);
  4368. }
  4369. // Call f for all linked documents.
  4370. function linkedDocs(doc, f, sharedHistOnly) {
  4371. function propagate(doc, skip, sharedHist) {
  4372. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4373. var rel = doc.linked[i];
  4374. if (rel.doc == skip) { continue }
  4375. var shared = sharedHist && rel.sharedHist;
  4376. if (sharedHistOnly && !shared) { continue }
  4377. f(rel.doc, shared);
  4378. propagate(rel.doc, doc, shared);
  4379. } }
  4380. }
  4381. propagate(doc, null, true);
  4382. }
  4383. // Attach a document to an editor.
  4384. function attachDoc(cm, doc) {
  4385. if (doc.cm) { throw new Error("This document is already in use.") }
  4386. cm.doc = doc;
  4387. doc.cm = cm;
  4388. estimateLineHeights(cm);
  4389. loadMode(cm);
  4390. setDirectionClass(cm);
  4391. cm.options.direction = doc.direction;
  4392. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4393. cm.options.mode = doc.modeOption;
  4394. regChange(cm);
  4395. }
  4396. function setDirectionClass(cm) {
  4397. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4398. }
  4399. function directionChanged(cm) {
  4400. runInOp(cm, function () {
  4401. setDirectionClass(cm);
  4402. regChange(cm);
  4403. });
  4404. }
  4405. function History(prev) {
  4406. // Arrays of change events and selections. Doing something adds an
  4407. // event to done and clears undo. Undoing moves events from done
  4408. // to undone, redoing moves them in the other direction.
  4409. this.done = []; this.undone = [];
  4410. this.undoDepth = prev ? prev.undoDepth : Infinity;
  4411. // Used to track when changes can be merged into a single undo
  4412. // event
  4413. this.lastModTime = this.lastSelTime = 0;
  4414. this.lastOp = this.lastSelOp = null;
  4415. this.lastOrigin = this.lastSelOrigin = null;
  4416. // Used by the isClean() method
  4417. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4418. }
  4419. // Create a history change event from an updateDoc-style change
  4420. // object.
  4421. function historyChangeFromChange(doc, change) {
  4422. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4423. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4424. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4425. return histChange
  4426. }
  4427. // Pop all selection events off the end of a history array. Stop at
  4428. // a change event.
  4429. function clearSelectionEvents(array) {
  4430. while (array.length) {
  4431. var last = lst(array);
  4432. if (last.ranges) { array.pop(); }
  4433. else { break }
  4434. }
  4435. }
  4436. // Find the top change event in the history. Pop off selection
  4437. // events that are in the way.
  4438. function lastChangeEvent(hist, force) {
  4439. if (force) {
  4440. clearSelectionEvents(hist.done);
  4441. return lst(hist.done)
  4442. } else if (hist.done.length && !lst(hist.done).ranges) {
  4443. return lst(hist.done)
  4444. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4445. hist.done.pop();
  4446. return lst(hist.done)
  4447. }
  4448. }
  4449. // Register a change in the history. Merges changes that are within
  4450. // a single operation, or are close together with an origin that
  4451. // allows merging (starting with "+") into a single event.
  4452. function addChangeToHistory(doc, change, selAfter, opId) {
  4453. var hist = doc.history;
  4454. hist.undone.length = 0;
  4455. var time = +new Date, cur;
  4456. var last;
  4457. if ((hist.lastOp == opId ||
  4458. hist.lastOrigin == change.origin && change.origin &&
  4459. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4460. change.origin.charAt(0) == "*")) &&
  4461. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4462. // Merge this change into the last event
  4463. last = lst(cur.changes);
  4464. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4465. // Optimized case for simple insertion -- don't want to add
  4466. // new changesets for every character typed
  4467. last.to = changeEnd(change);
  4468. } else {
  4469. // Add new sub-event
  4470. cur.changes.push(historyChangeFromChange(doc, change));
  4471. }
  4472. } else {
  4473. // Can not be merged, start a new event.
  4474. var before = lst(hist.done);
  4475. if (!before || !before.ranges)
  4476. { pushSelectionToHistory(doc.sel, hist.done); }
  4477. cur = {changes: [historyChangeFromChange(doc, change)],
  4478. generation: hist.generation};
  4479. hist.done.push(cur);
  4480. while (hist.done.length > hist.undoDepth) {
  4481. hist.done.shift();
  4482. if (!hist.done[0].ranges) { hist.done.shift(); }
  4483. }
  4484. }
  4485. hist.done.push(selAfter);
  4486. hist.generation = ++hist.maxGeneration;
  4487. hist.lastModTime = hist.lastSelTime = time;
  4488. hist.lastOp = hist.lastSelOp = opId;
  4489. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4490. if (!last) { signal(doc, "historyAdded"); }
  4491. }
  4492. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4493. var ch = origin.charAt(0);
  4494. return ch == "*" ||
  4495. ch == "+" &&
  4496. prev.ranges.length == sel.ranges.length &&
  4497. prev.somethingSelected() == sel.somethingSelected() &&
  4498. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4499. }
  4500. // Called whenever the selection changes, sets the new selection as
  4501. // the pending selection in the history, and pushes the old pending
  4502. // selection into the 'done' array when it was significantly
  4503. // different (in number of selected ranges, emptiness, or time).
  4504. function addSelectionToHistory(doc, sel, opId, options) {
  4505. var hist = doc.history, origin = options && options.origin;
  4506. // A new event is started when the previous origin does not match
  4507. // the current, or the origins don't allow matching. Origins
  4508. // starting with * are always merged, those starting with + are
  4509. // merged when similar and close together in time.
  4510. if (opId == hist.lastSelOp ||
  4511. (origin && hist.lastSelOrigin == origin &&
  4512. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4513. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4514. { hist.done[hist.done.length - 1] = sel; }
  4515. else
  4516. { pushSelectionToHistory(sel, hist.done); }
  4517. hist.lastSelTime = +new Date;
  4518. hist.lastSelOrigin = origin;
  4519. hist.lastSelOp = opId;
  4520. if (options && options.clearRedo !== false)
  4521. { clearSelectionEvents(hist.undone); }
  4522. }
  4523. function pushSelectionToHistory(sel, dest) {
  4524. var top = lst(dest);
  4525. if (!(top && top.ranges && top.equals(sel)))
  4526. { dest.push(sel); }
  4527. }
  4528. // Used to store marked span information in the history.
  4529. function attachLocalSpans(doc, change, from, to) {
  4530. var existing = change["spans_" + doc.id], n = 0;
  4531. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4532. if (line.markedSpans)
  4533. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4534. ++n;
  4535. });
  4536. }
  4537. // When un/re-doing restores text containing marked spans, those
  4538. // that have been explicitly cleared should not be restored.
  4539. function removeClearedSpans(spans) {
  4540. if (!spans) { return null }
  4541. var out;
  4542. for (var i = 0; i < spans.length; ++i) {
  4543. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4544. else if (out) { out.push(spans[i]); }
  4545. }
  4546. return !out ? spans : out.length ? out : null
  4547. }
  4548. // Retrieve and filter the old marked spans stored in a change event.
  4549. function getOldSpans(doc, change) {
  4550. var found = change["spans_" + doc.id];
  4551. if (!found) { return null }
  4552. var nw = [];
  4553. for (var i = 0; i < change.text.length; ++i)
  4554. { nw.push(removeClearedSpans(found[i])); }
  4555. return nw
  4556. }
  4557. // Used for un/re-doing changes from the history. Combines the
  4558. // result of computing the existing spans with the set of spans that
  4559. // existed in the history (so that deleting around a span and then
  4560. // undoing brings back the span).
  4561. function mergeOldSpans(doc, change) {
  4562. var old = getOldSpans(doc, change);
  4563. var stretched = stretchSpansOverChange(doc, change);
  4564. if (!old) { return stretched }
  4565. if (!stretched) { return old }
  4566. for (var i = 0; i < old.length; ++i) {
  4567. var oldCur = old[i], stretchCur = stretched[i];
  4568. if (oldCur && stretchCur) {
  4569. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4570. var span = stretchCur[j];
  4571. for (var k = 0; k < oldCur.length; ++k)
  4572. { if (oldCur[k].marker == span.marker) { continue spans } }
  4573. oldCur.push(span);
  4574. }
  4575. } else if (stretchCur) {
  4576. old[i] = stretchCur;
  4577. }
  4578. }
  4579. return old
  4580. }
  4581. // Used both to provide a JSON-safe object in .getHistory, and, when
  4582. // detaching a document, to split the history in two
  4583. function copyHistoryArray(events, newGroup, instantiateSel) {
  4584. var copy = [];
  4585. for (var i = 0; i < events.length; ++i) {
  4586. var event = events[i];
  4587. if (event.ranges) {
  4588. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4589. continue
  4590. }
  4591. var changes = event.changes, newChanges = [];
  4592. copy.push({changes: newChanges});
  4593. for (var j = 0; j < changes.length; ++j) {
  4594. var change = changes[j], m = (void 0);
  4595. newChanges.push({from: change.from, to: change.to, text: change.text});
  4596. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4597. if (indexOf(newGroup, Number(m[1])) > -1) {
  4598. lst(newChanges)[prop] = change[prop];
  4599. delete change[prop];
  4600. }
  4601. } } }
  4602. }
  4603. }
  4604. return copy
  4605. }
  4606. // The 'scroll' parameter given to many of these indicated whether
  4607. // the new cursor position should be scrolled into view after
  4608. // modifying the selection.
  4609. // If shift is held or the extend flag is set, extends a range to
  4610. // include a given position (and optionally a second position).
  4611. // Otherwise, simply returns the range between the given positions.
  4612. // Used for cursor motion and such.
  4613. function extendRange(range, head, other, extend) {
  4614. if (extend) {
  4615. var anchor = range.anchor;
  4616. if (other) {
  4617. var posBefore = cmp(head, anchor) < 0;
  4618. if (posBefore != (cmp(other, anchor) < 0)) {
  4619. anchor = head;
  4620. head = other;
  4621. } else if (posBefore != (cmp(head, other) < 0)) {
  4622. head = other;
  4623. }
  4624. }
  4625. return new Range(anchor, head)
  4626. } else {
  4627. return new Range(other || head, head)
  4628. }
  4629. }
  4630. // Extend the primary selection range, discard the rest.
  4631. function extendSelection(doc, head, other, options, extend) {
  4632. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4633. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4634. }
  4635. // Extend all selections (pos is an array of selections with length
  4636. // equal the number of selections)
  4637. function extendSelections(doc, heads, options) {
  4638. var out = [];
  4639. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4640. for (var i = 0; i < doc.sel.ranges.length; i++)
  4641. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4642. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4643. setSelection(doc, newSel, options);
  4644. }
  4645. // Updates a single range in the selection.
  4646. function replaceOneSelection(doc, i, range, options) {
  4647. var ranges = doc.sel.ranges.slice(0);
  4648. ranges[i] = range;
  4649. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4650. }
  4651. // Reset the selection to a single range.
  4652. function setSimpleSelection(doc, anchor, head, options) {
  4653. setSelection(doc, simpleSelection(anchor, head), options);
  4654. }
  4655. // Give beforeSelectionChange handlers a change to influence a
  4656. // selection update.
  4657. function filterSelectionChange(doc, sel, options) {
  4658. var obj = {
  4659. ranges: sel.ranges,
  4660. update: function(ranges) {
  4661. this.ranges = [];
  4662. for (var i = 0; i < ranges.length; i++)
  4663. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4664. clipPos(doc, ranges[i].head)); }
  4665. },
  4666. origin: options && options.origin
  4667. };
  4668. signal(doc, "beforeSelectionChange", doc, obj);
  4669. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4670. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4671. else { return sel }
  4672. }
  4673. function setSelectionReplaceHistory(doc, sel, options) {
  4674. var done = doc.history.done, last = lst(done);
  4675. if (last && last.ranges) {
  4676. done[done.length - 1] = sel;
  4677. setSelectionNoUndo(doc, sel, options);
  4678. } else {
  4679. setSelection(doc, sel, options);
  4680. }
  4681. }
  4682. // Set a new selection.
  4683. function setSelection(doc, sel, options) {
  4684. setSelectionNoUndo(doc, sel, options);
  4685. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4686. }
  4687. function setSelectionNoUndo(doc, sel, options) {
  4688. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4689. { sel = filterSelectionChange(doc, sel, options); }
  4690. var bias = options && options.bias ||
  4691. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4692. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4693. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  4694. { ensureCursorVisible(doc.cm); }
  4695. }
  4696. function setSelectionInner(doc, sel) {
  4697. if (sel.equals(doc.sel)) { return }
  4698. doc.sel = sel;
  4699. if (doc.cm) {
  4700. doc.cm.curOp.updateInput = 1;
  4701. doc.cm.curOp.selectionChanged = true;
  4702. signalCursorActivity(doc.cm);
  4703. }
  4704. signalLater(doc, "cursorActivity", doc);
  4705. }
  4706. // Verify that the selection does not partially select any atomic
  4707. // marked ranges.
  4708. function reCheckSelection(doc) {
  4709. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4710. }
  4711. // Return a selection that does not partially select any atomic
  4712. // ranges.
  4713. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4714. var out;
  4715. for (var i = 0; i < sel.ranges.length; i++) {
  4716. var range = sel.ranges[i];
  4717. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4718. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4719. var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4720. if (out || newAnchor != range.anchor || newHead != range.head) {
  4721. if (!out) { out = sel.ranges.slice(0, i); }
  4722. out[i] = new Range(newAnchor, newHead);
  4723. }
  4724. }
  4725. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4726. }
  4727. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4728. var line = getLine(doc, pos.line);
  4729. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4730. var sp = line.markedSpans[i], m = sp.marker;
  4731. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4732. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4733. // is with selectLeft/Right
  4734. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4735. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4736. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4737. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4738. if (mayClear) {
  4739. signal(m, "beforeCursorEnter");
  4740. if (m.explicitlyCleared) {
  4741. if (!line.markedSpans) { break }
  4742. else {--i; continue}
  4743. }
  4744. }
  4745. if (!m.atomic) { continue }
  4746. if (oldPos) {
  4747. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4748. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4749. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4750. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4751. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4752. }
  4753. var far = m.find(dir < 0 ? -1 : 1);
  4754. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4755. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4756. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4757. }
  4758. } }
  4759. return pos
  4760. }
  4761. // Ensure a given position is not inside an atomic range.
  4762. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4763. var dir = bias || 1;
  4764. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4765. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4766. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4767. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4768. if (!found) {
  4769. doc.cantEdit = true;
  4770. return Pos(doc.first, 0)
  4771. }
  4772. return found
  4773. }
  4774. function movePos(doc, pos, dir, line) {
  4775. if (dir < 0 && pos.ch == 0) {
  4776. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4777. else { return null }
  4778. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4779. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4780. else { return null }
  4781. } else {
  4782. return new Pos(pos.line, pos.ch + dir)
  4783. }
  4784. }
  4785. function selectAll(cm) {
  4786. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4787. }
  4788. // UPDATING
  4789. // Allow "beforeChange" event handlers to influence a change
  4790. function filterChange(doc, change, update) {
  4791. var obj = {
  4792. canceled: false,
  4793. from: change.from,
  4794. to: change.to,
  4795. text: change.text,
  4796. origin: change.origin,
  4797. cancel: function () { return obj.canceled = true; }
  4798. };
  4799. if (update) { obj.update = function (from, to, text, origin) {
  4800. if (from) { obj.from = clipPos(doc, from); }
  4801. if (to) { obj.to = clipPos(doc, to); }
  4802. if (text) { obj.text = text; }
  4803. if (origin !== undefined) { obj.origin = origin; }
  4804. }; }
  4805. signal(doc, "beforeChange", doc, obj);
  4806. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4807. if (obj.canceled) {
  4808. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4809. return null
  4810. }
  4811. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4812. }
  4813. // Apply a change to a document, and add it to the document's
  4814. // history, and propagating it to all linked documents.
  4815. function makeChange(doc, change, ignoreReadOnly) {
  4816. if (doc.cm) {
  4817. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4818. if (doc.cm.state.suppressEdits) { return }
  4819. }
  4820. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4821. change = filterChange(doc, change, true);
  4822. if (!change) { return }
  4823. }
  4824. // Possibly split or suppress the update based on the presence
  4825. // of read-only spans in its range.
  4826. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4827. if (split) {
  4828. for (var i = split.length - 1; i >= 0; --i)
  4829. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4830. } else {
  4831. makeChangeInner(doc, change);
  4832. }
  4833. }
  4834. function makeChangeInner(doc, change) {
  4835. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4836. var selAfter = computeSelAfterChange(doc, change);
  4837. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4838. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4839. var rebased = [];
  4840. linkedDocs(doc, function (doc, sharedHist) {
  4841. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4842. rebaseHist(doc.history, change);
  4843. rebased.push(doc.history);
  4844. }
  4845. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4846. });
  4847. }
  4848. // Revert a change stored in a document's history.
  4849. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4850. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4851. if (suppress && !allowSelectionOnly) { return }
  4852. var hist = doc.history, event, selAfter = doc.sel;
  4853. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4854. // Verify that there is a useable event (so that ctrl-z won't
  4855. // needlessly clear selection events)
  4856. var i = 0;
  4857. for (; i < source.length; i++) {
  4858. event = source[i];
  4859. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4860. { break }
  4861. }
  4862. if (i == source.length) { return }
  4863. hist.lastOrigin = hist.lastSelOrigin = null;
  4864. for (;;) {
  4865. event = source.pop();
  4866. if (event.ranges) {
  4867. pushSelectionToHistory(event, dest);
  4868. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4869. setSelection(doc, event, {clearRedo: false});
  4870. return
  4871. }
  4872. selAfter = event;
  4873. } else if (suppress) {
  4874. source.push(event);
  4875. return
  4876. } else { break }
  4877. }
  4878. // Build up a reverse change object to add to the opposite history
  4879. // stack (redo when undoing, and vice versa).
  4880. var antiChanges = [];
  4881. pushSelectionToHistory(selAfter, dest);
  4882. dest.push({changes: antiChanges, generation: hist.generation});
  4883. hist.generation = event.generation || ++hist.maxGeneration;
  4884. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4885. var loop = function ( i ) {
  4886. var change = event.changes[i];
  4887. change.origin = type;
  4888. if (filter && !filterChange(doc, change, false)) {
  4889. source.length = 0;
  4890. return {}
  4891. }
  4892. antiChanges.push(historyChangeFromChange(doc, change));
  4893. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4894. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4895. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4896. var rebased = [];
  4897. // Propagate to the linked documents
  4898. linkedDocs(doc, function (doc, sharedHist) {
  4899. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4900. rebaseHist(doc.history, change);
  4901. rebased.push(doc.history);
  4902. }
  4903. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4904. });
  4905. };
  4906. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4907. var returned = loop( i$1 );
  4908. if ( returned ) return returned.v;
  4909. }
  4910. }
  4911. // Sub-views need their line numbers shifted when text is added
  4912. // above or below them in the parent document.
  4913. function shiftDoc(doc, distance) {
  4914. if (distance == 0) { return }
  4915. doc.first += distance;
  4916. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4917. Pos(range.anchor.line + distance, range.anchor.ch),
  4918. Pos(range.head.line + distance, range.head.ch)
  4919. ); }), doc.sel.primIndex);
  4920. if (doc.cm) {
  4921. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4922. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4923. { regLineChange(doc.cm, l, "gutter"); }
  4924. }
  4925. }
  4926. // More lower-level change function, handling only a single document
  4927. // (not linked ones).
  4928. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4929. if (doc.cm && !doc.cm.curOp)
  4930. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4931. if (change.to.line < doc.first) {
  4932. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4933. return
  4934. }
  4935. if (change.from.line > doc.lastLine()) { return }
  4936. // Clip the change to the size of this doc
  4937. if (change.from.line < doc.first) {
  4938. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4939. shiftDoc(doc, shift);
  4940. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4941. text: [lst(change.text)], origin: change.origin};
  4942. }
  4943. var last = doc.lastLine();
  4944. if (change.to.line > last) {
  4945. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4946. text: [change.text[0]], origin: change.origin};
  4947. }
  4948. change.removed = getBetween(doc, change.from, change.to);
  4949. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4950. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4951. else { updateDoc(doc, change, spans); }
  4952. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4953. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4954. { doc.cantEdit = false; }
  4955. }
  4956. // Handle the interaction of a change to a document with the editor
  4957. // that this document is part of.
  4958. function makeChangeSingleDocInEditor(cm, change, spans) {
  4959. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4960. var recomputeMaxLength = false, checkWidthStart = from.line;
  4961. if (!cm.options.lineWrapping) {
  4962. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4963. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4964. if (line == display.maxLine) {
  4965. recomputeMaxLength = true;
  4966. return true
  4967. }
  4968. });
  4969. }
  4970. if (doc.sel.contains(change.from, change.to) > -1)
  4971. { signalCursorActivity(cm); }
  4972. updateDoc(doc, change, spans, estimateHeight(cm));
  4973. if (!cm.options.lineWrapping) {
  4974. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4975. var len = lineLength(line);
  4976. if (len > display.maxLineLength) {
  4977. display.maxLine = line;
  4978. display.maxLineLength = len;
  4979. display.maxLineChanged = true;
  4980. recomputeMaxLength = false;
  4981. }
  4982. });
  4983. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4984. }
  4985. retreatFrontier(doc, from.line);
  4986. startWorker(cm, 400);
  4987. var lendiff = change.text.length - (to.line - from.line) - 1;
  4988. // Remember that these lines changed, for updating the display
  4989. if (change.full)
  4990. { regChange(cm); }
  4991. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4992. { regLineChange(cm, from.line, "text"); }
  4993. else
  4994. { regChange(cm, from.line, to.line + 1, lendiff); }
  4995. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4996. if (changeHandler || changesHandler) {
  4997. var obj = {
  4998. from: from, to: to,
  4999. text: change.text,
  5000. removed: change.removed,
  5001. origin: change.origin
  5002. };
  5003. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  5004. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  5005. }
  5006. cm.display.selForContextMenu = null;
  5007. }
  5008. function replaceRange(doc, code, from, to, origin) {
  5009. var assign;
  5010. if (!to) { to = from; }
  5011. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  5012. if (typeof code == "string") { code = doc.splitLines(code); }
  5013. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  5014. }
  5015. // Rebasing/resetting history to deal with externally-sourced changes
  5016. function rebaseHistSelSingle(pos, from, to, diff) {
  5017. if (to < pos.line) {
  5018. pos.line += diff;
  5019. } else if (from < pos.line) {
  5020. pos.line = from;
  5021. pos.ch = 0;
  5022. }
  5023. }
  5024. // Tries to rebase an array of history events given a change in the
  5025. // document. If the change touches the same lines as the event, the
  5026. // event, and everything 'behind' it, is discarded. If the change is
  5027. // before the event, the event's positions are updated. Uses a
  5028. // copy-on-write scheme for the positions, to avoid having to
  5029. // reallocate them all on every rebase, but also avoid problems with
  5030. // shared position objects being unsafely updated.
  5031. function rebaseHistArray(array, from, to, diff) {
  5032. for (var i = 0; i < array.length; ++i) {
  5033. var sub = array[i], ok = true;
  5034. if (sub.ranges) {
  5035. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5036. for (var j = 0; j < sub.ranges.length; j++) {
  5037. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5038. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5039. }
  5040. continue
  5041. }
  5042. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5043. var cur = sub.changes[j$1];
  5044. if (to < cur.from.line) {
  5045. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5046. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5047. } else if (from <= cur.to.line) {
  5048. ok = false;
  5049. break
  5050. }
  5051. }
  5052. if (!ok) {
  5053. array.splice(0, i + 1);
  5054. i = 0;
  5055. }
  5056. }
  5057. }
  5058. function rebaseHist(hist, change) {
  5059. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5060. rebaseHistArray(hist.done, from, to, diff);
  5061. rebaseHistArray(hist.undone, from, to, diff);
  5062. }
  5063. // Utility for applying a change to a line by handle or number,
  5064. // returning the number and optionally registering the line as
  5065. // changed.
  5066. function changeLine(doc, handle, changeType, op) {
  5067. var no = handle, line = handle;
  5068. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5069. else { no = lineNo(handle); }
  5070. if (no == null) { return null }
  5071. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5072. return line
  5073. }
  5074. // The document is represented as a BTree consisting of leaves, with
  5075. // chunk of lines in them, and branches, with up to ten leaves or
  5076. // other branch nodes below them. The top node is always a branch
  5077. // node, and is the document object itself (meaning it has
  5078. // additional methods and properties).
  5079. //
  5080. // All nodes have parent links. The tree is used both to go from
  5081. // line numbers to line objects, and to go from objects to numbers.
  5082. // It also indexes by height, and is used to convert between height
  5083. // and line object, and to find the total height of the document.
  5084. //
  5085. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5086. function LeafChunk(lines) {
  5087. this.lines = lines;
  5088. this.parent = null;
  5089. var height = 0;
  5090. for (var i = 0; i < lines.length; ++i) {
  5091. lines[i].parent = this;
  5092. height += lines[i].height;
  5093. }
  5094. this.height = height;
  5095. }
  5096. LeafChunk.prototype = {
  5097. chunkSize: function() { return this.lines.length },
  5098. // Remove the n lines at offset 'at'.
  5099. removeInner: function(at, n) {
  5100. for (var i = at, e = at + n; i < e; ++i) {
  5101. var line = this.lines[i];
  5102. this.height -= line.height;
  5103. cleanUpLine(line);
  5104. signalLater(line, "delete");
  5105. }
  5106. this.lines.splice(at, n);
  5107. },
  5108. // Helper used to collapse a small branch into a single leaf.
  5109. collapse: function(lines) {
  5110. lines.push.apply(lines, this.lines);
  5111. },
  5112. // Insert the given array of lines at offset 'at', count them as
  5113. // having the given height.
  5114. insertInner: function(at, lines, height) {
  5115. this.height += height;
  5116. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5117. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5118. },
  5119. // Used to iterate over a part of the tree.
  5120. iterN: function(at, n, op) {
  5121. for (var e = at + n; at < e; ++at)
  5122. { if (op(this.lines[at])) { return true } }
  5123. }
  5124. };
  5125. function BranchChunk(children) {
  5126. this.children = children;
  5127. var size = 0, height = 0;
  5128. for (var i = 0; i < children.length; ++i) {
  5129. var ch = children[i];
  5130. size += ch.chunkSize(); height += ch.height;
  5131. ch.parent = this;
  5132. }
  5133. this.size = size;
  5134. this.height = height;
  5135. this.parent = null;
  5136. }
  5137. BranchChunk.prototype = {
  5138. chunkSize: function() { return this.size },
  5139. removeInner: function(at, n) {
  5140. this.size -= n;
  5141. for (var i = 0; i < this.children.length; ++i) {
  5142. var child = this.children[i], sz = child.chunkSize();
  5143. if (at < sz) {
  5144. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5145. child.removeInner(at, rm);
  5146. this.height -= oldHeight - child.height;
  5147. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5148. if ((n -= rm) == 0) { break }
  5149. at = 0;
  5150. } else { at -= sz; }
  5151. }
  5152. // If the result is smaller than 25 lines, ensure that it is a
  5153. // single leaf node.
  5154. if (this.size - n < 25 &&
  5155. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5156. var lines = [];
  5157. this.collapse(lines);
  5158. this.children = [new LeafChunk(lines)];
  5159. this.children[0].parent = this;
  5160. }
  5161. },
  5162. collapse: function(lines) {
  5163. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5164. },
  5165. insertInner: function(at, lines, height) {
  5166. this.size += lines.length;
  5167. this.height += height;
  5168. for (var i = 0; i < this.children.length; ++i) {
  5169. var child = this.children[i], sz = child.chunkSize();
  5170. if (at <= sz) {
  5171. child.insertInner(at, lines, height);
  5172. if (child.lines && child.lines.length > 50) {
  5173. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5174. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5175. var remaining = child.lines.length % 25 + 25;
  5176. for (var pos = remaining; pos < child.lines.length;) {
  5177. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5178. child.height -= leaf.height;
  5179. this.children.splice(++i, 0, leaf);
  5180. leaf.parent = this;
  5181. }
  5182. child.lines = child.lines.slice(0, remaining);
  5183. this.maybeSpill();
  5184. }
  5185. break
  5186. }
  5187. at -= sz;
  5188. }
  5189. },
  5190. // When a node has grown, check whether it should be split.
  5191. maybeSpill: function() {
  5192. if (this.children.length <= 10) { return }
  5193. var me = this;
  5194. do {
  5195. var spilled = me.children.splice(me.children.length - 5, 5);
  5196. var sibling = new BranchChunk(spilled);
  5197. if (!me.parent) { // Become the parent node
  5198. var copy = new BranchChunk(me.children);
  5199. copy.parent = me;
  5200. me.children = [copy, sibling];
  5201. me = copy;
  5202. } else {
  5203. me.size -= sibling.size;
  5204. me.height -= sibling.height;
  5205. var myIndex = indexOf(me.parent.children, me);
  5206. me.parent.children.splice(myIndex + 1, 0, sibling);
  5207. }
  5208. sibling.parent = me.parent;
  5209. } while (me.children.length > 10)
  5210. me.parent.maybeSpill();
  5211. },
  5212. iterN: function(at, n, op) {
  5213. for (var i = 0; i < this.children.length; ++i) {
  5214. var child = this.children[i], sz = child.chunkSize();
  5215. if (at < sz) {
  5216. var used = Math.min(n, sz - at);
  5217. if (child.iterN(at, used, op)) { return true }
  5218. if ((n -= used) == 0) { break }
  5219. at = 0;
  5220. } else { at -= sz; }
  5221. }
  5222. }
  5223. };
  5224. // Line widgets are block elements displayed above or below a line.
  5225. var LineWidget = function(doc, node, options) {
  5226. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5227. { this[opt] = options[opt]; } } }
  5228. this.doc = doc;
  5229. this.node = node;
  5230. };
  5231. LineWidget.prototype.clear = function () {
  5232. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5233. if (no == null || !ws) { return }
  5234. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5235. if (!ws.length) { line.widgets = null; }
  5236. var height = widgetHeight(this);
  5237. updateLineHeight(line, Math.max(0, line.height - height));
  5238. if (cm) {
  5239. runInOp(cm, function () {
  5240. adjustScrollWhenAboveVisible(cm, line, -height);
  5241. regLineChange(cm, no, "widget");
  5242. });
  5243. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5244. }
  5245. };
  5246. LineWidget.prototype.changed = function () {
  5247. var this$1 = this;
  5248. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5249. this.height = null;
  5250. var diff = widgetHeight(this) - oldH;
  5251. if (!diff) { return }
  5252. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5253. if (cm) {
  5254. runInOp(cm, function () {
  5255. cm.curOp.forceUpdate = true;
  5256. adjustScrollWhenAboveVisible(cm, line, diff);
  5257. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5258. });
  5259. }
  5260. };
  5261. eventMixin(LineWidget);
  5262. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5263. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5264. { addToScrollTop(cm, diff); }
  5265. }
  5266. function addLineWidget(doc, handle, node, options) {
  5267. var widget = new LineWidget(doc, node, options);
  5268. var cm = doc.cm;
  5269. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5270. changeLine(doc, handle, "widget", function (line) {
  5271. var widgets = line.widgets || (line.widgets = []);
  5272. if (widget.insertAt == null) { widgets.push(widget); }
  5273. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5274. widget.line = line;
  5275. if (cm && !lineIsHidden(doc, line)) {
  5276. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5277. updateLineHeight(line, line.height + widgetHeight(widget));
  5278. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5279. cm.curOp.forceUpdate = true;
  5280. }
  5281. return true
  5282. });
  5283. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5284. return widget
  5285. }
  5286. // TEXTMARKERS
  5287. // Created with markText and setBookmark methods. A TextMarker is a
  5288. // handle that can be used to clear or find a marked position in the
  5289. // document. Line objects hold arrays (markedSpans) containing
  5290. // {from, to, marker} object pointing to such marker objects, and
  5291. // indicating that such a marker is present on that line. Multiple
  5292. // lines may point to the same marker when it spans across lines.
  5293. // The spans will have null for their from/to properties when the
  5294. // marker continues beyond the start/end of the line. Markers have
  5295. // links back to the lines they currently touch.
  5296. // Collapsed markers have unique ids, in order to be able to order
  5297. // them, which is needed for uniquely determining an outer marker
  5298. // when they overlap (they may nest, but not partially overlap).
  5299. var nextMarkerId = 0;
  5300. var TextMarker = function(doc, type) {
  5301. this.lines = [];
  5302. this.type = type;
  5303. this.doc = doc;
  5304. this.id = ++nextMarkerId;
  5305. };
  5306. // Clear the marker.
  5307. TextMarker.prototype.clear = function () {
  5308. if (this.explicitlyCleared) { return }
  5309. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5310. if (withOp) { startOperation(cm); }
  5311. if (hasHandler(this, "clear")) {
  5312. var found = this.find();
  5313. if (found) { signalLater(this, "clear", found.from, found.to); }
  5314. }
  5315. var min = null, max = null;
  5316. for (var i = 0; i < this.lines.length; ++i) {
  5317. var line = this.lines[i];
  5318. var span = getMarkedSpanFor(line.markedSpans, this);
  5319. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5320. else if (cm) {
  5321. if (span.to != null) { max = lineNo(line); }
  5322. if (span.from != null) { min = lineNo(line); }
  5323. }
  5324. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5325. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5326. { updateLineHeight(line, textHeight(cm.display)); }
  5327. }
  5328. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5329. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5330. if (len > cm.display.maxLineLength) {
  5331. cm.display.maxLine = visual;
  5332. cm.display.maxLineLength = len;
  5333. cm.display.maxLineChanged = true;
  5334. }
  5335. } }
  5336. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5337. this.lines.length = 0;
  5338. this.explicitlyCleared = true;
  5339. if (this.atomic && this.doc.cantEdit) {
  5340. this.doc.cantEdit = false;
  5341. if (cm) { reCheckSelection(cm.doc); }
  5342. }
  5343. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5344. if (withOp) { endOperation(cm); }
  5345. if (this.parent) { this.parent.clear(); }
  5346. };
  5347. // Find the position of the marker in the document. Returns a {from,
  5348. // to} object by default. Side can be passed to get a specific side
  5349. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5350. // Pos objects returned contain a line object, rather than a line
  5351. // number (used to prevent looking up the same line twice).
  5352. TextMarker.prototype.find = function (side, lineObj) {
  5353. if (side == null && this.type == "bookmark") { side = 1; }
  5354. var from, to;
  5355. for (var i = 0; i < this.lines.length; ++i) {
  5356. var line = this.lines[i];
  5357. var span = getMarkedSpanFor(line.markedSpans, this);
  5358. if (span.from != null) {
  5359. from = Pos(lineObj ? line : lineNo(line), span.from);
  5360. if (side == -1) { return from }
  5361. }
  5362. if (span.to != null) {
  5363. to = Pos(lineObj ? line : lineNo(line), span.to);
  5364. if (side == 1) { return to }
  5365. }
  5366. }
  5367. return from && {from: from, to: to}
  5368. };
  5369. // Signals that the marker's widget changed, and surrounding layout
  5370. // should be recomputed.
  5371. TextMarker.prototype.changed = function () {
  5372. var this$1 = this;
  5373. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5374. if (!pos || !cm) { return }
  5375. runInOp(cm, function () {
  5376. var line = pos.line, lineN = lineNo(pos.line);
  5377. var view = findViewForLine(cm, lineN);
  5378. if (view) {
  5379. clearLineMeasurementCacheFor(view);
  5380. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5381. }
  5382. cm.curOp.updateMaxLine = true;
  5383. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5384. var oldHeight = widget.height;
  5385. widget.height = null;
  5386. var dHeight = widgetHeight(widget) - oldHeight;
  5387. if (dHeight)
  5388. { updateLineHeight(line, line.height + dHeight); }
  5389. }
  5390. signalLater(cm, "markerChanged", cm, this$1);
  5391. });
  5392. };
  5393. TextMarker.prototype.attachLine = function (line) {
  5394. if (!this.lines.length && this.doc.cm) {
  5395. var op = this.doc.cm.curOp;
  5396. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5397. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5398. }
  5399. this.lines.push(line);
  5400. };
  5401. TextMarker.prototype.detachLine = function (line) {
  5402. this.lines.splice(indexOf(this.lines, line), 1);
  5403. if (!this.lines.length && this.doc.cm) {
  5404. var op = this.doc.cm.curOp
  5405. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5406. }
  5407. };
  5408. eventMixin(TextMarker);
  5409. // Create a marker, wire it up to the right lines, and
  5410. function markText(doc, from, to, options, type) {
  5411. // Shared markers (across linked documents) are handled separately
  5412. // (markTextShared will call out to this again, once per
  5413. // document).
  5414. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5415. // Ensure we are in an operation.
  5416. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5417. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5418. if (options) { copyObj(options, marker, false); }
  5419. // Don't connect empty markers unless clearWhenEmpty is false
  5420. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5421. { return marker }
  5422. if (marker.replacedWith) {
  5423. // Showing up as a widget implies collapsed (widget replaces text)
  5424. marker.collapsed = true;
  5425. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5426. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5427. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5428. }
  5429. if (marker.collapsed) {
  5430. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5431. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5432. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5433. seeCollapsedSpans();
  5434. }
  5435. if (marker.addToHistory)
  5436. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5437. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5438. doc.iter(curLine, to.line + 1, function (line) {
  5439. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5440. { updateMaxLine = true; }
  5441. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5442. addMarkedSpan(line, new MarkedSpan(marker,
  5443. curLine == from.line ? from.ch : null,
  5444. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  5445. ++curLine;
  5446. });
  5447. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5448. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5449. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5450. }); }
  5451. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5452. if (marker.readOnly) {
  5453. seeReadOnlySpans();
  5454. if (doc.history.done.length || doc.history.undone.length)
  5455. { doc.clearHistory(); }
  5456. }
  5457. if (marker.collapsed) {
  5458. marker.id = ++nextMarkerId;
  5459. marker.atomic = true;
  5460. }
  5461. if (cm) {
  5462. // Sync editor state
  5463. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5464. if (marker.collapsed)
  5465. { regChange(cm, from.line, to.line + 1); }
  5466. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5467. marker.attributes || marker.title)
  5468. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5469. if (marker.atomic) { reCheckSelection(cm.doc); }
  5470. signalLater(cm, "markerAdded", cm, marker);
  5471. }
  5472. return marker
  5473. }
  5474. // SHARED TEXTMARKERS
  5475. // A shared marker spans multiple linked documents. It is
  5476. // implemented as a meta-marker-object controlling multiple normal
  5477. // markers.
  5478. var SharedTextMarker = function(markers, primary) {
  5479. this.markers = markers;
  5480. this.primary = primary;
  5481. for (var i = 0; i < markers.length; ++i)
  5482. { markers[i].parent = this; }
  5483. };
  5484. SharedTextMarker.prototype.clear = function () {
  5485. if (this.explicitlyCleared) { return }
  5486. this.explicitlyCleared = true;
  5487. for (var i = 0; i < this.markers.length; ++i)
  5488. { this.markers[i].clear(); }
  5489. signalLater(this, "clear");
  5490. };
  5491. SharedTextMarker.prototype.find = function (side, lineObj) {
  5492. return this.primary.find(side, lineObj)
  5493. };
  5494. eventMixin(SharedTextMarker);
  5495. function markTextShared(doc, from, to, options, type) {
  5496. options = copyObj(options);
  5497. options.shared = false;
  5498. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5499. var widget = options.widgetNode;
  5500. linkedDocs(doc, function (doc) {
  5501. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5502. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5503. for (var i = 0; i < doc.linked.length; ++i)
  5504. { if (doc.linked[i].isParent) { return } }
  5505. primary = lst(markers);
  5506. });
  5507. return new SharedTextMarker(markers, primary)
  5508. }
  5509. function findSharedMarkers(doc) {
  5510. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5511. }
  5512. function copySharedMarkers(doc, markers) {
  5513. for (var i = 0; i < markers.length; i++) {
  5514. var marker = markers[i], pos = marker.find();
  5515. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5516. if (cmp(mFrom, mTo)) {
  5517. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5518. marker.markers.push(subMark);
  5519. subMark.parent = marker;
  5520. }
  5521. }
  5522. }
  5523. function detachSharedMarkers(markers) {
  5524. var loop = function ( i ) {
  5525. var marker = markers[i], linked = [marker.primary.doc];
  5526. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5527. for (var j = 0; j < marker.markers.length; j++) {
  5528. var subMarker = marker.markers[j];
  5529. if (indexOf(linked, subMarker.doc) == -1) {
  5530. subMarker.parent = null;
  5531. marker.markers.splice(j--, 1);
  5532. }
  5533. }
  5534. };
  5535. for (var i = 0; i < markers.length; i++) loop( i );
  5536. }
  5537. var nextDocId = 0;
  5538. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5539. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5540. if (firstLine == null) { firstLine = 0; }
  5541. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5542. this.first = firstLine;
  5543. this.scrollTop = this.scrollLeft = 0;
  5544. this.cantEdit = false;
  5545. this.cleanGeneration = 1;
  5546. this.modeFrontier = this.highlightFrontier = firstLine;
  5547. var start = Pos(firstLine, 0);
  5548. this.sel = simpleSelection(start);
  5549. this.history = new History(null);
  5550. this.id = ++nextDocId;
  5551. this.modeOption = mode;
  5552. this.lineSep = lineSep;
  5553. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5554. this.extend = false;
  5555. if (typeof text == "string") { text = this.splitLines(text); }
  5556. updateDoc(this, {from: start, to: start, text: text});
  5557. setSelection(this, simpleSelection(start), sel_dontScroll);
  5558. };
  5559. Doc.prototype = createObj(BranchChunk.prototype, {
  5560. constructor: Doc,
  5561. // Iterate over the document. Supports two forms -- with only one
  5562. // argument, it calls that for each line in the document. With
  5563. // three, it iterates over the range given by the first two (with
  5564. // the second being non-inclusive).
  5565. iter: function(from, to, op) {
  5566. if (op) { this.iterN(from - this.first, to - from, op); }
  5567. else { this.iterN(this.first, this.first + this.size, from); }
  5568. },
  5569. // Non-public interface for adding and removing lines.
  5570. insert: function(at, lines) {
  5571. var height = 0;
  5572. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5573. this.insertInner(at - this.first, lines, height);
  5574. },
  5575. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5576. // From here, the methods are part of the public interface. Most
  5577. // are also available from CodeMirror (editor) instances.
  5578. getValue: function(lineSep) {
  5579. var lines = getLines(this, this.first, this.first + this.size);
  5580. if (lineSep === false) { return lines }
  5581. return lines.join(lineSep || this.lineSeparator())
  5582. },
  5583. setValue: docMethodOp(function(code) {
  5584. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5585. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5586. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5587. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5588. setSelection(this, simpleSelection(top), sel_dontScroll);
  5589. }),
  5590. replaceRange: function(code, from, to, origin) {
  5591. from = clipPos(this, from);
  5592. to = to ? clipPos(this, to) : from;
  5593. replaceRange(this, code, from, to, origin);
  5594. },
  5595. getRange: function(from, to, lineSep) {
  5596. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5597. if (lineSep === false) { return lines }
  5598. if (lineSep === '') { return lines.join('') }
  5599. return lines.join(lineSep || this.lineSeparator())
  5600. },
  5601. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5602. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5603. getLineNumber: function(line) {return lineNo(line)},
  5604. getLineHandleVisualStart: function(line) {
  5605. if (typeof line == "number") { line = getLine(this, line); }
  5606. return visualLine(line)
  5607. },
  5608. lineCount: function() {return this.size},
  5609. firstLine: function() {return this.first},
  5610. lastLine: function() {return this.first + this.size - 1},
  5611. clipPos: function(pos) {return clipPos(this, pos)},
  5612. getCursor: function(start) {
  5613. var range = this.sel.primary(), pos;
  5614. if (start == null || start == "head") { pos = range.head; }
  5615. else if (start == "anchor") { pos = range.anchor; }
  5616. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5617. else { pos = range.from(); }
  5618. return pos
  5619. },
  5620. listSelections: function() { return this.sel.ranges },
  5621. somethingSelected: function() {return this.sel.somethingSelected()},
  5622. setCursor: docMethodOp(function(line, ch, options) {
  5623. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5624. }),
  5625. setSelection: docMethodOp(function(anchor, head, options) {
  5626. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5627. }),
  5628. extendSelection: docMethodOp(function(head, other, options) {
  5629. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5630. }),
  5631. extendSelections: docMethodOp(function(heads, options) {
  5632. extendSelections(this, clipPosArray(this, heads), options);
  5633. }),
  5634. extendSelectionsBy: docMethodOp(function(f, options) {
  5635. var heads = map(this.sel.ranges, f);
  5636. extendSelections(this, clipPosArray(this, heads), options);
  5637. }),
  5638. setSelections: docMethodOp(function(ranges, primary, options) {
  5639. if (!ranges.length) { return }
  5640. var out = [];
  5641. for (var i = 0; i < ranges.length; i++)
  5642. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  5643. clipPos(this, ranges[i].head || ranges[i].anchor)); }
  5644. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5645. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5646. }),
  5647. addSelection: docMethodOp(function(anchor, head, options) {
  5648. var ranges = this.sel.ranges.slice(0);
  5649. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5650. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5651. }),
  5652. getSelection: function(lineSep) {
  5653. var ranges = this.sel.ranges, lines;
  5654. for (var i = 0; i < ranges.length; i++) {
  5655. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5656. lines = lines ? lines.concat(sel) : sel;
  5657. }
  5658. if (lineSep === false) { return lines }
  5659. else { return lines.join(lineSep || this.lineSeparator()) }
  5660. },
  5661. getSelections: function(lineSep) {
  5662. var parts = [], ranges = this.sel.ranges;
  5663. for (var i = 0; i < ranges.length; i++) {
  5664. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5665. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5666. parts[i] = sel;
  5667. }
  5668. return parts
  5669. },
  5670. replaceSelection: function(code, collapse, origin) {
  5671. var dup = [];
  5672. for (var i = 0; i < this.sel.ranges.length; i++)
  5673. { dup[i] = code; }
  5674. this.replaceSelections(dup, collapse, origin || "+input");
  5675. },
  5676. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5677. var changes = [], sel = this.sel;
  5678. for (var i = 0; i < sel.ranges.length; i++) {
  5679. var range = sel.ranges[i];
  5680. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  5681. }
  5682. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5683. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5684. { makeChange(this, changes[i$1]); }
  5685. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5686. else if (this.cm) { ensureCursorVisible(this.cm); }
  5687. }),
  5688. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5689. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5690. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5691. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5692. setExtending: function(val) {this.extend = val;},
  5693. getExtending: function() {return this.extend},
  5694. historySize: function() {
  5695. var hist = this.history, done = 0, undone = 0;
  5696. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5697. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5698. return {undo: done, redo: undone}
  5699. },
  5700. clearHistory: function() {
  5701. var this$1 = this;
  5702. this.history = new History(this.history);
  5703. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5704. },
  5705. markClean: function() {
  5706. this.cleanGeneration = this.changeGeneration(true);
  5707. },
  5708. changeGeneration: function(forceSplit) {
  5709. if (forceSplit)
  5710. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5711. return this.history.generation
  5712. },
  5713. isClean: function (gen) {
  5714. return this.history.generation == (gen || this.cleanGeneration)
  5715. },
  5716. getHistory: function() {
  5717. return {done: copyHistoryArray(this.history.done),
  5718. undone: copyHistoryArray(this.history.undone)}
  5719. },
  5720. setHistory: function(histData) {
  5721. var hist = this.history = new History(this.history);
  5722. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5723. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5724. },
  5725. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5726. return changeLine(this, line, "gutter", function (line) {
  5727. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5728. markers[gutterID] = value;
  5729. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5730. return true
  5731. })
  5732. }),
  5733. clearGutter: docMethodOp(function(gutterID) {
  5734. var this$1 = this;
  5735. this.iter(function (line) {
  5736. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5737. changeLine(this$1, line, "gutter", function () {
  5738. line.gutterMarkers[gutterID] = null;
  5739. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5740. return true
  5741. });
  5742. }
  5743. });
  5744. }),
  5745. lineInfo: function(line) {
  5746. var n;
  5747. if (typeof line == "number") {
  5748. if (!isLine(this, line)) { return null }
  5749. n = line;
  5750. line = getLine(this, line);
  5751. if (!line) { return null }
  5752. } else {
  5753. n = lineNo(line);
  5754. if (n == null) { return null }
  5755. }
  5756. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5757. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5758. widgets: line.widgets}
  5759. },
  5760. addLineClass: docMethodOp(function(handle, where, cls) {
  5761. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5762. var prop = where == "text" ? "textClass"
  5763. : where == "background" ? "bgClass"
  5764. : where == "gutter" ? "gutterClass" : "wrapClass";
  5765. if (!line[prop]) { line[prop] = cls; }
  5766. else if (classTest(cls).test(line[prop])) { return false }
  5767. else { line[prop] += " " + cls; }
  5768. return true
  5769. })
  5770. }),
  5771. removeLineClass: docMethodOp(function(handle, where, cls) {
  5772. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5773. var prop = where == "text" ? "textClass"
  5774. : where == "background" ? "bgClass"
  5775. : where == "gutter" ? "gutterClass" : "wrapClass";
  5776. var cur = line[prop];
  5777. if (!cur) { return false }
  5778. else if (cls == null) { line[prop] = null; }
  5779. else {
  5780. var found = cur.match(classTest(cls));
  5781. if (!found) { return false }
  5782. var end = found.index + found[0].length;
  5783. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5784. }
  5785. return true
  5786. })
  5787. }),
  5788. addLineWidget: docMethodOp(function(handle, node, options) {
  5789. return addLineWidget(this, handle, node, options)
  5790. }),
  5791. removeLineWidget: function(widget) { widget.clear(); },
  5792. markText: function(from, to, options) {
  5793. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5794. },
  5795. setBookmark: function(pos, options) {
  5796. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5797. insertLeft: options && options.insertLeft,
  5798. clearWhenEmpty: false, shared: options && options.shared,
  5799. handleMouseEvents: options && options.handleMouseEvents};
  5800. pos = clipPos(this, pos);
  5801. return markText(this, pos, pos, realOpts, "bookmark")
  5802. },
  5803. findMarksAt: function(pos) {
  5804. pos = clipPos(this, pos);
  5805. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5806. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5807. var span = spans[i];
  5808. if ((span.from == null || span.from <= pos.ch) &&
  5809. (span.to == null || span.to >= pos.ch))
  5810. { markers.push(span.marker.parent || span.marker); }
  5811. } }
  5812. return markers
  5813. },
  5814. findMarks: function(from, to, filter) {
  5815. from = clipPos(this, from); to = clipPos(this, to);
  5816. var found = [], lineNo = from.line;
  5817. this.iter(from.line, to.line + 1, function (line) {
  5818. var spans = line.markedSpans;
  5819. if (spans) { for (var i = 0; i < spans.length; i++) {
  5820. var span = spans[i];
  5821. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5822. span.from == null && lineNo != from.line ||
  5823. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5824. (!filter || filter(span.marker)))
  5825. { found.push(span.marker.parent || span.marker); }
  5826. } }
  5827. ++lineNo;
  5828. });
  5829. return found
  5830. },
  5831. getAllMarks: function() {
  5832. var markers = [];
  5833. this.iter(function (line) {
  5834. var sps = line.markedSpans;
  5835. if (sps) { for (var i = 0; i < sps.length; ++i)
  5836. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5837. });
  5838. return markers
  5839. },
  5840. posFromIndex: function(off) {
  5841. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5842. this.iter(function (line) {
  5843. var sz = line.text.length + sepSize;
  5844. if (sz > off) { ch = off; return true }
  5845. off -= sz;
  5846. ++lineNo;
  5847. });
  5848. return clipPos(this, Pos(lineNo, ch))
  5849. },
  5850. indexFromPos: function (coords) {
  5851. coords = clipPos(this, coords);
  5852. var index = coords.ch;
  5853. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5854. var sepSize = this.lineSeparator().length;
  5855. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5856. index += line.text.length + sepSize;
  5857. });
  5858. return index
  5859. },
  5860. copy: function(copyHistory) {
  5861. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5862. this.modeOption, this.first, this.lineSep, this.direction);
  5863. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5864. doc.sel = this.sel;
  5865. doc.extend = false;
  5866. if (copyHistory) {
  5867. doc.history.undoDepth = this.history.undoDepth;
  5868. doc.setHistory(this.getHistory());
  5869. }
  5870. return doc
  5871. },
  5872. linkedDoc: function(options) {
  5873. if (!options) { options = {}; }
  5874. var from = this.first, to = this.first + this.size;
  5875. if (options.from != null && options.from > from) { from = options.from; }
  5876. if (options.to != null && options.to < to) { to = options.to; }
  5877. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5878. if (options.sharedHist) { copy.history = this.history
  5879. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5880. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5881. copySharedMarkers(copy, findSharedMarkers(this));
  5882. return copy
  5883. },
  5884. unlinkDoc: function(other) {
  5885. if (other instanceof CodeMirror) { other = other.doc; }
  5886. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5887. var link = this.linked[i];
  5888. if (link.doc != other) { continue }
  5889. this.linked.splice(i, 1);
  5890. other.unlinkDoc(this);
  5891. detachSharedMarkers(findSharedMarkers(this));
  5892. break
  5893. } }
  5894. // If the histories were shared, split them again
  5895. if (other.history == this.history) {
  5896. var splitIds = [other.id];
  5897. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5898. other.history = new History(null);
  5899. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5900. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5901. }
  5902. },
  5903. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5904. getMode: function() {return this.mode},
  5905. getEditor: function() {return this.cm},
  5906. splitLines: function(str) {
  5907. if (this.lineSep) { return str.split(this.lineSep) }
  5908. return splitLinesAuto(str)
  5909. },
  5910. lineSeparator: function() { return this.lineSep || "\n" },
  5911. setDirection: docMethodOp(function (dir) {
  5912. if (dir != "rtl") { dir = "ltr"; }
  5913. if (dir == this.direction) { return }
  5914. this.direction = dir;
  5915. this.iter(function (line) { return line.order = null; });
  5916. if (this.cm) { directionChanged(this.cm); }
  5917. })
  5918. });
  5919. // Public alias.
  5920. Doc.prototype.eachLine = Doc.prototype.iter;
  5921. // Kludge to work around strange IE behavior where it'll sometimes
  5922. // re-fire a series of drag-related events right after the drop (#1551)
  5923. var lastDrop = 0;
  5924. function onDrop(e) {
  5925. var cm = this;
  5926. clearDragCursor(cm);
  5927. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5928. { return }
  5929. e_preventDefault(e);
  5930. if (ie) { lastDrop = +new Date; }
  5931. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5932. if (!pos || cm.isReadOnly()) { return }
  5933. // Might be a file drop, in which case we simply extract the text
  5934. // and insert it.
  5935. if (files && files.length && window.FileReader && window.File) {
  5936. var n = files.length, text = Array(n), read = 0;
  5937. var markAsReadAndPasteIfAllFilesAreRead = function () {
  5938. if (++read == n) {
  5939. operation(cm, function () {
  5940. pos = clipPos(cm.doc, pos);
  5941. var change = {from: pos, to: pos,
  5942. text: cm.doc.splitLines(
  5943. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  5944. origin: "paste"};
  5945. makeChange(cm.doc, change);
  5946. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  5947. })();
  5948. }
  5949. };
  5950. var readTextFromFile = function (file, i) {
  5951. if (cm.options.allowDropFileTypes &&
  5952. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  5953. markAsReadAndPasteIfAllFilesAreRead();
  5954. return
  5955. }
  5956. var reader = new FileReader;
  5957. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  5958. reader.onload = function () {
  5959. var content = reader.result;
  5960. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  5961. markAsReadAndPasteIfAllFilesAreRead();
  5962. return
  5963. }
  5964. text[i] = content;
  5965. markAsReadAndPasteIfAllFilesAreRead();
  5966. };
  5967. reader.readAsText(file);
  5968. };
  5969. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  5970. } else { // Normal drop
  5971. // Don't do a replace if the drop happened inside of the selected text.
  5972. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5973. cm.state.draggingText(e);
  5974. // Ensure the editor is re-focused
  5975. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5976. return
  5977. }
  5978. try {
  5979. var text$1 = e.dataTransfer.getData("Text");
  5980. if (text$1) {
  5981. var selected;
  5982. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5983. { selected = cm.listSelections(); }
  5984. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5985. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5986. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5987. cm.replaceSelection(text$1, "around", "paste");
  5988. cm.display.input.focus();
  5989. }
  5990. }
  5991. catch(e$1){}
  5992. }
  5993. }
  5994. function onDragStart(cm, e) {
  5995. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5996. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5997. e.dataTransfer.setData("Text", cm.getSelection());
  5998. e.dataTransfer.effectAllowed = "copyMove";
  5999. // Use dummy image instead of default browsers image.
  6000. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  6001. if (e.dataTransfer.setDragImage && !safari) {
  6002. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  6003. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  6004. if (presto) {
  6005. img.width = img.height = 1;
  6006. cm.display.wrapper.appendChild(img);
  6007. // Force a relayout, or Opera won't use our image for some obscure reason
  6008. img._top = img.offsetTop;
  6009. }
  6010. e.dataTransfer.setDragImage(img, 0, 0);
  6011. if (presto) { img.parentNode.removeChild(img); }
  6012. }
  6013. }
  6014. function onDragOver(cm, e) {
  6015. var pos = posFromMouse(cm, e);
  6016. if (!pos) { return }
  6017. var frag = document.createDocumentFragment();
  6018. drawSelectionCursor(cm, pos, frag);
  6019. if (!cm.display.dragCursor) {
  6020. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6021. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6022. }
  6023. removeChildrenAndAdd(cm.display.dragCursor, frag);
  6024. }
  6025. function clearDragCursor(cm) {
  6026. if (cm.display.dragCursor) {
  6027. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6028. cm.display.dragCursor = null;
  6029. }
  6030. }
  6031. // These must be handled carefully, because naively registering a
  6032. // handler for each editor will cause the editors to never be
  6033. // garbage collected.
  6034. function forEachCodeMirror(f) {
  6035. if (!document.getElementsByClassName) { return }
  6036. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6037. for (var i = 0; i < byClass.length; i++) {
  6038. var cm = byClass[i].CodeMirror;
  6039. if (cm) { editors.push(cm); }
  6040. }
  6041. if (editors.length) { editors[0].operation(function () {
  6042. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6043. }); }
  6044. }
  6045. var globalsRegistered = false;
  6046. function ensureGlobalHandlers() {
  6047. if (globalsRegistered) { return }
  6048. registerGlobalHandlers();
  6049. globalsRegistered = true;
  6050. }
  6051. function registerGlobalHandlers() {
  6052. // When the window resizes, we need to refresh active editors.
  6053. var resizeTimer;
  6054. on(window, "resize", function () {
  6055. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6056. resizeTimer = null;
  6057. forEachCodeMirror(onResize);
  6058. }, 100); }
  6059. });
  6060. // When the window loses focus, we want to show the editor as blurred
  6061. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6062. }
  6063. // Called when the window resizes
  6064. function onResize(cm) {
  6065. var d = cm.display;
  6066. // Might be a text scaling operation, clear size caches.
  6067. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6068. d.scrollbarsClipped = false;
  6069. cm.setSize();
  6070. }
  6071. var keyNames = {
  6072. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6073. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6074. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6075. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6076. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6077. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6078. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6079. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6080. };
  6081. // Number keys
  6082. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6083. // Alphabetic keys
  6084. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6085. // Function keys
  6086. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6087. var keyMap = {};
  6088. keyMap.basic = {
  6089. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6090. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6091. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6092. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6093. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6094. "Esc": "singleSelection"
  6095. };
  6096. // Note that the save and find-related commands aren't defined by
  6097. // default. User code or addons can define them. Unknown commands
  6098. // are simply ignored.
  6099. keyMap.pcDefault = {
  6100. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6101. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6102. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6103. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6104. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6105. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6106. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6107. "fallthrough": "basic"
  6108. };
  6109. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6110. keyMap.emacsy = {
  6111. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6112. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6113. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6114. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6115. };
  6116. keyMap.macDefault = {
  6117. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6118. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6119. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6120. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6121. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6122. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6123. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6124. "fallthrough": ["basic", "emacsy"]
  6125. };
  6126. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6127. // KEYMAP DISPATCH
  6128. function normalizeKeyName(name) {
  6129. var parts = name.split(/-(?!$)/);
  6130. name = parts[parts.length - 1];
  6131. var alt, ctrl, shift, cmd;
  6132. for (var i = 0; i < parts.length - 1; i++) {
  6133. var mod = parts[i];
  6134. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6135. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6136. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6137. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6138. else { throw new Error("Unrecognized modifier name: " + mod) }
  6139. }
  6140. if (alt) { name = "Alt-" + name; }
  6141. if (ctrl) { name = "Ctrl-" + name; }
  6142. if (cmd) { name = "Cmd-" + name; }
  6143. if (shift) { name = "Shift-" + name; }
  6144. return name
  6145. }
  6146. // This is a kludge to keep keymaps mostly working as raw objects
  6147. // (backwards compatibility) while at the same time support features
  6148. // like normalization and multi-stroke key bindings. It compiles a
  6149. // new normalized keymap, and then updates the old object to reflect
  6150. // this.
  6151. function normalizeKeyMap(keymap) {
  6152. var copy = {};
  6153. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6154. var value = keymap[keyname];
  6155. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6156. if (value == "...") { delete keymap[keyname]; continue }
  6157. var keys = map(keyname.split(" "), normalizeKeyName);
  6158. for (var i = 0; i < keys.length; i++) {
  6159. var val = (void 0), name = (void 0);
  6160. if (i == keys.length - 1) {
  6161. name = keys.join(" ");
  6162. val = value;
  6163. } else {
  6164. name = keys.slice(0, i + 1).join(" ");
  6165. val = "...";
  6166. }
  6167. var prev = copy[name];
  6168. if (!prev) { copy[name] = val; }
  6169. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6170. }
  6171. delete keymap[keyname];
  6172. } }
  6173. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6174. return keymap
  6175. }
  6176. function lookupKey(key, map, handle, context) {
  6177. map = getKeyMap(map);
  6178. var found = map.call ? map.call(key, context) : map[key];
  6179. if (found === false) { return "nothing" }
  6180. if (found === "...") { return "multi" }
  6181. if (found != null && handle(found)) { return "handled" }
  6182. if (map.fallthrough) {
  6183. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6184. { return lookupKey(key, map.fallthrough, handle, context) }
  6185. for (var i = 0; i < map.fallthrough.length; i++) {
  6186. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6187. if (result) { return result }
  6188. }
  6189. }
  6190. }
  6191. // Modifier key presses don't count as 'real' key presses for the
  6192. // purpose of keymap fallthrough.
  6193. function isModifierKey(value) {
  6194. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6195. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6196. }
  6197. function addModifierNames(name, event, noShift) {
  6198. var base = name;
  6199. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6200. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6201. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6202. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6203. return name
  6204. }
  6205. // Look up the name of a key as indicated by an event object.
  6206. function keyName(event, noShift) {
  6207. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6208. var name = keyNames[event.keyCode];
  6209. if (name == null || event.altGraphKey) { return false }
  6210. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6211. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6212. if (event.keyCode == 3 && event.code) { name = event.code; }
  6213. return addModifierNames(name, event, noShift)
  6214. }
  6215. function getKeyMap(val) {
  6216. return typeof val == "string" ? keyMap[val] : val
  6217. }
  6218. // Helper for deleting text near the selection(s), used to implement
  6219. // backspace, delete, and similar functionality.
  6220. function deleteNearSelection(cm, compute) {
  6221. var ranges = cm.doc.sel.ranges, kill = [];
  6222. // Build up a set of ranges to kill first, merging overlapping
  6223. // ranges.
  6224. for (var i = 0; i < ranges.length; i++) {
  6225. var toKill = compute(ranges[i]);
  6226. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6227. var replaced = kill.pop();
  6228. if (cmp(replaced.from, toKill.from) < 0) {
  6229. toKill.from = replaced.from;
  6230. break
  6231. }
  6232. }
  6233. kill.push(toKill);
  6234. }
  6235. // Next, remove those actual ranges.
  6236. runInOp(cm, function () {
  6237. for (var i = kill.length - 1; i >= 0; i--)
  6238. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6239. ensureCursorVisible(cm);
  6240. });
  6241. }
  6242. function moveCharLogically(line, ch, dir) {
  6243. var target = skipExtendingChars(line.text, ch + dir, dir);
  6244. return target < 0 || target > line.text.length ? null : target
  6245. }
  6246. function moveLogically(line, start, dir) {
  6247. var ch = moveCharLogically(line, start.ch, dir);
  6248. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6249. }
  6250. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6251. if (visually) {
  6252. if (cm.doc.direction == "rtl") { dir = -dir; }
  6253. var order = getOrder(lineObj, cm.doc.direction);
  6254. if (order) {
  6255. var part = dir < 0 ? lst(order) : order[0];
  6256. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6257. var sticky = moveInStorageOrder ? "after" : "before";
  6258. var ch;
  6259. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6260. // it could be that the last bidi part is not on the last visual line,
  6261. // since visual lines contain content order-consecutive chunks.
  6262. // Thus, in rtl, we are looking for the first (content-order) character
  6263. // in the rtl chunk that is on the last line (that is, the same line
  6264. // as the last (content-order) character).
  6265. if (part.level > 0 || cm.doc.direction == "rtl") {
  6266. var prep = prepareMeasureForLine(cm, lineObj);
  6267. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6268. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6269. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6270. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6271. } else { ch = dir < 0 ? part.to : part.from; }
  6272. return new Pos(lineNo, ch, sticky)
  6273. }
  6274. }
  6275. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6276. }
  6277. function moveVisually(cm, line, start, dir) {
  6278. var bidi = getOrder(line, cm.doc.direction);
  6279. if (!bidi) { return moveLogically(line, start, dir) }
  6280. if (start.ch >= line.text.length) {
  6281. start.ch = line.text.length;
  6282. start.sticky = "before";
  6283. } else if (start.ch <= 0) {
  6284. start.ch = 0;
  6285. start.sticky = "after";
  6286. }
  6287. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6288. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6289. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6290. // nothing interesting happens.
  6291. return moveLogically(line, start, dir)
  6292. }
  6293. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6294. var prep;
  6295. var getWrappedLineExtent = function (ch) {
  6296. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6297. prep = prep || prepareMeasureForLine(cm, line);
  6298. return wrappedLineExtentChar(cm, line, prep, ch)
  6299. };
  6300. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6301. if (cm.doc.direction == "rtl" || part.level == 1) {
  6302. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6303. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6304. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6305. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6306. var sticky = moveInStorageOrder ? "before" : "after";
  6307. return new Pos(start.line, ch, sticky)
  6308. }
  6309. }
  6310. // Case 3: Could not move within this bidi part in this visual line, so leave
  6311. // the current bidi part
  6312. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6313. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6314. ? new Pos(start.line, mv(ch, 1), "before")
  6315. : new Pos(start.line, ch, "after"); };
  6316. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6317. var part = bidi[partPos];
  6318. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6319. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6320. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6321. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6322. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6323. }
  6324. };
  6325. // Case 3a: Look for other bidi parts on the same visual line
  6326. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6327. if (res) { return res }
  6328. // Case 3b: Look for other bidi parts on the next visual line
  6329. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6330. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6331. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6332. if (res) { return res }
  6333. }
  6334. // Case 4: Nowhere to move
  6335. return null
  6336. }
  6337. // Commands are parameter-less actions that can be performed on an
  6338. // editor, mostly used for keybindings.
  6339. var commands = {
  6340. selectAll: selectAll,
  6341. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6342. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6343. if (range.empty()) {
  6344. var len = getLine(cm.doc, range.head.line).text.length;
  6345. if (range.head.ch == len && range.head.line < cm.lastLine())
  6346. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6347. else
  6348. { return {from: range.head, to: Pos(range.head.line, len)} }
  6349. } else {
  6350. return {from: range.from(), to: range.to()}
  6351. }
  6352. }); },
  6353. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6354. from: Pos(range.from().line, 0),
  6355. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6356. }); }); },
  6357. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6358. from: Pos(range.from().line, 0), to: range.from()
  6359. }); }); },
  6360. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6361. var top = cm.charCoords(range.head, "div").top + 5;
  6362. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6363. return {from: leftPos, to: range.from()}
  6364. }); },
  6365. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6366. var top = cm.charCoords(range.head, "div").top + 5;
  6367. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6368. return {from: range.from(), to: rightPos }
  6369. }); },
  6370. undo: function (cm) { return cm.undo(); },
  6371. redo: function (cm) { return cm.redo(); },
  6372. undoSelection: function (cm) { return cm.undoSelection(); },
  6373. redoSelection: function (cm) { return cm.redoSelection(); },
  6374. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6375. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6376. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6377. {origin: "+move", bias: 1}
  6378. ); },
  6379. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6380. {origin: "+move", bias: 1}
  6381. ); },
  6382. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6383. {origin: "+move", bias: -1}
  6384. ); },
  6385. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6386. var top = cm.cursorCoords(range.head, "div").top + 5;
  6387. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6388. }, sel_move); },
  6389. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6390. var top = cm.cursorCoords(range.head, "div").top + 5;
  6391. return cm.coordsChar({left: 0, top: top}, "div")
  6392. }, sel_move); },
  6393. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6394. var top = cm.cursorCoords(range.head, "div").top + 5;
  6395. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6396. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6397. return pos
  6398. }, sel_move); },
  6399. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6400. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6401. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6402. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6403. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6404. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6405. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6406. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6407. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6408. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6409. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6410. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6411. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6412. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6413. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6414. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6415. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6416. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6417. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6418. indentMore: function (cm) { return cm.indentSelection("add"); },
  6419. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6420. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6421. insertSoftTab: function (cm) {
  6422. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6423. for (var i = 0; i < ranges.length; i++) {
  6424. var pos = ranges[i].from();
  6425. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6426. spaces.push(spaceStr(tabSize - col % tabSize));
  6427. }
  6428. cm.replaceSelections(spaces);
  6429. },
  6430. defaultTab: function (cm) {
  6431. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6432. else { cm.execCommand("insertTab"); }
  6433. },
  6434. // Swap the two chars left and right of each selection's head.
  6435. // Move cursor behind the two swapped characters afterwards.
  6436. //
  6437. // Doesn't consider line feeds a character.
  6438. // Doesn't scan more than one line above to find a character.
  6439. // Doesn't do anything on an empty line.
  6440. // Doesn't do anything with non-empty selections.
  6441. transposeChars: function (cm) { return runInOp(cm, function () {
  6442. var ranges = cm.listSelections(), newSel = [];
  6443. for (var i = 0; i < ranges.length; i++) {
  6444. if (!ranges[i].empty()) { continue }
  6445. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6446. if (line) {
  6447. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6448. if (cur.ch > 0) {
  6449. cur = new Pos(cur.line, cur.ch + 1);
  6450. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6451. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6452. } else if (cur.line > cm.doc.first) {
  6453. var prev = getLine(cm.doc, cur.line - 1).text;
  6454. if (prev) {
  6455. cur = new Pos(cur.line, 1);
  6456. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6457. prev.charAt(prev.length - 1),
  6458. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6459. }
  6460. }
  6461. }
  6462. newSel.push(new Range(cur, cur));
  6463. }
  6464. cm.setSelections(newSel);
  6465. }); },
  6466. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6467. var sels = cm.listSelections();
  6468. for (var i = sels.length - 1; i >= 0; i--)
  6469. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6470. sels = cm.listSelections();
  6471. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6472. { cm.indentLine(sels[i$1].from().line, null, true); }
  6473. ensureCursorVisible(cm);
  6474. }); },
  6475. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6476. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6477. };
  6478. function lineStart(cm, lineN) {
  6479. var line = getLine(cm.doc, lineN);
  6480. var visual = visualLine(line);
  6481. if (visual != line) { lineN = lineNo(visual); }
  6482. return endOfLine(true, cm, visual, lineN, 1)
  6483. }
  6484. function lineEnd(cm, lineN) {
  6485. var line = getLine(cm.doc, lineN);
  6486. var visual = visualLineEnd(line);
  6487. if (visual != line) { lineN = lineNo(visual); }
  6488. return endOfLine(true, cm, line, lineN, -1)
  6489. }
  6490. function lineStartSmart(cm, pos) {
  6491. var start = lineStart(cm, pos.line);
  6492. var line = getLine(cm.doc, start.line);
  6493. var order = getOrder(line, cm.doc.direction);
  6494. if (!order || order[0].level == 0) {
  6495. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6496. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6497. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6498. }
  6499. return start
  6500. }
  6501. // Run a handler that was bound to a key.
  6502. function doHandleBinding(cm, bound, dropShift) {
  6503. if (typeof bound == "string") {
  6504. bound = commands[bound];
  6505. if (!bound) { return false }
  6506. }
  6507. // Ensure previous input has been read, so that the handler sees a
  6508. // consistent view of the document
  6509. cm.display.input.ensurePolled();
  6510. var prevShift = cm.display.shift, done = false;
  6511. try {
  6512. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6513. if (dropShift) { cm.display.shift = false; }
  6514. done = bound(cm) != Pass;
  6515. } finally {
  6516. cm.display.shift = prevShift;
  6517. cm.state.suppressEdits = false;
  6518. }
  6519. return done
  6520. }
  6521. function lookupKeyForEditor(cm, name, handle) {
  6522. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6523. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6524. if (result) { return result }
  6525. }
  6526. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6527. || lookupKey(name, cm.options.keyMap, handle, cm)
  6528. }
  6529. // Note that, despite the name, this function is also used to check
  6530. // for bound mouse clicks.
  6531. var stopSeq = new Delayed;
  6532. function dispatchKey(cm, name, e, handle) {
  6533. var seq = cm.state.keySeq;
  6534. if (seq) {
  6535. if (isModifierKey(name)) { return "handled" }
  6536. if (/\'$/.test(name))
  6537. { cm.state.keySeq = null; }
  6538. else
  6539. { stopSeq.set(50, function () {
  6540. if (cm.state.keySeq == seq) {
  6541. cm.state.keySeq = null;
  6542. cm.display.input.reset();
  6543. }
  6544. }); }
  6545. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6546. }
  6547. return dispatchKeyInner(cm, name, e, handle)
  6548. }
  6549. function dispatchKeyInner(cm, name, e, handle) {
  6550. var result = lookupKeyForEditor(cm, name, handle);
  6551. if (result == "multi")
  6552. { cm.state.keySeq = name; }
  6553. if (result == "handled")
  6554. { signalLater(cm, "keyHandled", cm, name, e); }
  6555. if (result == "handled" || result == "multi") {
  6556. e_preventDefault(e);
  6557. restartBlink(cm);
  6558. }
  6559. return !!result
  6560. }
  6561. // Handle a key from the keydown event.
  6562. function handleKeyBinding(cm, e) {
  6563. var name = keyName(e, true);
  6564. if (!name) { return false }
  6565. if (e.shiftKey && !cm.state.keySeq) {
  6566. // First try to resolve full name (including 'Shift-'). Failing
  6567. // that, see if there is a cursor-motion command (starting with
  6568. // 'go') bound to the keyname without 'Shift-'.
  6569. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6570. || dispatchKey(cm, name, e, function (b) {
  6571. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6572. { return doHandleBinding(cm, b) }
  6573. })
  6574. } else {
  6575. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6576. }
  6577. }
  6578. // Handle a key from the keypress event
  6579. function handleCharBinding(cm, e, ch) {
  6580. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6581. }
  6582. var lastStoppedKey = null;
  6583. function onKeyDown(e) {
  6584. var cm = this;
  6585. if (e.target && e.target != cm.display.input.getField()) { return }
  6586. cm.curOp.focus = activeElt(doc(cm));
  6587. if (signalDOMEvent(cm, e)) { return }
  6588. // IE does strange things with escape.
  6589. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6590. var code = e.keyCode;
  6591. cm.display.shift = code == 16 || e.shiftKey;
  6592. var handled = handleKeyBinding(cm, e);
  6593. if (presto) {
  6594. lastStoppedKey = handled ? code : null;
  6595. // Opera has no cut event... we try to at least catch the key combo
  6596. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6597. { cm.replaceSelection("", null, "cut"); }
  6598. }
  6599. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6600. { document.execCommand("cut"); }
  6601. // Turn mouse into crosshair when Alt is held on Mac.
  6602. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6603. { showCrossHair(cm); }
  6604. }
  6605. function showCrossHair(cm) {
  6606. var lineDiv = cm.display.lineDiv;
  6607. addClass(lineDiv, "CodeMirror-crosshair");
  6608. function up(e) {
  6609. if (e.keyCode == 18 || !e.altKey) {
  6610. rmClass(lineDiv, "CodeMirror-crosshair");
  6611. off(document, "keyup", up);
  6612. off(document, "mouseover", up);
  6613. }
  6614. }
  6615. on(document, "keyup", up);
  6616. on(document, "mouseover", up);
  6617. }
  6618. function onKeyUp(e) {
  6619. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6620. signalDOMEvent(this, e);
  6621. }
  6622. function onKeyPress(e) {
  6623. var cm = this;
  6624. if (e.target && e.target != cm.display.input.getField()) { return }
  6625. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6626. var keyCode = e.keyCode, charCode = e.charCode;
  6627. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6628. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6629. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6630. // Some browsers fire keypress events for backspace
  6631. if (ch == "\x08") { return }
  6632. if (handleCharBinding(cm, e, ch)) { return }
  6633. cm.display.input.onKeyPress(e);
  6634. }
  6635. var DOUBLECLICK_DELAY = 400;
  6636. var PastClick = function(time, pos, button) {
  6637. this.time = time;
  6638. this.pos = pos;
  6639. this.button = button;
  6640. };
  6641. PastClick.prototype.compare = function (time, pos, button) {
  6642. return this.time + DOUBLECLICK_DELAY > time &&
  6643. cmp(pos, this.pos) == 0 && button == this.button
  6644. };
  6645. var lastClick, lastDoubleClick;
  6646. function clickRepeat(pos, button) {
  6647. var now = +new Date;
  6648. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6649. lastClick = lastDoubleClick = null;
  6650. return "triple"
  6651. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6652. lastDoubleClick = new PastClick(now, pos, button);
  6653. lastClick = null;
  6654. return "double"
  6655. } else {
  6656. lastClick = new PastClick(now, pos, button);
  6657. lastDoubleClick = null;
  6658. return "single"
  6659. }
  6660. }
  6661. // A mouse down can be a single click, double click, triple click,
  6662. // start of selection drag, start of text drag, new cursor
  6663. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6664. // middle-click-paste. Or it might be a click on something we should
  6665. // not interfere with, such as a scrollbar or widget.
  6666. function onMouseDown(e) {
  6667. var cm = this, display = cm.display;
  6668. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6669. display.input.ensurePolled();
  6670. display.shift = e.shiftKey;
  6671. if (eventInWidget(display, e)) {
  6672. if (!webkit) {
  6673. // Briefly turn off draggability, to allow widgets to do
  6674. // normal dragging things.
  6675. display.scroller.draggable = false;
  6676. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6677. }
  6678. return
  6679. }
  6680. if (clickInGutter(cm, e)) { return }
  6681. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6682. win(cm).focus();
  6683. // #3261: make sure, that we're not starting a second selection
  6684. if (button == 1 && cm.state.selectingText)
  6685. { cm.state.selectingText(e); }
  6686. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6687. if (button == 1) {
  6688. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6689. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6690. } else if (button == 2) {
  6691. if (pos) { extendSelection(cm.doc, pos); }
  6692. setTimeout(function () { return display.input.focus(); }, 20);
  6693. } else if (button == 3) {
  6694. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6695. else { delayBlurEvent(cm); }
  6696. }
  6697. }
  6698. function handleMappedButton(cm, button, pos, repeat, event) {
  6699. var name = "Click";
  6700. if (repeat == "double") { name = "Double" + name; }
  6701. else if (repeat == "triple") { name = "Triple" + name; }
  6702. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6703. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6704. if (typeof bound == "string") { bound = commands[bound]; }
  6705. if (!bound) { return false }
  6706. var done = false;
  6707. try {
  6708. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6709. done = bound(cm, pos) != Pass;
  6710. } finally {
  6711. cm.state.suppressEdits = false;
  6712. }
  6713. return done
  6714. })
  6715. }
  6716. function configureMouse(cm, repeat, event) {
  6717. var option = cm.getOption("configureMouse");
  6718. var value = option ? option(cm, repeat, event) : {};
  6719. if (value.unit == null) {
  6720. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6721. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6722. }
  6723. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6724. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6725. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6726. return value
  6727. }
  6728. function leftButtonDown(cm, pos, repeat, event) {
  6729. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6730. else { cm.curOp.focus = activeElt(doc(cm)); }
  6731. var behavior = configureMouse(cm, repeat, event);
  6732. var sel = cm.doc.sel, contained;
  6733. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6734. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6735. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6736. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6737. { leftButtonStartDrag(cm, event, pos, behavior); }
  6738. else
  6739. { leftButtonSelect(cm, event, pos, behavior); }
  6740. }
  6741. // Start a text drag. When it ends, see if any dragging actually
  6742. // happen, and treat as a click if it didn't.
  6743. function leftButtonStartDrag(cm, event, pos, behavior) {
  6744. var display = cm.display, moved = false;
  6745. var dragEnd = operation(cm, function (e) {
  6746. if (webkit) { display.scroller.draggable = false; }
  6747. cm.state.draggingText = false;
  6748. if (cm.state.delayingBlurEvent) {
  6749. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6750. else { delayBlurEvent(cm); }
  6751. }
  6752. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6753. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6754. off(display.scroller, "dragstart", dragStart);
  6755. off(display.scroller, "drop", dragEnd);
  6756. if (!moved) {
  6757. e_preventDefault(e);
  6758. if (!behavior.addNew)
  6759. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6760. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6761. if ((webkit && !safari) || ie && ie_version == 9)
  6762. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  6763. else
  6764. { display.input.focus(); }
  6765. }
  6766. });
  6767. var mouseMove = function(e2) {
  6768. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6769. };
  6770. var dragStart = function () { return moved = true; };
  6771. // Let the drag handler handle this.
  6772. if (webkit) { display.scroller.draggable = true; }
  6773. cm.state.draggingText = dragEnd;
  6774. dragEnd.copy = !behavior.moveOnDrag;
  6775. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6776. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6777. on(display.scroller, "dragstart", dragStart);
  6778. on(display.scroller, "drop", dragEnd);
  6779. cm.state.delayingBlurEvent = true;
  6780. setTimeout(function () { return display.input.focus(); }, 20);
  6781. // IE's approach to draggable
  6782. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6783. }
  6784. function rangeForUnit(cm, pos, unit) {
  6785. if (unit == "char") { return new Range(pos, pos) }
  6786. if (unit == "word") { return cm.findWordAt(pos) }
  6787. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6788. var result = unit(cm, pos);
  6789. return new Range(result.from, result.to)
  6790. }
  6791. // Normal selection, as opposed to text dragging.
  6792. function leftButtonSelect(cm, event, start, behavior) {
  6793. if (ie) { delayBlurEvent(cm); }
  6794. var display = cm.display, doc$1 = cm.doc;
  6795. e_preventDefault(event);
  6796. var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges;
  6797. if (behavior.addNew && !behavior.extend) {
  6798. ourIndex = doc$1.sel.contains(start);
  6799. if (ourIndex > -1)
  6800. { ourRange = ranges[ourIndex]; }
  6801. else
  6802. { ourRange = new Range(start, start); }
  6803. } else {
  6804. ourRange = doc$1.sel.primary();
  6805. ourIndex = doc$1.sel.primIndex;
  6806. }
  6807. if (behavior.unit == "rectangle") {
  6808. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6809. start = posFromMouse(cm, event, true, true);
  6810. ourIndex = -1;
  6811. } else {
  6812. var range = rangeForUnit(cm, start, behavior.unit);
  6813. if (behavior.extend)
  6814. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6815. else
  6816. { ourRange = range; }
  6817. }
  6818. if (!behavior.addNew) {
  6819. ourIndex = 0;
  6820. setSelection(doc$1, new Selection([ourRange], 0), sel_mouse);
  6821. startSel = doc$1.sel;
  6822. } else if (ourIndex == -1) {
  6823. ourIndex = ranges.length;
  6824. setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6825. {scroll: false, origin: "*mouse"});
  6826. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6827. setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6828. {scroll: false, origin: "*mouse"});
  6829. startSel = doc$1.sel;
  6830. } else {
  6831. replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse);
  6832. }
  6833. var lastPos = start;
  6834. function extendTo(pos) {
  6835. if (cmp(lastPos, pos) == 0) { return }
  6836. lastPos = pos;
  6837. if (behavior.unit == "rectangle") {
  6838. var ranges = [], tabSize = cm.options.tabSize;
  6839. var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize);
  6840. var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize);
  6841. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6842. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6843. line <= end; line++) {
  6844. var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize);
  6845. if (left == right)
  6846. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6847. else if (text.length > leftPos)
  6848. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6849. }
  6850. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6851. setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6852. {origin: "*mouse", scroll: false});
  6853. cm.scrollIntoView(pos);
  6854. } else {
  6855. var oldRange = ourRange;
  6856. var range = rangeForUnit(cm, pos, behavior.unit);
  6857. var anchor = oldRange.anchor, head;
  6858. if (cmp(range.anchor, anchor) > 0) {
  6859. head = range.head;
  6860. anchor = minPos(oldRange.from(), range.anchor);
  6861. } else {
  6862. head = range.anchor;
  6863. anchor = maxPos(oldRange.to(), range.head);
  6864. }
  6865. var ranges$1 = startSel.ranges.slice(0);
  6866. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head));
  6867. setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6868. }
  6869. }
  6870. var editorSize = display.wrapper.getBoundingClientRect();
  6871. // Used to ensure timeout re-tries don't fire when another extend
  6872. // happened in the meantime (clearTimeout isn't reliable -- at
  6873. // least on Chrome, the timeouts still happen even when cleared,
  6874. // if the clear happens after their scheduled firing time).
  6875. var counter = 0;
  6876. function extend(e) {
  6877. var curCount = ++counter;
  6878. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6879. if (!cur) { return }
  6880. if (cmp(cur, lastPos) != 0) {
  6881. cm.curOp.focus = activeElt(doc(cm));
  6882. extendTo(cur);
  6883. var visible = visibleLines(display, doc$1);
  6884. if (cur.line >= visible.to || cur.line < visible.from)
  6885. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6886. } else {
  6887. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6888. if (outside) { setTimeout(operation(cm, function () {
  6889. if (counter != curCount) { return }
  6890. display.scroller.scrollTop += outside;
  6891. extend(e);
  6892. }), 50); }
  6893. }
  6894. }
  6895. function done(e) {
  6896. cm.state.selectingText = false;
  6897. counter = Infinity;
  6898. // If e is null or undefined we interpret this as someone trying
  6899. // to explicitly cancel the selection rather than the user
  6900. // letting go of the mouse button.
  6901. if (e) {
  6902. e_preventDefault(e);
  6903. display.input.focus();
  6904. }
  6905. off(display.wrapper.ownerDocument, "mousemove", move);
  6906. off(display.wrapper.ownerDocument, "mouseup", up);
  6907. doc$1.history.lastSelOrigin = null;
  6908. }
  6909. var move = operation(cm, function (e) {
  6910. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6911. else { extend(e); }
  6912. });
  6913. var up = operation(cm, done);
  6914. cm.state.selectingText = up;
  6915. on(display.wrapper.ownerDocument, "mousemove", move);
  6916. on(display.wrapper.ownerDocument, "mouseup", up);
  6917. }
  6918. // Used when mouse-selecting to adjust the anchor to the proper side
  6919. // of a bidi jump depending on the visual position of the head.
  6920. function bidiSimplify(cm, range) {
  6921. var anchor = range.anchor;
  6922. var head = range.head;
  6923. var anchorLine = getLine(cm.doc, anchor.line);
  6924. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6925. var order = getOrder(anchorLine);
  6926. if (!order) { return range }
  6927. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6928. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6929. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6930. if (boundary == 0 || boundary == order.length) { return range }
  6931. // Compute the relative visual position of the head compared to the
  6932. // anchor (<0 is to the left, >0 to the right)
  6933. var leftSide;
  6934. if (head.line != anchor.line) {
  6935. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6936. } else {
  6937. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6938. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6939. if (headIndex == boundary - 1 || headIndex == boundary)
  6940. { leftSide = dir < 0; }
  6941. else
  6942. { leftSide = dir > 0; }
  6943. }
  6944. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6945. var from = leftSide == (usePart.level == 1);
  6946. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6947. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6948. }
  6949. // Determines whether an event happened in the gutter, and fires the
  6950. // handlers for the corresponding event.
  6951. function gutterEvent(cm, e, type, prevent) {
  6952. var mX, mY;
  6953. if (e.touches) {
  6954. mX = e.touches[0].clientX;
  6955. mY = e.touches[0].clientY;
  6956. } else {
  6957. try { mX = e.clientX; mY = e.clientY; }
  6958. catch(e$1) { return false }
  6959. }
  6960. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6961. if (prevent) { e_preventDefault(e); }
  6962. var display = cm.display;
  6963. var lineBox = display.lineDiv.getBoundingClientRect();
  6964. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6965. mY -= lineBox.top - display.viewOffset;
  6966. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6967. var g = display.gutters.childNodes[i];
  6968. if (g && g.getBoundingClientRect().right >= mX) {
  6969. var line = lineAtHeight(cm.doc, mY);
  6970. var gutter = cm.display.gutterSpecs[i];
  6971. signal(cm, type, cm, line, gutter.className, e);
  6972. return e_defaultPrevented(e)
  6973. }
  6974. }
  6975. }
  6976. function clickInGutter(cm, e) {
  6977. return gutterEvent(cm, e, "gutterClick", true)
  6978. }
  6979. // CONTEXT MENU HANDLING
  6980. // To make the context menu work, we need to briefly unhide the
  6981. // textarea (making it as unobtrusive as possible) to let the
  6982. // right-click take effect on it.
  6983. function onContextMenu(cm, e) {
  6984. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6985. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6986. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6987. }
  6988. function contextMenuInGutter(cm, e) {
  6989. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6990. return gutterEvent(cm, e, "gutterContextMenu", false)
  6991. }
  6992. function themeChanged(cm) {
  6993. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6994. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6995. clearCaches(cm);
  6996. }
  6997. var Init = {toString: function(){return "CodeMirror.Init"}};
  6998. var defaults = {};
  6999. var optionHandlers = {};
  7000. function defineOptions(CodeMirror) {
  7001. var optionHandlers = CodeMirror.optionHandlers;
  7002. function option(name, deflt, handle, notOnInit) {
  7003. CodeMirror.defaults[name] = deflt;
  7004. if (handle) { optionHandlers[name] =
  7005. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  7006. }
  7007. CodeMirror.defineOption = option;
  7008. // Passed to option handlers when there is no old value.
  7009. CodeMirror.Init = Init;
  7010. // These two are, on init, called from the constructor because they
  7011. // have to be initialized before the editor can start at all.
  7012. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  7013. option("mode", null, function (cm, val) {
  7014. cm.doc.modeOption = val;
  7015. loadMode(cm);
  7016. }, true);
  7017. option("indentUnit", 2, loadMode, true);
  7018. option("indentWithTabs", false);
  7019. option("smartIndent", true);
  7020. option("tabSize", 4, function (cm) {
  7021. resetModeState(cm);
  7022. clearCaches(cm);
  7023. regChange(cm);
  7024. }, true);
  7025. option("lineSeparator", null, function (cm, val) {
  7026. cm.doc.lineSep = val;
  7027. if (!val) { return }
  7028. var newBreaks = [], lineNo = cm.doc.first;
  7029. cm.doc.iter(function (line) {
  7030. for (var pos = 0;;) {
  7031. var found = line.text.indexOf(val, pos);
  7032. if (found == -1) { break }
  7033. pos = found + val.length;
  7034. newBreaks.push(Pos(lineNo, found));
  7035. }
  7036. lineNo++;
  7037. });
  7038. for (var i = newBreaks.length - 1; i >= 0; i--)
  7039. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7040. });
  7041. 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) {
  7042. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7043. if (old != Init) { cm.refresh(); }
  7044. });
  7045. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7046. option("electricChars", true);
  7047. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7048. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7049. }, true);
  7050. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7051. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7052. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7053. option("rtlMoveVisually", !windows);
  7054. option("wholeLineUpdateBefore", true);
  7055. option("theme", "default", function (cm) {
  7056. themeChanged(cm);
  7057. updateGutters(cm);
  7058. }, true);
  7059. option("keyMap", "default", function (cm, val, old) {
  7060. var next = getKeyMap(val);
  7061. var prev = old != Init && getKeyMap(old);
  7062. if (prev && prev.detach) { prev.detach(cm, next); }
  7063. if (next.attach) { next.attach(cm, prev || null); }
  7064. });
  7065. option("extraKeys", null);
  7066. option("configureMouse", null);
  7067. option("lineWrapping", false, wrappingChanged, true);
  7068. option("gutters", [], function (cm, val) {
  7069. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7070. updateGutters(cm);
  7071. }, true);
  7072. option("fixedGutter", true, function (cm, val) {
  7073. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7074. cm.refresh();
  7075. }, true);
  7076. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7077. option("scrollbarStyle", "native", function (cm) {
  7078. initScrollbars(cm);
  7079. updateScrollbars(cm);
  7080. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7081. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7082. }, true);
  7083. option("lineNumbers", false, function (cm, val) {
  7084. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7085. updateGutters(cm);
  7086. }, true);
  7087. option("firstLineNumber", 1, updateGutters, true);
  7088. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7089. option("showCursorWhenSelecting", false, updateSelection, true);
  7090. option("resetSelectionOnContextMenu", true);
  7091. option("lineWiseCopyCut", true);
  7092. option("pasteLinesPerSelection", true);
  7093. option("selectionsMayTouch", false);
  7094. option("readOnly", false, function (cm, val) {
  7095. if (val == "nocursor") {
  7096. onBlur(cm);
  7097. cm.display.input.blur();
  7098. }
  7099. cm.display.input.readOnlyChanged(val);
  7100. });
  7101. option("screenReaderLabel", null, function (cm, val) {
  7102. val = (val === '') ? null : val;
  7103. cm.display.input.screenReaderLabelChanged(val);
  7104. });
  7105. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7106. option("dragDrop", true, dragDropChanged);
  7107. option("allowDropFileTypes", null);
  7108. option("cursorBlinkRate", 530);
  7109. option("cursorScrollMargin", 0);
  7110. option("cursorHeight", 1, updateSelection, true);
  7111. option("singleCursorHeightPerLine", true, updateSelection, true);
  7112. option("workTime", 100);
  7113. option("workDelay", 100);
  7114. option("flattenSpans", true, resetModeState, true);
  7115. option("addModeClass", false, resetModeState, true);
  7116. option("pollInterval", 100);
  7117. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7118. option("historyEventDelay", 1250);
  7119. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7120. option("maxHighlightLength", 10000, resetModeState, true);
  7121. option("moveInputWithCursor", true, function (cm, val) {
  7122. if (!val) { cm.display.input.resetPosition(); }
  7123. });
  7124. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7125. option("autofocus", null);
  7126. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7127. option("phrases", null);
  7128. }
  7129. function dragDropChanged(cm, value, old) {
  7130. var wasOn = old && old != Init;
  7131. if (!value != !wasOn) {
  7132. var funcs = cm.display.dragFunctions;
  7133. var toggle = value ? on : off;
  7134. toggle(cm.display.scroller, "dragstart", funcs.start);
  7135. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7136. toggle(cm.display.scroller, "dragover", funcs.over);
  7137. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7138. toggle(cm.display.scroller, "drop", funcs.drop);
  7139. }
  7140. }
  7141. function wrappingChanged(cm) {
  7142. if (cm.options.lineWrapping) {
  7143. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7144. cm.display.sizer.style.minWidth = "";
  7145. cm.display.sizerWidth = null;
  7146. } else {
  7147. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7148. findMaxLine(cm);
  7149. }
  7150. estimateLineHeights(cm);
  7151. regChange(cm);
  7152. clearCaches(cm);
  7153. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7154. }
  7155. // A CodeMirror instance represents an editor. This is the object
  7156. // that user code is usually dealing with.
  7157. function CodeMirror(place, options) {
  7158. var this$1 = this;
  7159. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7160. this.options = options = options ? copyObj(options) : {};
  7161. // Determine effective options based on given values and defaults.
  7162. copyObj(defaults, options, false);
  7163. var doc = options.value;
  7164. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7165. else if (options.mode) { doc.modeOption = options.mode; }
  7166. this.doc = doc;
  7167. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7168. var display = this.display = new Display(place, doc, input, options);
  7169. display.wrapper.CodeMirror = this;
  7170. themeChanged(this);
  7171. if (options.lineWrapping)
  7172. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7173. initScrollbars(this);
  7174. this.state = {
  7175. keyMaps: [], // stores maps added by addKeyMap
  7176. overlays: [], // highlighting overlays, as added by addOverlay
  7177. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7178. overwrite: false,
  7179. delayingBlurEvent: false,
  7180. focused: false,
  7181. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7182. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7183. selectingText: false,
  7184. draggingText: false,
  7185. highlight: new Delayed(), // stores highlight worker timeout
  7186. keySeq: null, // Unfinished key sequence
  7187. specialChars: null
  7188. };
  7189. if (options.autofocus && !mobile) { display.input.focus(); }
  7190. // Override magic textarea content restore that IE sometimes does
  7191. // on our hidden textarea on reload
  7192. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7193. registerEventHandlers(this);
  7194. ensureGlobalHandlers();
  7195. startOperation(this);
  7196. this.curOp.forceUpdate = true;
  7197. attachDoc(this, doc);
  7198. if ((options.autofocus && !mobile) || this.hasFocus())
  7199. { setTimeout(function () {
  7200. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7201. }, 20); }
  7202. else
  7203. { onBlur(this); }
  7204. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7205. { optionHandlers[opt](this, options[opt], Init); } }
  7206. maybeUpdateLineNumberWidth(this);
  7207. if (options.finishInit) { options.finishInit(this); }
  7208. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7209. endOperation(this);
  7210. // Suppress optimizelegibility in Webkit, since it breaks text
  7211. // measuring on line wrapping boundaries.
  7212. if (webkit && options.lineWrapping &&
  7213. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7214. { display.lineDiv.style.textRendering = "auto"; }
  7215. }
  7216. // The default configuration options.
  7217. CodeMirror.defaults = defaults;
  7218. // Functions to run when options are changed.
  7219. CodeMirror.optionHandlers = optionHandlers;
  7220. // Attach the necessary event handlers when initializing the editor
  7221. function registerEventHandlers(cm) {
  7222. var d = cm.display;
  7223. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7224. // Older IE's will not fire a second mousedown for a double click
  7225. if (ie && ie_version < 11)
  7226. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7227. if (signalDOMEvent(cm, e)) { return }
  7228. var pos = posFromMouse(cm, e);
  7229. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7230. e_preventDefault(e);
  7231. var word = cm.findWordAt(pos);
  7232. extendSelection(cm.doc, word.anchor, word.head);
  7233. })); }
  7234. else
  7235. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7236. // Some browsers fire contextmenu *after* opening the menu, at
  7237. // which point we can't mess with it anymore. Context menu is
  7238. // handled in onMouseDown for these browsers.
  7239. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7240. on(d.input.getField(), "contextmenu", function (e) {
  7241. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7242. });
  7243. // Used to suppress mouse event handling when a touch happens
  7244. var touchFinished, prevTouch = {end: 0};
  7245. function finishTouch() {
  7246. if (d.activeTouch) {
  7247. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7248. prevTouch = d.activeTouch;
  7249. prevTouch.end = +new Date;
  7250. }
  7251. }
  7252. function isMouseLikeTouchEvent(e) {
  7253. if (e.touches.length != 1) { return false }
  7254. var touch = e.touches[0];
  7255. return touch.radiusX <= 1 && touch.radiusY <= 1
  7256. }
  7257. function farAway(touch, other) {
  7258. if (other.left == null) { return true }
  7259. var dx = other.left - touch.left, dy = other.top - touch.top;
  7260. return dx * dx + dy * dy > 20 * 20
  7261. }
  7262. on(d.scroller, "touchstart", function (e) {
  7263. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7264. d.input.ensurePolled();
  7265. clearTimeout(touchFinished);
  7266. var now = +new Date;
  7267. d.activeTouch = {start: now, moved: false,
  7268. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7269. if (e.touches.length == 1) {
  7270. d.activeTouch.left = e.touches[0].pageX;
  7271. d.activeTouch.top = e.touches[0].pageY;
  7272. }
  7273. }
  7274. });
  7275. on(d.scroller, "touchmove", function () {
  7276. if (d.activeTouch) { d.activeTouch.moved = true; }
  7277. });
  7278. on(d.scroller, "touchend", function (e) {
  7279. var touch = d.activeTouch;
  7280. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7281. !touch.moved && new Date - touch.start < 300) {
  7282. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7283. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7284. { range = new Range(pos, pos); }
  7285. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7286. { range = cm.findWordAt(pos); }
  7287. else // Triple tap
  7288. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7289. cm.setSelection(range.anchor, range.head);
  7290. cm.focus();
  7291. e_preventDefault(e);
  7292. }
  7293. finishTouch();
  7294. });
  7295. on(d.scroller, "touchcancel", finishTouch);
  7296. // Sync scrolling between fake scrollbars and real scrollable
  7297. // area, ensure viewport is updated when scrolling.
  7298. on(d.scroller, "scroll", function () {
  7299. if (d.scroller.clientHeight) {
  7300. updateScrollTop(cm, d.scroller.scrollTop);
  7301. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7302. signal(cm, "scroll", cm);
  7303. }
  7304. });
  7305. // Listen to wheel events in order to try and update the viewport on time.
  7306. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7307. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7308. // Prevent wrapper from ever scrolling
  7309. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7310. d.dragFunctions = {
  7311. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7312. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7313. start: function (e) { return onDragStart(cm, e); },
  7314. drop: operation(cm, onDrop),
  7315. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7316. };
  7317. var inp = d.input.getField();
  7318. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7319. on(inp, "keydown", operation(cm, onKeyDown));
  7320. on(inp, "keypress", operation(cm, onKeyPress));
  7321. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7322. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7323. }
  7324. var initHooks = [];
  7325. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7326. // Indent the given line. The how parameter can be "smart",
  7327. // "add"/null, "subtract", or "prev". When aggressive is false
  7328. // (typically set to true for forced single-line indents), empty
  7329. // lines are not indented, and places where the mode returns Pass
  7330. // are left alone.
  7331. function indentLine(cm, n, how, aggressive) {
  7332. var doc = cm.doc, state;
  7333. if (how == null) { how = "add"; }
  7334. if (how == "smart") {
  7335. // Fall back to "prev" when the mode doesn't have an indentation
  7336. // method.
  7337. if (!doc.mode.indent) { how = "prev"; }
  7338. else { state = getContextBefore(cm, n).state; }
  7339. }
  7340. var tabSize = cm.options.tabSize;
  7341. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7342. if (line.stateAfter) { line.stateAfter = null; }
  7343. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7344. if (!aggressive && !/\S/.test(line.text)) {
  7345. indentation = 0;
  7346. how = "not";
  7347. } else if (how == "smart") {
  7348. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7349. if (indentation == Pass || indentation > 150) {
  7350. if (!aggressive) { return }
  7351. how = "prev";
  7352. }
  7353. }
  7354. if (how == "prev") {
  7355. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7356. else { indentation = 0; }
  7357. } else if (how == "add") {
  7358. indentation = curSpace + cm.options.indentUnit;
  7359. } else if (how == "subtract") {
  7360. indentation = curSpace - cm.options.indentUnit;
  7361. } else if (typeof how == "number") {
  7362. indentation = curSpace + how;
  7363. }
  7364. indentation = Math.max(0, indentation);
  7365. var indentString = "", pos = 0;
  7366. if (cm.options.indentWithTabs)
  7367. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7368. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7369. if (indentString != curSpaceString) {
  7370. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7371. line.stateAfter = null;
  7372. return true
  7373. } else {
  7374. // Ensure that, if the cursor was in the whitespace at the start
  7375. // of the line, it is moved to the end of that space.
  7376. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7377. var range = doc.sel.ranges[i$1];
  7378. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7379. var pos$1 = Pos(n, curSpaceString.length);
  7380. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7381. break
  7382. }
  7383. }
  7384. }
  7385. }
  7386. // This will be set to a {lineWise: bool, text: [string]} object, so
  7387. // that, when pasting, we know what kind of selections the copied
  7388. // text was made out of.
  7389. var lastCopied = null;
  7390. function setLastCopied(newLastCopied) {
  7391. lastCopied = newLastCopied;
  7392. }
  7393. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7394. var doc = cm.doc;
  7395. cm.display.shift = false;
  7396. if (!sel) { sel = doc.sel; }
  7397. var recent = +new Date - 200;
  7398. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7399. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7400. // When pasting N lines into N selections, insert one line per selection
  7401. if (paste && sel.ranges.length > 1) {
  7402. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7403. if (sel.ranges.length % lastCopied.text.length == 0) {
  7404. multiPaste = [];
  7405. for (var i = 0; i < lastCopied.text.length; i++)
  7406. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7407. }
  7408. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7409. multiPaste = map(textLines, function (l) { return [l]; });
  7410. }
  7411. }
  7412. var updateInput = cm.curOp.updateInput;
  7413. // Normal behavior is to insert the new text into every selection
  7414. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7415. var range = sel.ranges[i$1];
  7416. var from = range.from(), to = range.to();
  7417. if (range.empty()) {
  7418. if (deleted && deleted > 0) // Handle deletion
  7419. { from = Pos(from.line, from.ch - deleted); }
  7420. else if (cm.state.overwrite && !paste) // Handle overwrite
  7421. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7422. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7423. { from = to = Pos(from.line, 0); }
  7424. }
  7425. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7426. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7427. makeChange(cm.doc, changeEvent);
  7428. signalLater(cm, "inputRead", cm, changeEvent);
  7429. }
  7430. if (inserted && !paste)
  7431. { triggerElectric(cm, inserted); }
  7432. ensureCursorVisible(cm);
  7433. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7434. cm.curOp.typing = true;
  7435. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7436. }
  7437. function handlePaste(e, cm) {
  7438. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7439. if (pasted) {
  7440. e.preventDefault();
  7441. if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
  7442. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7443. return true
  7444. }
  7445. }
  7446. function triggerElectric(cm, inserted) {
  7447. // When an 'electric' character is inserted, immediately trigger a reindent
  7448. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7449. var sel = cm.doc.sel;
  7450. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7451. var range = sel.ranges[i];
  7452. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7453. var mode = cm.getModeAt(range.head);
  7454. var indented = false;
  7455. if (mode.electricChars) {
  7456. for (var j = 0; j < mode.electricChars.length; j++)
  7457. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7458. indented = indentLine(cm, range.head.line, "smart");
  7459. break
  7460. } }
  7461. } else if (mode.electricInput) {
  7462. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7463. { indented = indentLine(cm, range.head.line, "smart"); }
  7464. }
  7465. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7466. }
  7467. }
  7468. function copyableRanges(cm) {
  7469. var text = [], ranges = [];
  7470. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7471. var line = cm.doc.sel.ranges[i].head.line;
  7472. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7473. ranges.push(lineRange);
  7474. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7475. }
  7476. return {text: text, ranges: ranges}
  7477. }
  7478. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7479. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  7480. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  7481. field.setAttribute("spellcheck", !!spellcheck);
  7482. }
  7483. function hiddenTextarea() {
  7484. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  7485. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7486. // The textarea is kept positioned near the cursor to prevent the
  7487. // fact that it'll be scrolled into view on input from scrolling
  7488. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7489. // very slow. So make the area wide instead.
  7490. if (webkit) { te.style.width = "1000px"; }
  7491. else { te.setAttribute("wrap", "off"); }
  7492. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7493. if (ios) { te.style.border = "1px solid black"; }
  7494. disableBrowserMagic(te);
  7495. return div
  7496. }
  7497. // The publicly visible API. Note that methodOp(f) means
  7498. // 'wrap f in an operation, performed on its `this` parameter'.
  7499. // This is not the complete set of editor methods. Most of the
  7500. // methods defined on the Doc type are also injected into
  7501. // CodeMirror.prototype, for backwards compatibility and
  7502. // convenience.
  7503. function addEditorMethods(CodeMirror) {
  7504. var optionHandlers = CodeMirror.optionHandlers;
  7505. var helpers = CodeMirror.helpers = {};
  7506. CodeMirror.prototype = {
  7507. constructor: CodeMirror,
  7508. focus: function(){win(this).focus(); this.display.input.focus();},
  7509. setOption: function(option, value) {
  7510. var options = this.options, old = options[option];
  7511. if (options[option] == value && option != "mode") { return }
  7512. options[option] = value;
  7513. if (optionHandlers.hasOwnProperty(option))
  7514. { operation(this, optionHandlers[option])(this, value, old); }
  7515. signal(this, "optionChange", this, option);
  7516. },
  7517. getOption: function(option) {return this.options[option]},
  7518. getDoc: function() {return this.doc},
  7519. addKeyMap: function(map, bottom) {
  7520. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7521. },
  7522. removeKeyMap: function(map) {
  7523. var maps = this.state.keyMaps;
  7524. for (var i = 0; i < maps.length; ++i)
  7525. { if (maps[i] == map || maps[i].name == map) {
  7526. maps.splice(i, 1);
  7527. return true
  7528. } }
  7529. },
  7530. addOverlay: methodOp(function(spec, options) {
  7531. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7532. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7533. insertSorted(this.state.overlays,
  7534. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7535. priority: (options && options.priority) || 0},
  7536. function (overlay) { return overlay.priority; });
  7537. this.state.modeGen++;
  7538. regChange(this);
  7539. }),
  7540. removeOverlay: methodOp(function(spec) {
  7541. var overlays = this.state.overlays;
  7542. for (var i = 0; i < overlays.length; ++i) {
  7543. var cur = overlays[i].modeSpec;
  7544. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7545. overlays.splice(i, 1);
  7546. this.state.modeGen++;
  7547. regChange(this);
  7548. return
  7549. }
  7550. }
  7551. }),
  7552. indentLine: methodOp(function(n, dir, aggressive) {
  7553. if (typeof dir != "string" && typeof dir != "number") {
  7554. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7555. else { dir = dir ? "add" : "subtract"; }
  7556. }
  7557. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7558. }),
  7559. indentSelection: methodOp(function(how) {
  7560. var ranges = this.doc.sel.ranges, end = -1;
  7561. for (var i = 0; i < ranges.length; i++) {
  7562. var range = ranges[i];
  7563. if (!range.empty()) {
  7564. var from = range.from(), to = range.to();
  7565. var start = Math.max(end, from.line);
  7566. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7567. for (var j = start; j < end; ++j)
  7568. { indentLine(this, j, how); }
  7569. var newRanges = this.doc.sel.ranges;
  7570. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7571. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7572. } else if (range.head.line > end) {
  7573. indentLine(this, range.head.line, how, true);
  7574. end = range.head.line;
  7575. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7576. }
  7577. }
  7578. }),
  7579. // Fetch the parser token for a given character. Useful for hacks
  7580. // that want to inspect the mode state (say, for completion).
  7581. getTokenAt: function(pos, precise) {
  7582. return takeToken(this, pos, precise)
  7583. },
  7584. getLineTokens: function(line, precise) {
  7585. return takeToken(this, Pos(line), precise, true)
  7586. },
  7587. getTokenTypeAt: function(pos) {
  7588. pos = clipPos(this.doc, pos);
  7589. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7590. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7591. var type;
  7592. if (ch == 0) { type = styles[2]; }
  7593. else { for (;;) {
  7594. var mid = (before + after) >> 1;
  7595. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7596. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7597. else { type = styles[mid * 2 + 2]; break }
  7598. } }
  7599. var cut = type ? type.indexOf("overlay ") : -1;
  7600. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7601. },
  7602. getModeAt: function(pos) {
  7603. var mode = this.doc.mode;
  7604. if (!mode.innerMode) { return mode }
  7605. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7606. },
  7607. getHelper: function(pos, type) {
  7608. return this.getHelpers(pos, type)[0]
  7609. },
  7610. getHelpers: function(pos, type) {
  7611. var found = [];
  7612. if (!helpers.hasOwnProperty(type)) { return found }
  7613. var help = helpers[type], mode = this.getModeAt(pos);
  7614. if (typeof mode[type] == "string") {
  7615. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7616. } else if (mode[type]) {
  7617. for (var i = 0; i < mode[type].length; i++) {
  7618. var val = help[mode[type][i]];
  7619. if (val) { found.push(val); }
  7620. }
  7621. } else if (mode.helperType && help[mode.helperType]) {
  7622. found.push(help[mode.helperType]);
  7623. } else if (help[mode.name]) {
  7624. found.push(help[mode.name]);
  7625. }
  7626. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7627. var cur = help._global[i$1];
  7628. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7629. { found.push(cur.val); }
  7630. }
  7631. return found
  7632. },
  7633. getStateAfter: function(line, precise) {
  7634. var doc = this.doc;
  7635. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7636. return getContextBefore(this, line + 1, precise).state
  7637. },
  7638. cursorCoords: function(start, mode) {
  7639. var pos, range = this.doc.sel.primary();
  7640. if (start == null) { pos = range.head; }
  7641. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7642. else { pos = start ? range.from() : range.to(); }
  7643. return cursorCoords(this, pos, mode || "page")
  7644. },
  7645. charCoords: function(pos, mode) {
  7646. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7647. },
  7648. coordsChar: function(coords, mode) {
  7649. coords = fromCoordSystem(this, coords, mode || "page");
  7650. return coordsChar(this, coords.left, coords.top)
  7651. },
  7652. lineAtHeight: function(height, mode) {
  7653. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7654. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7655. },
  7656. heightAtLine: function(line, mode, includeWidgets) {
  7657. var end = false, lineObj;
  7658. if (typeof line == "number") {
  7659. var last = this.doc.first + this.doc.size - 1;
  7660. if (line < this.doc.first) { line = this.doc.first; }
  7661. else if (line > last) { line = last; end = true; }
  7662. lineObj = getLine(this.doc, line);
  7663. } else {
  7664. lineObj = line;
  7665. }
  7666. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7667. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7668. },
  7669. defaultTextHeight: function() { return textHeight(this.display) },
  7670. defaultCharWidth: function() { return charWidth(this.display) },
  7671. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7672. addWidget: function(pos, node, scroll, vert, horiz) {
  7673. var display = this.display;
  7674. pos = cursorCoords(this, clipPos(this.doc, pos));
  7675. var top = pos.bottom, left = pos.left;
  7676. node.style.position = "absolute";
  7677. node.setAttribute("cm-ignore-events", "true");
  7678. this.display.input.setUneditable(node);
  7679. display.sizer.appendChild(node);
  7680. if (vert == "over") {
  7681. top = pos.top;
  7682. } else if (vert == "above" || vert == "near") {
  7683. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7684. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7685. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7686. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7687. { top = pos.top - node.offsetHeight; }
  7688. else if (pos.bottom + node.offsetHeight <= vspace)
  7689. { top = pos.bottom; }
  7690. if (left + node.offsetWidth > hspace)
  7691. { left = hspace - node.offsetWidth; }
  7692. }
  7693. node.style.top = top + "px";
  7694. node.style.left = node.style.right = "";
  7695. if (horiz == "right") {
  7696. left = display.sizer.clientWidth - node.offsetWidth;
  7697. node.style.right = "0px";
  7698. } else {
  7699. if (horiz == "left") { left = 0; }
  7700. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7701. node.style.left = left + "px";
  7702. }
  7703. if (scroll)
  7704. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7705. },
  7706. triggerOnKeyDown: methodOp(onKeyDown),
  7707. triggerOnKeyPress: methodOp(onKeyPress),
  7708. triggerOnKeyUp: onKeyUp,
  7709. triggerOnMouseDown: methodOp(onMouseDown),
  7710. execCommand: function(cmd) {
  7711. if (commands.hasOwnProperty(cmd))
  7712. { return commands[cmd].call(null, this) }
  7713. },
  7714. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7715. findPosH: function(from, amount, unit, visually) {
  7716. var dir = 1;
  7717. if (amount < 0) { dir = -1; amount = -amount; }
  7718. var cur = clipPos(this.doc, from);
  7719. for (var i = 0; i < amount; ++i) {
  7720. cur = findPosH(this.doc, cur, dir, unit, visually);
  7721. if (cur.hitSide) { break }
  7722. }
  7723. return cur
  7724. },
  7725. moveH: methodOp(function(dir, unit) {
  7726. var this$1 = this;
  7727. this.extendSelectionsBy(function (range) {
  7728. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7729. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7730. else
  7731. { return dir < 0 ? range.from() : range.to() }
  7732. }, sel_move);
  7733. }),
  7734. deleteH: methodOp(function(dir, unit) {
  7735. var sel = this.doc.sel, doc = this.doc;
  7736. if (sel.somethingSelected())
  7737. { doc.replaceSelection("", null, "+delete"); }
  7738. else
  7739. { deleteNearSelection(this, function (range) {
  7740. var other = findPosH(doc, range.head, dir, unit, false);
  7741. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7742. }); }
  7743. }),
  7744. findPosV: function(from, amount, unit, goalColumn) {
  7745. var dir = 1, x = goalColumn;
  7746. if (amount < 0) { dir = -1; amount = -amount; }
  7747. var cur = clipPos(this.doc, from);
  7748. for (var i = 0; i < amount; ++i) {
  7749. var coords = cursorCoords(this, cur, "div");
  7750. if (x == null) { x = coords.left; }
  7751. else { coords.left = x; }
  7752. cur = findPosV(this, coords, dir, unit);
  7753. if (cur.hitSide) { break }
  7754. }
  7755. return cur
  7756. },
  7757. moveV: methodOp(function(dir, unit) {
  7758. var this$1 = this;
  7759. var doc = this.doc, goals = [];
  7760. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7761. doc.extendSelectionsBy(function (range) {
  7762. if (collapse)
  7763. { return dir < 0 ? range.from() : range.to() }
  7764. var headPos = cursorCoords(this$1, range.head, "div");
  7765. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7766. goals.push(headPos.left);
  7767. var pos = findPosV(this$1, headPos, dir, unit);
  7768. if (unit == "page" && range == doc.sel.primary())
  7769. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7770. return pos
  7771. }, sel_move);
  7772. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7773. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7774. }),
  7775. // Find the word at the given position (as returned by coordsChar).
  7776. findWordAt: function(pos) {
  7777. var doc = this.doc, line = getLine(doc, pos.line).text;
  7778. var start = pos.ch, end = pos.ch;
  7779. if (line) {
  7780. var helper = this.getHelper(pos, "wordChars");
  7781. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7782. var startChar = line.charAt(start);
  7783. var check = isWordChar(startChar, helper)
  7784. ? function (ch) { return isWordChar(ch, helper); }
  7785. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7786. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7787. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7788. while (end < line.length && check(line.charAt(end))) { ++end; }
  7789. }
  7790. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7791. },
  7792. toggleOverwrite: function(value) {
  7793. if (value != null && value == this.state.overwrite) { return }
  7794. if (this.state.overwrite = !this.state.overwrite)
  7795. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7796. else
  7797. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7798. signal(this, "overwriteToggle", this, this.state.overwrite);
  7799. },
  7800. hasFocus: function() { return this.display.input.getField() == activeElt(doc(this)) },
  7801. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7802. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7803. getScrollInfo: function() {
  7804. var scroller = this.display.scroller;
  7805. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7806. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7807. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7808. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7809. },
  7810. scrollIntoView: methodOp(function(range, margin) {
  7811. if (range == null) {
  7812. range = {from: this.doc.sel.primary().head, to: null};
  7813. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7814. } else if (typeof range == "number") {
  7815. range = {from: Pos(range, 0), to: null};
  7816. } else if (range.from == null) {
  7817. range = {from: range, to: null};
  7818. }
  7819. if (!range.to) { range.to = range.from; }
  7820. range.margin = margin || 0;
  7821. if (range.from.line != null) {
  7822. scrollToRange(this, range);
  7823. } else {
  7824. scrollToCoordsRange(this, range.from, range.to, range.margin);
  7825. }
  7826. }),
  7827. setSize: methodOp(function(width, height) {
  7828. var this$1 = this;
  7829. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7830. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7831. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7832. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7833. var lineNo = this.display.viewFrom;
  7834. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7835. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7836. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7837. ++lineNo;
  7838. });
  7839. this.curOp.forceUpdate = true;
  7840. signal(this, "refresh", this);
  7841. }),
  7842. operation: function(f){return runInOp(this, f)},
  7843. startOperation: function(){return startOperation(this)},
  7844. endOperation: function(){return endOperation(this)},
  7845. refresh: methodOp(function() {
  7846. var oldHeight = this.display.cachedTextHeight;
  7847. regChange(this);
  7848. this.curOp.forceUpdate = true;
  7849. clearCaches(this);
  7850. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7851. updateGutterSpace(this.display);
  7852. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  7853. { estimateLineHeights(this); }
  7854. signal(this, "refresh", this);
  7855. }),
  7856. swapDoc: methodOp(function(doc) {
  7857. var old = this.doc;
  7858. old.cm = null;
  7859. // Cancel the current text selection if any (#5821)
  7860. if (this.state.selectingText) { this.state.selectingText(); }
  7861. attachDoc(this, doc);
  7862. clearCaches(this);
  7863. this.display.input.reset();
  7864. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7865. this.curOp.forceScroll = true;
  7866. signalLater(this, "swapDoc", this, old);
  7867. return old
  7868. }),
  7869. phrase: function(phraseText) {
  7870. var phrases = this.options.phrases;
  7871. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7872. },
  7873. getInputField: function(){return this.display.input.getField()},
  7874. getWrapperElement: function(){return this.display.wrapper},
  7875. getScrollerElement: function(){return this.display.scroller},
  7876. getGutterElement: function(){return this.display.gutters}
  7877. };
  7878. eventMixin(CodeMirror);
  7879. CodeMirror.registerHelper = function(type, name, value) {
  7880. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7881. helpers[type][name] = value;
  7882. };
  7883. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7884. CodeMirror.registerHelper(type, name, value);
  7885. helpers[type]._global.push({pred: predicate, val: value});
  7886. };
  7887. }
  7888. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7889. // right), unit can be "codepoint", "char", "column" (like char, but
  7890. // doesn't cross line boundaries), "word" (across next word), or
  7891. // "group" (to the start of next group of word or
  7892. // non-word-non-whitespace chars). The visually param controls
  7893. // whether, in right-to-left text, direction 1 means to move towards
  7894. // the next index in the string, or towards the character to the right
  7895. // of the current position. The resulting position will have a
  7896. // hitSide=true property if it reached the end of the document.
  7897. function findPosH(doc, pos, dir, unit, visually) {
  7898. var oldPos = pos;
  7899. var origDir = dir;
  7900. var lineObj = getLine(doc, pos.line);
  7901. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  7902. function findNextLine() {
  7903. var l = pos.line + lineDir;
  7904. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7905. pos = new Pos(l, pos.ch, pos.sticky);
  7906. return lineObj = getLine(doc, l)
  7907. }
  7908. function moveOnce(boundToLine) {
  7909. var next;
  7910. if (unit == "codepoint") {
  7911. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  7912. if (isNaN(ch)) {
  7913. next = null;
  7914. } else {
  7915. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  7916. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  7917. }
  7918. } else if (visually) {
  7919. next = moveVisually(doc.cm, lineObj, pos, dir);
  7920. } else {
  7921. next = moveLogically(lineObj, pos, dir);
  7922. }
  7923. if (next == null) {
  7924. if (!boundToLine && findNextLine())
  7925. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  7926. else
  7927. { return false }
  7928. } else {
  7929. pos = next;
  7930. }
  7931. return true
  7932. }
  7933. if (unit == "char" || unit == "codepoint") {
  7934. moveOnce();
  7935. } else if (unit == "column") {
  7936. moveOnce(true);
  7937. } else if (unit == "word" || unit == "group") {
  7938. var sawType = null, group = unit == "group";
  7939. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7940. for (var first = true;; first = false) {
  7941. if (dir < 0 && !moveOnce(!first)) { break }
  7942. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7943. var type = isWordChar(cur, helper) ? "w"
  7944. : group && cur == "\n" ? "n"
  7945. : !group || /\s/.test(cur) ? null
  7946. : "p";
  7947. if (group && !first && !type) { type = "s"; }
  7948. if (sawType && sawType != type) {
  7949. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7950. break
  7951. }
  7952. if (type) { sawType = type; }
  7953. if (dir > 0 && !moveOnce(!first)) { break }
  7954. }
  7955. }
  7956. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7957. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7958. return result
  7959. }
  7960. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7961. // "page" or "line". The resulting position will have a hitSide=true
  7962. // property if it reached the end of the document.
  7963. function findPosV(cm, pos, dir, unit) {
  7964. var doc = cm.doc, x = pos.left, y;
  7965. if (unit == "page") {
  7966. var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
  7967. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7968. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7969. } else if (unit == "line") {
  7970. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7971. }
  7972. var target;
  7973. for (;;) {
  7974. target = coordsChar(cm, x, y);
  7975. if (!target.outside) { break }
  7976. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7977. y += dir * 5;
  7978. }
  7979. return target
  7980. }
  7981. // CONTENTEDITABLE INPUT STYLE
  7982. var ContentEditableInput = function(cm) {
  7983. this.cm = cm;
  7984. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7985. this.polling = new Delayed();
  7986. this.composing = null;
  7987. this.gracePeriod = false;
  7988. this.readDOMTimeout = null;
  7989. };
  7990. ContentEditableInput.prototype.init = function (display) {
  7991. var this$1 = this;
  7992. var input = this, cm = input.cm;
  7993. var div = input.div = display.lineDiv;
  7994. div.contentEditable = true;
  7995. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7996. function belongsToInput(e) {
  7997. for (var t = e.target; t; t = t.parentNode) {
  7998. if (t == div) { return true }
  7999. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  8000. }
  8001. return false
  8002. }
  8003. on(div, "paste", function (e) {
  8004. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8005. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  8006. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  8007. });
  8008. on(div, "compositionstart", function (e) {
  8009. this$1.composing = {data: e.data, done: false};
  8010. });
  8011. on(div, "compositionupdate", function (e) {
  8012. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  8013. });
  8014. on(div, "compositionend", function (e) {
  8015. if (this$1.composing) {
  8016. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  8017. this$1.composing.done = true;
  8018. }
  8019. });
  8020. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8021. on(div, "input", function () {
  8022. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8023. });
  8024. function onCopyCut(e) {
  8025. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8026. if (cm.somethingSelected()) {
  8027. setLastCopied({lineWise: false, text: cm.getSelections()});
  8028. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8029. } else if (!cm.options.lineWiseCopyCut) {
  8030. return
  8031. } else {
  8032. var ranges = copyableRanges(cm);
  8033. setLastCopied({lineWise: true, text: ranges.text});
  8034. if (e.type == "cut") {
  8035. cm.operation(function () {
  8036. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8037. cm.replaceSelection("", null, "cut");
  8038. });
  8039. }
  8040. }
  8041. if (e.clipboardData) {
  8042. e.clipboardData.clearData();
  8043. var content = lastCopied.text.join("\n");
  8044. // iOS exposes the clipboard API, but seems to discard content inserted into it
  8045. e.clipboardData.setData("Text", content);
  8046. if (e.clipboardData.getData("Text") == content) {
  8047. e.preventDefault();
  8048. return
  8049. }
  8050. }
  8051. // Old-fashioned briefly-focus-a-textarea hack
  8052. var kludge = hiddenTextarea(), te = kludge.firstChild;
  8053. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8054. te.value = lastCopied.text.join("\n");
  8055. var hadFocus = activeElt(div.ownerDocument);
  8056. selectInput(te);
  8057. setTimeout(function () {
  8058. cm.display.lineSpace.removeChild(kludge);
  8059. hadFocus.focus();
  8060. if (hadFocus == div) { input.showPrimarySelection(); }
  8061. }, 50);
  8062. }
  8063. on(div, "copy", onCopyCut);
  8064. on(div, "cut", onCopyCut);
  8065. };
  8066. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8067. // Label for screenreaders, accessibility
  8068. if(label) {
  8069. this.div.setAttribute('aria-label', label);
  8070. } else {
  8071. this.div.removeAttribute('aria-label');
  8072. }
  8073. };
  8074. ContentEditableInput.prototype.prepareSelection = function () {
  8075. var result = prepareSelection(this.cm, false);
  8076. result.focus = activeElt(this.div.ownerDocument) == this.div;
  8077. return result
  8078. };
  8079. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8080. if (!info || !this.cm.display.view.length) { return }
  8081. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8082. this.showMultipleSelections(info);
  8083. };
  8084. ContentEditableInput.prototype.getSelection = function () {
  8085. return this.cm.display.wrapper.ownerDocument.getSelection()
  8086. };
  8087. ContentEditableInput.prototype.showPrimarySelection = function () {
  8088. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8089. var from = prim.from(), to = prim.to();
  8090. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8091. sel.removeAllRanges();
  8092. return
  8093. }
  8094. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8095. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8096. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8097. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8098. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8099. { return }
  8100. var view = cm.display.view;
  8101. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8102. {node: view[0].measure.map[2], offset: 0};
  8103. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8104. if (!end) {
  8105. var measure = view[view.length - 1].measure;
  8106. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8107. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8108. }
  8109. if (!start || !end) {
  8110. sel.removeAllRanges();
  8111. return
  8112. }
  8113. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8114. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8115. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8116. if (rng) {
  8117. if (!gecko && cm.state.focused) {
  8118. sel.collapse(start.node, start.offset);
  8119. if (!rng.collapsed) {
  8120. sel.removeAllRanges();
  8121. sel.addRange(rng);
  8122. }
  8123. } else {
  8124. sel.removeAllRanges();
  8125. sel.addRange(rng);
  8126. }
  8127. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8128. else if (gecko) { this.startGracePeriod(); }
  8129. }
  8130. this.rememberSelection();
  8131. };
  8132. ContentEditableInput.prototype.startGracePeriod = function () {
  8133. var this$1 = this;
  8134. clearTimeout(this.gracePeriod);
  8135. this.gracePeriod = setTimeout(function () {
  8136. this$1.gracePeriod = false;
  8137. if (this$1.selectionChanged())
  8138. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8139. }, 20);
  8140. };
  8141. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8142. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8143. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8144. };
  8145. ContentEditableInput.prototype.rememberSelection = function () {
  8146. var sel = this.getSelection();
  8147. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8148. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8149. };
  8150. ContentEditableInput.prototype.selectionInEditor = function () {
  8151. var sel = this.getSelection();
  8152. if (!sel.rangeCount) { return false }
  8153. var node = sel.getRangeAt(0).commonAncestorContainer;
  8154. return contains(this.div, node)
  8155. };
  8156. ContentEditableInput.prototype.focus = function () {
  8157. if (this.cm.options.readOnly != "nocursor") {
  8158. if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div)
  8159. { this.showSelection(this.prepareSelection(), true); }
  8160. this.div.focus();
  8161. }
  8162. };
  8163. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8164. ContentEditableInput.prototype.getField = function () { return this.div };
  8165. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8166. ContentEditableInput.prototype.receivedFocus = function () {
  8167. var this$1 = this;
  8168. var input = this;
  8169. if (this.selectionInEditor())
  8170. { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  8171. else
  8172. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8173. function poll() {
  8174. if (input.cm.state.focused) {
  8175. input.pollSelection();
  8176. input.polling.set(input.cm.options.pollInterval, poll);
  8177. }
  8178. }
  8179. this.polling.set(this.cm.options.pollInterval, poll);
  8180. };
  8181. ContentEditableInput.prototype.selectionChanged = function () {
  8182. var sel = this.getSelection();
  8183. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8184. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8185. };
  8186. ContentEditableInput.prototype.pollSelection = function () {
  8187. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8188. var sel = this.getSelection(), cm = this.cm;
  8189. // On Android Chrome (version 56, at least), backspacing into an
  8190. // uneditable block element will put the cursor in that element,
  8191. // and then, because it's not editable, hide the virtual keyboard.
  8192. // Because Android doesn't allow us to actually detect backspace
  8193. // presses in a sane way, this code checks for when that happens
  8194. // and simulates a backspace press in this case.
  8195. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8196. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8197. this.blur();
  8198. this.focus();
  8199. return
  8200. }
  8201. if (this.composing) { return }
  8202. this.rememberSelection();
  8203. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8204. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8205. if (anchor && head) { runInOp(cm, function () {
  8206. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8207. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8208. }); }
  8209. };
  8210. ContentEditableInput.prototype.pollContent = function () {
  8211. if (this.readDOMTimeout != null) {
  8212. clearTimeout(this.readDOMTimeout);
  8213. this.readDOMTimeout = null;
  8214. }
  8215. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8216. var from = sel.from(), to = sel.to();
  8217. if (from.ch == 0 && from.line > cm.firstLine())
  8218. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8219. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8220. { to = Pos(to.line + 1, 0); }
  8221. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8222. var fromIndex, fromLine, fromNode;
  8223. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8224. fromLine = lineNo(display.view[0].line);
  8225. fromNode = display.view[0].node;
  8226. } else {
  8227. fromLine = lineNo(display.view[fromIndex].line);
  8228. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8229. }
  8230. var toIndex = findViewIndex(cm, to.line);
  8231. var toLine, toNode;
  8232. if (toIndex == display.view.length - 1) {
  8233. toLine = display.viewTo - 1;
  8234. toNode = display.lineDiv.lastChild;
  8235. } else {
  8236. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8237. toNode = display.view[toIndex + 1].node.previousSibling;
  8238. }
  8239. if (!fromNode) { return false }
  8240. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8241. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8242. while (newText.length > 1 && oldText.length > 1) {
  8243. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8244. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8245. else { break }
  8246. }
  8247. var cutFront = 0, cutEnd = 0;
  8248. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8249. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8250. { ++cutFront; }
  8251. var newBot = lst(newText), oldBot = lst(oldText);
  8252. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8253. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8254. while (cutEnd < maxCutEnd &&
  8255. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8256. { ++cutEnd; }
  8257. // Try to move start of change to start of selection if ambiguous
  8258. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8259. while (cutFront && cutFront > from.ch &&
  8260. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8261. cutFront--;
  8262. cutEnd++;
  8263. }
  8264. }
  8265. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8266. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8267. var chFrom = Pos(fromLine, cutFront);
  8268. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8269. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8270. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8271. return true
  8272. }
  8273. };
  8274. ContentEditableInput.prototype.ensurePolled = function () {
  8275. this.forceCompositionEnd();
  8276. };
  8277. ContentEditableInput.prototype.reset = function () {
  8278. this.forceCompositionEnd();
  8279. };
  8280. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8281. if (!this.composing) { return }
  8282. clearTimeout(this.readDOMTimeout);
  8283. this.composing = null;
  8284. this.updateFromDOM();
  8285. this.div.blur();
  8286. this.div.focus();
  8287. };
  8288. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8289. var this$1 = this;
  8290. if (this.readDOMTimeout != null) { return }
  8291. this.readDOMTimeout = setTimeout(function () {
  8292. this$1.readDOMTimeout = null;
  8293. if (this$1.composing) {
  8294. if (this$1.composing.done) { this$1.composing = null; }
  8295. else { return }
  8296. }
  8297. this$1.updateFromDOM();
  8298. }, 80);
  8299. };
  8300. ContentEditableInput.prototype.updateFromDOM = function () {
  8301. var this$1 = this;
  8302. if (this.cm.isReadOnly() || !this.pollContent())
  8303. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8304. };
  8305. ContentEditableInput.prototype.setUneditable = function (node) {
  8306. node.contentEditable = "false";
  8307. };
  8308. ContentEditableInput.prototype.onKeyPress = function (e) {
  8309. if (e.charCode == 0 || this.composing) { return }
  8310. e.preventDefault();
  8311. if (!this.cm.isReadOnly())
  8312. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8313. };
  8314. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8315. this.div.contentEditable = String(val != "nocursor");
  8316. };
  8317. ContentEditableInput.prototype.onContextMenu = function () {};
  8318. ContentEditableInput.prototype.resetPosition = function () {};
  8319. ContentEditableInput.prototype.needsContentAttribute = true;
  8320. function posToDOM(cm, pos) {
  8321. var view = findViewForLine(cm, pos.line);
  8322. if (!view || view.hidden) { return null }
  8323. var line = getLine(cm.doc, pos.line);
  8324. var info = mapFromLineView(view, line, pos.line);
  8325. var order = getOrder(line, cm.doc.direction), side = "left";
  8326. if (order) {
  8327. var partPos = getBidiPartAt(order, pos.ch);
  8328. side = partPos % 2 ? "right" : "left";
  8329. }
  8330. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8331. result.offset = result.collapse == "right" ? result.end : result.start;
  8332. return result
  8333. }
  8334. function isInGutter(node) {
  8335. for (var scan = node; scan; scan = scan.parentNode)
  8336. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8337. return false
  8338. }
  8339. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8340. function domTextBetween(cm, from, to, fromLine, toLine) {
  8341. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8342. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8343. function close() {
  8344. if (closing) {
  8345. text += lineSep;
  8346. if (extraLinebreak) { text += lineSep; }
  8347. closing = extraLinebreak = false;
  8348. }
  8349. }
  8350. function addText(str) {
  8351. if (str) {
  8352. close();
  8353. text += str;
  8354. }
  8355. }
  8356. function walk(node) {
  8357. if (node.nodeType == 1) {
  8358. var cmText = node.getAttribute("cm-text");
  8359. if (cmText) {
  8360. addText(cmText);
  8361. return
  8362. }
  8363. var markerID = node.getAttribute("cm-marker"), range;
  8364. if (markerID) {
  8365. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8366. if (found.length && (range = found[0].find(0)))
  8367. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8368. return
  8369. }
  8370. if (node.getAttribute("contenteditable") == "false") { return }
  8371. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8372. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8373. if (isBlock) { close(); }
  8374. for (var i = 0; i < node.childNodes.length; i++)
  8375. { walk(node.childNodes[i]); }
  8376. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8377. if (isBlock) { closing = true; }
  8378. } else if (node.nodeType == 3) {
  8379. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8380. }
  8381. }
  8382. for (;;) {
  8383. walk(from);
  8384. if (from == to) { break }
  8385. from = from.nextSibling;
  8386. extraLinebreak = false;
  8387. }
  8388. return text
  8389. }
  8390. function domToPos(cm, node, offset) {
  8391. var lineNode;
  8392. if (node == cm.display.lineDiv) {
  8393. lineNode = cm.display.lineDiv.childNodes[offset];
  8394. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8395. node = null; offset = 0;
  8396. } else {
  8397. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8398. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8399. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8400. }
  8401. }
  8402. for (var i = 0; i < cm.display.view.length; i++) {
  8403. var lineView = cm.display.view[i];
  8404. if (lineView.node == lineNode)
  8405. { return locateNodeInLineView(lineView, node, offset) }
  8406. }
  8407. }
  8408. function locateNodeInLineView(lineView, node, offset) {
  8409. var wrapper = lineView.text.firstChild, bad = false;
  8410. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8411. if (node == wrapper) {
  8412. bad = true;
  8413. node = wrapper.childNodes[offset];
  8414. offset = 0;
  8415. if (!node) {
  8416. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8417. return badPos(Pos(lineNo(line), line.text.length), bad)
  8418. }
  8419. }
  8420. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8421. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8422. textNode = node.firstChild;
  8423. if (offset) { offset = textNode.nodeValue.length; }
  8424. }
  8425. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8426. var measure = lineView.measure, maps = measure.maps;
  8427. function find(textNode, topNode, offset) {
  8428. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8429. var map = i < 0 ? measure.map : maps[i];
  8430. for (var j = 0; j < map.length; j += 3) {
  8431. var curNode = map[j + 2];
  8432. if (curNode == textNode || curNode == topNode) {
  8433. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8434. var ch = map[j] + offset;
  8435. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8436. return Pos(line, ch)
  8437. }
  8438. }
  8439. }
  8440. }
  8441. var found = find(textNode, topNode, offset);
  8442. if (found) { return badPos(found, bad) }
  8443. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8444. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8445. found = find(after, after.firstChild, 0);
  8446. if (found)
  8447. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8448. else
  8449. { dist += after.textContent.length; }
  8450. }
  8451. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8452. found = find(before, before.firstChild, -1);
  8453. if (found)
  8454. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8455. else
  8456. { dist$1 += before.textContent.length; }
  8457. }
  8458. }
  8459. // TEXTAREA INPUT STYLE
  8460. var TextareaInput = function(cm) {
  8461. this.cm = cm;
  8462. // See input.poll and input.reset
  8463. this.prevInput = "";
  8464. // Flag that indicates whether we expect input to appear real soon
  8465. // now (after some event like 'keypress' or 'input') and are
  8466. // polling intensively.
  8467. this.pollingFast = false;
  8468. // Self-resetting timeout for the poller
  8469. this.polling = new Delayed();
  8470. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8471. this.hasSelection = false;
  8472. this.composing = null;
  8473. this.resetting = false;
  8474. };
  8475. TextareaInput.prototype.init = function (display) {
  8476. var this$1 = this;
  8477. var input = this, cm = this.cm;
  8478. this.createField(display);
  8479. var te = this.textarea;
  8480. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8481. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8482. if (ios) { te.style.width = "0px"; }
  8483. on(te, "input", function () {
  8484. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8485. input.poll();
  8486. });
  8487. on(te, "paste", function (e) {
  8488. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8489. cm.state.pasteIncoming = +new Date;
  8490. input.fastPoll();
  8491. });
  8492. function prepareCopyCut(e) {
  8493. if (signalDOMEvent(cm, e)) { return }
  8494. if (cm.somethingSelected()) {
  8495. setLastCopied({lineWise: false, text: cm.getSelections()});
  8496. } else if (!cm.options.lineWiseCopyCut) {
  8497. return
  8498. } else {
  8499. var ranges = copyableRanges(cm);
  8500. setLastCopied({lineWise: true, text: ranges.text});
  8501. if (e.type == "cut") {
  8502. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8503. } else {
  8504. input.prevInput = "";
  8505. te.value = ranges.text.join("\n");
  8506. selectInput(te);
  8507. }
  8508. }
  8509. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8510. }
  8511. on(te, "cut", prepareCopyCut);
  8512. on(te, "copy", prepareCopyCut);
  8513. on(display.scroller, "paste", function (e) {
  8514. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8515. if (!te.dispatchEvent) {
  8516. cm.state.pasteIncoming = +new Date;
  8517. input.focus();
  8518. return
  8519. }
  8520. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8521. var event = new Event("paste");
  8522. event.clipboardData = e.clipboardData;
  8523. te.dispatchEvent(event);
  8524. });
  8525. // Prevent normal selection in the editor (we handle our own)
  8526. on(display.lineSpace, "selectstart", function (e) {
  8527. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8528. });
  8529. on(te, "compositionstart", function () {
  8530. var start = cm.getCursor("from");
  8531. if (input.composing) { input.composing.range.clear(); }
  8532. input.composing = {
  8533. start: start,
  8534. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8535. };
  8536. });
  8537. on(te, "compositionend", function () {
  8538. if (input.composing) {
  8539. input.poll();
  8540. input.composing.range.clear();
  8541. input.composing = null;
  8542. }
  8543. });
  8544. };
  8545. TextareaInput.prototype.createField = function (_display) {
  8546. // Wraps and hides input textarea
  8547. this.wrapper = hiddenTextarea();
  8548. // The semihidden textarea that is focused when the editor is
  8549. // focused, and receives input.
  8550. this.textarea = this.wrapper.firstChild;
  8551. };
  8552. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8553. // Label for screenreaders, accessibility
  8554. if(label) {
  8555. this.textarea.setAttribute('aria-label', label);
  8556. } else {
  8557. this.textarea.removeAttribute('aria-label');
  8558. }
  8559. };
  8560. TextareaInput.prototype.prepareSelection = function () {
  8561. // Redraw the selection and/or cursor
  8562. var cm = this.cm, display = cm.display, doc = cm.doc;
  8563. var result = prepareSelection(cm);
  8564. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8565. if (cm.options.moveInputWithCursor) {
  8566. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8567. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8568. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8569. headPos.top + lineOff.top - wrapOff.top));
  8570. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8571. headPos.left + lineOff.left - wrapOff.left));
  8572. }
  8573. return result
  8574. };
  8575. TextareaInput.prototype.showSelection = function (drawn) {
  8576. var cm = this.cm, display = cm.display;
  8577. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8578. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8579. if (drawn.teTop != null) {
  8580. this.wrapper.style.top = drawn.teTop + "px";
  8581. this.wrapper.style.left = drawn.teLeft + "px";
  8582. }
  8583. };
  8584. // Reset the input to correspond to the selection (or to be empty,
  8585. // when not typing and nothing is selected)
  8586. TextareaInput.prototype.reset = function (typing) {
  8587. if (this.contextMenuPending || this.composing && typing) { return }
  8588. var cm = this.cm;
  8589. this.resetting = true;
  8590. if (cm.somethingSelected()) {
  8591. this.prevInput = "";
  8592. var content = cm.getSelection();
  8593. this.textarea.value = content;
  8594. if (cm.state.focused) { selectInput(this.textarea); }
  8595. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8596. } else if (!typing) {
  8597. this.prevInput = this.textarea.value = "";
  8598. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8599. }
  8600. this.resetting = false;
  8601. };
  8602. TextareaInput.prototype.getField = function () { return this.textarea };
  8603. TextareaInput.prototype.supportsTouch = function () { return false };
  8604. TextareaInput.prototype.focus = function () {
  8605. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) {
  8606. try { this.textarea.focus(); }
  8607. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8608. }
  8609. };
  8610. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8611. TextareaInput.prototype.resetPosition = function () {
  8612. this.wrapper.style.top = this.wrapper.style.left = 0;
  8613. };
  8614. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8615. // Poll for input changes, using the normal rate of polling. This
  8616. // runs as long as the editor is focused.
  8617. TextareaInput.prototype.slowPoll = function () {
  8618. var this$1 = this;
  8619. if (this.pollingFast) { return }
  8620. this.polling.set(this.cm.options.pollInterval, function () {
  8621. this$1.poll();
  8622. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8623. });
  8624. };
  8625. // When an event has just come in that is likely to add or change
  8626. // something in the input textarea, we poll faster, to ensure that
  8627. // the change appears on the screen quickly.
  8628. TextareaInput.prototype.fastPoll = function () {
  8629. var missed = false, input = this;
  8630. input.pollingFast = true;
  8631. function p() {
  8632. var changed = input.poll();
  8633. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8634. else {input.pollingFast = false; input.slowPoll();}
  8635. }
  8636. input.polling.set(20, p);
  8637. };
  8638. // Read input from the textarea, and update the document to match.
  8639. // When something is selected, it is present in the textarea, and
  8640. // selected (unless it is huge, in which case a placeholder is
  8641. // used). When nothing is selected, the cursor sits after previously
  8642. // seen text (can be empty), which is stored in prevInput (we must
  8643. // not reset the textarea when typing, because that breaks IME).
  8644. TextareaInput.prototype.poll = function () {
  8645. var this$1 = this;
  8646. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8647. // Since this is called a *lot*, try to bail out as cheaply as
  8648. // possible when it is clear that nothing happened. hasSelection
  8649. // will be the case when there is a lot of text in the textarea,
  8650. // in which case reading its value would be expensive.
  8651. if (this.contextMenuPending || this.resetting || !cm.state.focused ||
  8652. (hasSelection(input) && !prevInput && !this.composing) ||
  8653. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8654. { return false }
  8655. var text = input.value;
  8656. // If nothing changed, bail.
  8657. if (text == prevInput && !cm.somethingSelected()) { return false }
  8658. // Work around nonsensical selection resetting in IE9/10, and
  8659. // inexplicable appearance of private area unicode characters on
  8660. // some key combos in Mac (#2689).
  8661. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8662. mac && /[\uf700-\uf7ff]/.test(text)) {
  8663. cm.display.input.reset();
  8664. return false
  8665. }
  8666. if (cm.doc.sel == cm.display.selForContextMenu) {
  8667. var first = text.charCodeAt(0);
  8668. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8669. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8670. }
  8671. // Find the part of the input that is actually new
  8672. var same = 0, l = Math.min(prevInput.length, text.length);
  8673. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8674. runInOp(cm, function () {
  8675. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8676. null, this$1.composing ? "*compose" : null);
  8677. // Don't leave long text in the textarea, since it makes further polling slow
  8678. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8679. else { this$1.prevInput = text; }
  8680. if (this$1.composing) {
  8681. this$1.composing.range.clear();
  8682. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8683. {className: "CodeMirror-composing"});
  8684. }
  8685. });
  8686. return true
  8687. };
  8688. TextareaInput.prototype.ensurePolled = function () {
  8689. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8690. };
  8691. TextareaInput.prototype.onKeyPress = function () {
  8692. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8693. this.fastPoll();
  8694. };
  8695. TextareaInput.prototype.onContextMenu = function (e) {
  8696. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8697. if (input.contextMenuPending) { input.contextMenuPending(); }
  8698. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8699. if (!pos || presto) { return } // Opera is difficult.
  8700. // Reset the current text selection only if the click is done outside of the selection
  8701. // and 'resetSelectionOnContextMenu' option is true.
  8702. var reset = cm.options.resetSelectionOnContextMenu;
  8703. if (reset && cm.doc.sel.contains(pos) == -1)
  8704. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8705. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8706. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8707. input.wrapper.style.cssText = "position: static";
  8708. 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);";
  8709. var oldScrollY;
  8710. if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
  8711. display.input.focus();
  8712. if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
  8713. display.input.reset();
  8714. // Adds "Select all" to context menu in FF
  8715. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8716. input.contextMenuPending = rehide;
  8717. display.selForContextMenu = cm.doc.sel;
  8718. clearTimeout(display.detectingSelectAll);
  8719. // Select-all will be greyed out if there's nothing to select, so
  8720. // this adds a zero-width space so that we can later check whether
  8721. // it got selected.
  8722. function prepareSelectAllHack() {
  8723. if (te.selectionStart != null) {
  8724. var selected = cm.somethingSelected();
  8725. var extval = "\u200b" + (selected ? te.value : "");
  8726. te.value = "\u21da"; // Used to catch context-menu undo
  8727. te.value = extval;
  8728. input.prevInput = selected ? "" : "\u200b";
  8729. te.selectionStart = 1; te.selectionEnd = extval.length;
  8730. // Re-set this, in case some other handler touched the
  8731. // selection in the meantime.
  8732. display.selForContextMenu = cm.doc.sel;
  8733. }
  8734. }
  8735. function rehide() {
  8736. if (input.contextMenuPending != rehide) { return }
  8737. input.contextMenuPending = false;
  8738. input.wrapper.style.cssText = oldWrapperCSS;
  8739. te.style.cssText = oldCSS;
  8740. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8741. // Try to detect the user choosing select-all
  8742. if (te.selectionStart != null) {
  8743. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8744. var i = 0, poll = function () {
  8745. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8746. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8747. operation(cm, selectAll)(cm);
  8748. } else if (i++ < 10) {
  8749. display.detectingSelectAll = setTimeout(poll, 500);
  8750. } else {
  8751. display.selForContextMenu = null;
  8752. display.input.reset();
  8753. }
  8754. };
  8755. display.detectingSelectAll = setTimeout(poll, 200);
  8756. }
  8757. }
  8758. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8759. if (captureRightClick) {
  8760. e_stop(e);
  8761. var mouseup = function () {
  8762. off(window, "mouseup", mouseup);
  8763. setTimeout(rehide, 20);
  8764. };
  8765. on(window, "mouseup", mouseup);
  8766. } else {
  8767. setTimeout(rehide, 50);
  8768. }
  8769. };
  8770. TextareaInput.prototype.readOnlyChanged = function (val) {
  8771. if (!val) { this.reset(); }
  8772. this.textarea.disabled = val == "nocursor";
  8773. this.textarea.readOnly = !!val;
  8774. };
  8775. TextareaInput.prototype.setUneditable = function () {};
  8776. TextareaInput.prototype.needsContentAttribute = false;
  8777. function fromTextArea(textarea, options) {
  8778. options = options ? copyObj(options) : {};
  8779. options.value = textarea.value;
  8780. if (!options.tabindex && textarea.tabIndex)
  8781. { options.tabindex = textarea.tabIndex; }
  8782. if (!options.placeholder && textarea.placeholder)
  8783. { options.placeholder = textarea.placeholder; }
  8784. // Set autofocus to true if this textarea is focused, or if it has
  8785. // autofocus and no other element is focused.
  8786. if (options.autofocus == null) {
  8787. var hasFocus = activeElt(textarea.ownerDocument);
  8788. options.autofocus = hasFocus == textarea ||
  8789. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8790. }
  8791. function save() {textarea.value = cm.getValue();}
  8792. var realSubmit;
  8793. if (textarea.form) {
  8794. on(textarea.form, "submit", save);
  8795. // Deplorable hack to make the submit method do the right thing.
  8796. if (!options.leaveSubmitMethodAlone) {
  8797. var form = textarea.form;
  8798. realSubmit = form.submit;
  8799. try {
  8800. var wrappedSubmit = form.submit = function () {
  8801. save();
  8802. form.submit = realSubmit;
  8803. form.submit();
  8804. form.submit = wrappedSubmit;
  8805. };
  8806. } catch(e) {}
  8807. }
  8808. }
  8809. options.finishInit = function (cm) {
  8810. cm.save = save;
  8811. cm.getTextArea = function () { return textarea; };
  8812. cm.toTextArea = function () {
  8813. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8814. save();
  8815. textarea.parentNode.removeChild(cm.getWrapperElement());
  8816. textarea.style.display = "";
  8817. if (textarea.form) {
  8818. off(textarea.form, "submit", save);
  8819. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  8820. { textarea.form.submit = realSubmit; }
  8821. }
  8822. };
  8823. };
  8824. textarea.style.display = "none";
  8825. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8826. options);
  8827. return cm
  8828. }
  8829. function addLegacyProps(CodeMirror) {
  8830. CodeMirror.off = off;
  8831. CodeMirror.on = on;
  8832. CodeMirror.wheelEventPixels = wheelEventPixels;
  8833. CodeMirror.Doc = Doc;
  8834. CodeMirror.splitLines = splitLinesAuto;
  8835. CodeMirror.countColumn = countColumn;
  8836. CodeMirror.findColumn = findColumn;
  8837. CodeMirror.isWordChar = isWordCharBasic;
  8838. CodeMirror.Pass = Pass;
  8839. CodeMirror.signal = signal;
  8840. CodeMirror.Line = Line;
  8841. CodeMirror.changeEnd = changeEnd;
  8842. CodeMirror.scrollbarModel = scrollbarModel;
  8843. CodeMirror.Pos = Pos;
  8844. CodeMirror.cmpPos = cmp;
  8845. CodeMirror.modes = modes;
  8846. CodeMirror.mimeModes = mimeModes;
  8847. CodeMirror.resolveMode = resolveMode;
  8848. CodeMirror.getMode = getMode;
  8849. CodeMirror.modeExtensions = modeExtensions;
  8850. CodeMirror.extendMode = extendMode;
  8851. CodeMirror.copyState = copyState;
  8852. CodeMirror.startState = startState;
  8853. CodeMirror.innerMode = innerMode;
  8854. CodeMirror.commands = commands;
  8855. CodeMirror.keyMap = keyMap;
  8856. CodeMirror.keyName = keyName;
  8857. CodeMirror.isModifierKey = isModifierKey;
  8858. CodeMirror.lookupKey = lookupKey;
  8859. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8860. CodeMirror.StringStream = StringStream;
  8861. CodeMirror.SharedTextMarker = SharedTextMarker;
  8862. CodeMirror.TextMarker = TextMarker;
  8863. CodeMirror.LineWidget = LineWidget;
  8864. CodeMirror.e_preventDefault = e_preventDefault;
  8865. CodeMirror.e_stopPropagation = e_stopPropagation;
  8866. CodeMirror.e_stop = e_stop;
  8867. CodeMirror.addClass = addClass;
  8868. CodeMirror.contains = contains;
  8869. CodeMirror.rmClass = rmClass;
  8870. CodeMirror.keyNames = keyNames;
  8871. }
  8872. // EDITOR CONSTRUCTOR
  8873. defineOptions(CodeMirror);
  8874. addEditorMethods(CodeMirror);
  8875. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8876. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8877. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8878. { CodeMirror.prototype[prop] = (function(method) {
  8879. return function() {return method.apply(this.doc, arguments)}
  8880. })(Doc.prototype[prop]); } }
  8881. eventMixin(Doc);
  8882. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8883. // Extra arguments are stored as the mode's dependencies, which is
  8884. // used by (legacy) mechanisms like loadmode.js to automatically
  8885. // load a mode. (Preferred mechanism is the require/define calls.)
  8886. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8887. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8888. defineMode.apply(this, arguments);
  8889. };
  8890. CodeMirror.defineMIME = defineMIME;
  8891. // Minimal default mode.
  8892. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8893. CodeMirror.defineMIME("text/plain", "null");
  8894. // EXTENSIONS
  8895. CodeMirror.defineExtension = function (name, func) {
  8896. CodeMirror.prototype[name] = func;
  8897. };
  8898. CodeMirror.defineDocExtension = function (name, func) {
  8899. Doc.prototype[name] = func;
  8900. };
  8901. CodeMirror.fromTextArea = fromTextArea;
  8902. addLegacyProps(CodeMirror);
  8903. CodeMirror.version = "5.65.9";
  8904. return CodeMirror;
  8905. })));