not really known
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.

9332 lines
351 KiB

  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), 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.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\//.test(userAgent);
  26. var presto = /Opera\//.test(userAgent);
  27. var safari = /Apple Computer/.test(navigator.vendor);
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  29. var phantom = /PhantomJS/.test(userAgent);
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  31. var android = /Android/.test(userAgent);
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  34. var mac = ios || /Mac/.test(platform);
  35. var chromeOS = /\bCrOS\b/.test(userAgent);
  36. var windows = /win/i.test(platform);
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  38. if (presto_version) { presto_version = Number(presto_version[1]); }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  42. var captureRightClick = gecko || (ie && ie_version >= 9);
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className;
  46. var match = classTest(cls).exec(current);
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length);
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  50. }
  51. };
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild); }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag);
  62. if (className) { e.className = className; }
  63. if (style) { e.style.cssText = style; }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style);
  71. e.setAttribute("role", "presentation");
  72. return e
  73. }
  74. var range;
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange();
  77. r.setEnd(endNode || node, end);
  78. r.setStart(node, start);
  79. return r
  80. }; }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange();
  83. try { r.moveToElementText(node.parentNode); }
  84. catch(e) { return r }
  85. r.collapse(true);
  86. r.moveEnd("character", end);
  87. r.moveStart("character", start);
  88. return r
  89. }; }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode; }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host; }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement;
  105. try {
  106. activeElement = document.activeElement;
  107. } catch(e) {
  108. activeElement = document.body || null;
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement; }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className;
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ");
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select(); };
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1);
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {}; }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop]; } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/);
  145. if (end == -1) { end = string.length; }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i);
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i;
  152. n += tabSize - (n % tabSize);
  153. i = nextTab + 1;
  154. }
  155. }
  156. var Delayed = function() {this.id = null;};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id);
  159. this.id = setTimeout(f, ms);
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30;
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false};
  173. var sel_mouse = {origin: "*mouse"};
  174. var sel_move = {origin: "+move"};
  175. // The inverse of countColumn -- find the offset that corresponds to
  176. // a particular column.
  177. function findColumn(string, goal, tabSize) {
  178. for (var pos = 0, col = 0;;) {
  179. var nextTab = string.indexOf("\t", pos);
  180. if (nextTab == -1) { nextTab = string.length; }
  181. var skipped = nextTab - pos;
  182. if (nextTab == string.length || col + skipped >= goal)
  183. { return pos + Math.min(skipped, goal - col) }
  184. col += nextTab - pos;
  185. col += tabSize - (col % tabSize);
  186. pos = nextTab + 1;
  187. if (col >= goal) { return pos }
  188. }
  189. }
  190. var spaceStrs = [""];
  191. function spaceStr(n) {
  192. while (spaceStrs.length <= n)
  193. { spaceStrs.push(lst(spaceStrs) + " "); }
  194. return spaceStrs[n]
  195. }
  196. function lst(arr) { return arr[arr.length-1] }
  197. function map(array, f) {
  198. var out = [];
  199. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  200. return out
  201. }
  202. function insertSorted(array, value, score) {
  203. var pos = 0, priority = score(value);
  204. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  205. array.splice(pos, 0, value);
  206. }
  207. function nothing() {}
  208. function createObj(base, props) {
  209. var inst;
  210. if (Object.create) {
  211. inst = Object.create(base);
  212. } else {
  213. nothing.prototype = base;
  214. inst = new nothing();
  215. }
  216. if (props) { copyObj(props, inst); }
  217. return inst
  218. }
  219. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  220. function isWordCharBasic(ch) {
  221. return /\w/.test(ch) || ch > "\x80" &&
  222. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  223. }
  224. function isWordChar(ch, helper) {
  225. if (!helper) { return isWordCharBasic(ch) }
  226. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  227. return helper.test(ch)
  228. }
  229. function isEmpty(obj) {
  230. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  231. return true
  232. }
  233. // Extending unicode characters. A series of a non-extending char +
  234. // any number of extending chars is treated as a single unit as far
  235. // as editing and measuring is concerned. This is not fully correct,
  236. // since some scripts/fonts/browsers also treat other configurations
  237. // of code points as a group.
  238. 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]/;
  239. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  240. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  241. function skipExtendingChars(str, pos, dir) {
  242. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  243. return pos
  244. }
  245. // Returns the value from the range [`from`; `to`] that satisfies
  246. // `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`.
  247. function findFirst(pred, from, to) {
  248. for (;;) {
  249. if (Math.abs(from - to) <= 1) { return pred(from) ? from : to }
  250. var mid = Math.floor((from + to) / 2);
  251. if (pred(mid)) { to = mid; }
  252. else { from = mid; }
  253. }
  254. }
  255. // The display handles the DOM integration, both for input reading
  256. // and content drawing. It holds references to DOM nodes and
  257. // display-related state.
  258. function Display(place, doc, input) {
  259. var d = this;
  260. this.input = input;
  261. // Covers bottom-right square when both scrollbars are present.
  262. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  263. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  264. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  265. // and h scrollbar is present.
  266. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  267. d.gutterFiller.setAttribute("cm-not-content", "true");
  268. // Will contain the actual code, positioned to cover the viewport.
  269. d.lineDiv = eltP("div", null, "CodeMirror-code");
  270. // Elements are added to these to represent selection and cursors.
  271. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  272. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  273. // A visibility: hidden element used to find the size of things.
  274. d.measure = elt("div", null, "CodeMirror-measure");
  275. // When lines outside of the viewport are measured, they are drawn in this.
  276. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  277. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  278. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  279. null, "position: relative; outline: none");
  280. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  281. // Moved around its parent to cover visible view.
  282. d.mover = elt("div", [lines], null, "position: relative");
  283. // Set to the height of the document, allowing scrolling.
  284. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  285. d.sizerWidth = null;
  286. // Behavior of elts with overflow: auto and padding is
  287. // inconsistent across browsers. This is used to ensure the
  288. // scrollable area is big enough.
  289. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  290. // Will contain the gutters, if any.
  291. d.gutters = elt("div", null, "CodeMirror-gutters");
  292. d.lineGutter = null;
  293. // Actual scrollable element.
  294. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  295. d.scroller.setAttribute("tabIndex", "-1");
  296. // The element in which the editor lives.
  297. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  298. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  299. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  300. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  301. if (place) {
  302. if (place.appendChild) { place.appendChild(d.wrapper); }
  303. else { place(d.wrapper); }
  304. }
  305. // Current rendered range (may be bigger than the view window).
  306. d.viewFrom = d.viewTo = doc.first;
  307. d.reportedViewFrom = d.reportedViewTo = doc.first;
  308. // Information about the rendered lines.
  309. d.view = [];
  310. d.renderedView = null;
  311. // Holds info about a single rendered line when it was rendered
  312. // for measurement, while not in view.
  313. d.externalMeasured = null;
  314. // Empty space (in pixels) above the view
  315. d.viewOffset = 0;
  316. d.lastWrapHeight = d.lastWrapWidth = 0;
  317. d.updateLineNumbers = null;
  318. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  319. d.scrollbarsClipped = false;
  320. // Used to only resize the line number gutter when necessary (when
  321. // the amount of lines crosses a boundary that makes its width change)
  322. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  323. // Set to true when a non-horizontal-scrolling line widget is
  324. // added. As an optimization, line widget aligning is skipped when
  325. // this is false.
  326. d.alignWidgets = false;
  327. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  328. // Tracks the maximum line length so that the horizontal scrollbar
  329. // can be kept static when scrolling.
  330. d.maxLine = null;
  331. d.maxLineLength = 0;
  332. d.maxLineChanged = false;
  333. // Used for measuring wheel scrolling granularity
  334. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  335. // True when shift is held down.
  336. d.shift = false;
  337. // Used to track whether anything happened since the context menu
  338. // was opened.
  339. d.selForContextMenu = null;
  340. d.activeTouch = null;
  341. input.init(d);
  342. }
  343. // Find the line object corresponding to the given line number.
  344. function getLine(doc, n) {
  345. n -= doc.first;
  346. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  347. var chunk = doc;
  348. while (!chunk.lines) {
  349. for (var i = 0;; ++i) {
  350. var child = chunk.children[i], sz = child.chunkSize();
  351. if (n < sz) { chunk = child; break }
  352. n -= sz;
  353. }
  354. }
  355. return chunk.lines[n]
  356. }
  357. // Get the part of a document between two positions, as an array of
  358. // strings.
  359. function getBetween(doc, start, end) {
  360. var out = [], n = start.line;
  361. doc.iter(start.line, end.line + 1, function (line) {
  362. var text = line.text;
  363. if (n == end.line) { text = text.slice(0, end.ch); }
  364. if (n == start.line) { text = text.slice(start.ch); }
  365. out.push(text);
  366. ++n;
  367. });
  368. return out
  369. }
  370. // Get the lines between from and to, as array of strings.
  371. function getLines(doc, from, to) {
  372. var out = [];
  373. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  374. return out
  375. }
  376. // Update the height of a line, propagating the height change
  377. // upwards to parent nodes.
  378. function updateLineHeight(line, height) {
  379. var diff = height - line.height;
  380. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  381. }
  382. // Given a line object, find its line number by walking up through
  383. // its parent links.
  384. function lineNo(line) {
  385. if (line.parent == null) { return null }
  386. var cur = line.parent, no = indexOf(cur.lines, line);
  387. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  388. for (var i = 0;; ++i) {
  389. if (chunk.children[i] == cur) { break }
  390. no += chunk.children[i].chunkSize();
  391. }
  392. }
  393. return no + cur.first
  394. }
  395. // Find the line at the given vertical position, using the height
  396. // information in the document tree.
  397. function lineAtHeight(chunk, h) {
  398. var n = chunk.first;
  399. outer: do {
  400. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  401. var child = chunk.children[i$1], ch = child.height;
  402. if (h < ch) { chunk = child; continue outer }
  403. h -= ch;
  404. n += child.chunkSize();
  405. }
  406. return n
  407. } while (!chunk.lines)
  408. var i = 0;
  409. for (; i < chunk.lines.length; ++i) {
  410. var line = chunk.lines[i], lh = line.height;
  411. if (h < lh) { break }
  412. h -= lh;
  413. }
  414. return n + i
  415. }
  416. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  417. function lineNumberFor(options, i) {
  418. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  419. }
  420. // A Pos instance represents a position within the text.
  421. function Pos(line, ch, sticky) {
  422. if ( sticky === void 0 ) sticky = null;
  423. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  424. this.line = line;
  425. this.ch = ch;
  426. this.sticky = sticky;
  427. }
  428. // Compare two positions, return 0 if they are the same, a negative
  429. // number when a is less, and a positive number otherwise.
  430. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  431. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  432. function copyPos(x) {return Pos(x.line, x.ch)}
  433. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  434. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  435. // Most of the external API clips given positions to make sure they
  436. // actually exist within the document.
  437. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  438. function clipPos(doc, pos) {
  439. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  440. var last = doc.first + doc.size - 1;
  441. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  442. return clipToLen(pos, getLine(doc, pos.line).text.length)
  443. }
  444. function clipToLen(pos, linelen) {
  445. var ch = pos.ch;
  446. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  447. else if (ch < 0) { return Pos(pos.line, 0) }
  448. else { return pos }
  449. }
  450. function clipPosArray(doc, array) {
  451. var out = [];
  452. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  453. return out
  454. }
  455. // Optimize some code when these features are not used.
  456. var sawReadOnlySpans = false;
  457. var sawCollapsedSpans = false;
  458. function seeReadOnlySpans() {
  459. sawReadOnlySpans = true;
  460. }
  461. function seeCollapsedSpans() {
  462. sawCollapsedSpans = true;
  463. }
  464. // TEXTMARKER SPANS
  465. function MarkedSpan(marker, from, to) {
  466. this.marker = marker;
  467. this.from = from; this.to = to;
  468. }
  469. // Search an array of spans for a span matching the given marker.
  470. function getMarkedSpanFor(spans, marker) {
  471. if (spans) { for (var i = 0; i < spans.length; ++i) {
  472. var span = spans[i];
  473. if (span.marker == marker) { return span }
  474. } }
  475. }
  476. // Remove a span from an array, returning undefined if no spans are
  477. // left (we don't store arrays for lines without spans).
  478. function removeMarkedSpan(spans, span) {
  479. var r;
  480. for (var i = 0; i < spans.length; ++i)
  481. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  482. return r
  483. }
  484. // Add a span to a line.
  485. function addMarkedSpan(line, span) {
  486. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  487. span.marker.attachLine(line);
  488. }
  489. // Used for the algorithm that adjusts markers for a change in the
  490. // document. These functions cut an array of spans at a given
  491. // character position, returning an array of remaining chunks (or
  492. // undefined if nothing remains).
  493. function markedSpansBefore(old, startCh, isInsert) {
  494. var nw;
  495. if (old) { for (var i = 0; i < old.length; ++i) {
  496. var span = old[i], marker = span.marker;
  497. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  498. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  499. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  500. }
  501. } }
  502. return nw
  503. }
  504. function markedSpansAfter(old, endCh, isInsert) {
  505. var nw;
  506. if (old) { for (var i = 0; i < old.length; ++i) {
  507. var span = old[i], marker = span.marker;
  508. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  509. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  510. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  511. span.to == null ? null : span.to - endCh));
  512. }
  513. } }
  514. return nw
  515. }
  516. // Given a change object, compute the new set of marker spans that
  517. // cover the line in which the change took place. Removes spans
  518. // entirely within the change, reconnects spans belonging to the
  519. // same marker that appear on both sides of the change, and cuts off
  520. // spans partially within the change. Returns an array of span
  521. // arrays with one element for each line in (after) the change.
  522. function stretchSpansOverChange(doc, change) {
  523. if (change.full) { return null }
  524. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  525. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  526. if (!oldFirst && !oldLast) { return null }
  527. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  528. // Get the spans that 'stick out' on both sides
  529. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  530. var last = markedSpansAfter(oldLast, endCh, isInsert);
  531. // Next, merge those two ends
  532. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  533. if (first) {
  534. // Fix up .to properties of first
  535. for (var i = 0; i < first.length; ++i) {
  536. var span = first[i];
  537. if (span.to == null) {
  538. var found = getMarkedSpanFor(last, span.marker);
  539. if (!found) { span.to = startCh; }
  540. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  541. }
  542. }
  543. }
  544. if (last) {
  545. // Fix up .from in last (or move them into first in case of sameLine)
  546. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  547. var span$1 = last[i$1];
  548. if (span$1.to != null) { span$1.to += offset; }
  549. if (span$1.from == null) {
  550. var found$1 = getMarkedSpanFor(first, span$1.marker);
  551. if (!found$1) {
  552. span$1.from = offset;
  553. if (sameLine) { (first || (first = [])).push(span$1); }
  554. }
  555. } else {
  556. span$1.from += offset;
  557. if (sameLine) { (first || (first = [])).push(span$1); }
  558. }
  559. }
  560. }
  561. // Make sure we didn't create any zero-length spans
  562. if (first) { first = clearEmptySpans(first); }
  563. if (last && last != first) { last = clearEmptySpans(last); }
  564. var newMarkers = [first];
  565. if (!sameLine) {
  566. // Fill gap with whole-line-spans
  567. var gap = change.text.length - 2, gapMarkers;
  568. if (gap > 0 && first)
  569. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  570. { if (first[i$2].to == null)
  571. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  572. for (var i$3 = 0; i$3 < gap; ++i$3)
  573. { newMarkers.push(gapMarkers); }
  574. newMarkers.push(last);
  575. }
  576. return newMarkers
  577. }
  578. // Remove spans that are empty and don't have a clearWhenEmpty
  579. // option of false.
  580. function clearEmptySpans(spans) {
  581. for (var i = 0; i < spans.length; ++i) {
  582. var span = spans[i];
  583. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  584. { spans.splice(i--, 1); }
  585. }
  586. if (!spans.length) { return null }
  587. return spans
  588. }
  589. // Used to 'clip' out readOnly ranges when making a change.
  590. function removeReadOnlyRanges(doc, from, to) {
  591. var markers = null;
  592. doc.iter(from.line, to.line + 1, function (line) {
  593. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  594. var mark = line.markedSpans[i].marker;
  595. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  596. { (markers || (markers = [])).push(mark); }
  597. } }
  598. });
  599. if (!markers) { return null }
  600. var parts = [{from: from, to: to}];
  601. for (var i = 0; i < markers.length; ++i) {
  602. var mk = markers[i], m = mk.find(0);
  603. for (var j = 0; j < parts.length; ++j) {
  604. var p = parts[j];
  605. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  606. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  607. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  608. { newParts.push({from: p.from, to: m.from}); }
  609. if (dto > 0 || !mk.inclusiveRight && !dto)
  610. { newParts.push({from: m.to, to: p.to}); }
  611. parts.splice.apply(parts, newParts);
  612. j += newParts.length - 3;
  613. }
  614. }
  615. return parts
  616. }
  617. // Connect or disconnect spans from a line.
  618. function detachMarkedSpans(line) {
  619. var spans = line.markedSpans;
  620. if (!spans) { return }
  621. for (var i = 0; i < spans.length; ++i)
  622. { spans[i].marker.detachLine(line); }
  623. line.markedSpans = null;
  624. }
  625. function attachMarkedSpans(line, spans) {
  626. if (!spans) { return }
  627. for (var i = 0; i < spans.length; ++i)
  628. { spans[i].marker.attachLine(line); }
  629. line.markedSpans = spans;
  630. }
  631. // Helpers used when computing which overlapping collapsed span
  632. // counts as the larger one.
  633. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  634. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  635. // Returns a number indicating which of two overlapping collapsed
  636. // spans is larger (and thus includes the other). Falls back to
  637. // comparing ids when the spans cover exactly the same range.
  638. function compareCollapsedMarkers(a, b) {
  639. var lenDiff = a.lines.length - b.lines.length;
  640. if (lenDiff != 0) { return lenDiff }
  641. var aPos = a.find(), bPos = b.find();
  642. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  643. if (fromCmp) { return -fromCmp }
  644. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  645. if (toCmp) { return toCmp }
  646. return b.id - a.id
  647. }
  648. // Find out whether a line ends or starts in a collapsed span. If
  649. // so, return the marker for that span.
  650. function collapsedSpanAtSide(line, start) {
  651. var sps = sawCollapsedSpans && line.markedSpans, found;
  652. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  653. sp = sps[i];
  654. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  655. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  656. { found = sp.marker; }
  657. } }
  658. return found
  659. }
  660. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  661. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  662. // Test whether there exists a collapsed span that partially
  663. // overlaps (covers the start or end, but not both) of a new span.
  664. // Such overlap is not allowed.
  665. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  666. var line = getLine(doc, lineNo$$1);
  667. var sps = sawCollapsedSpans && line.markedSpans;
  668. if (sps) { for (var i = 0; i < sps.length; ++i) {
  669. var sp = sps[i];
  670. if (!sp.marker.collapsed) { continue }
  671. var found = sp.marker.find(0);
  672. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  673. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  674. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  675. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  676. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  677. { return true }
  678. } }
  679. }
  680. // A visual line is a line as drawn on the screen. Folding, for
  681. // example, can cause multiple logical lines to appear on the same
  682. // visual line. This finds the start of the visual line that the
  683. // given line is part of (usually that is the line itself).
  684. function visualLine(line) {
  685. var merged;
  686. while (merged = collapsedSpanAtStart(line))
  687. { line = merged.find(-1, true).line; }
  688. return line
  689. }
  690. function visualLineEnd(line) {
  691. var merged;
  692. while (merged = collapsedSpanAtEnd(line))
  693. { line = merged.find(1, true).line; }
  694. return line
  695. }
  696. // Returns an array of logical lines that continue the visual line
  697. // started by the argument, or undefined if there are no such lines.
  698. function visualLineContinued(line) {
  699. var merged, lines;
  700. while (merged = collapsedSpanAtEnd(line)) {
  701. line = merged.find(1, true).line
  702. ;(lines || (lines = [])).push(line);
  703. }
  704. return lines
  705. }
  706. // Get the line number of the start of the visual line that the
  707. // given line number is part of.
  708. function visualLineNo(doc, lineN) {
  709. var line = getLine(doc, lineN), vis = visualLine(line);
  710. if (line == vis) { return lineN }
  711. return lineNo(vis)
  712. }
  713. // Get the line number of the start of the next visual line after
  714. // the given line.
  715. function visualLineEndNo(doc, lineN) {
  716. if (lineN > doc.lastLine()) { return lineN }
  717. var line = getLine(doc, lineN), merged;
  718. if (!lineIsHidden(doc, line)) { return lineN }
  719. while (merged = collapsedSpanAtEnd(line))
  720. { line = merged.find(1, true).line; }
  721. return lineNo(line) + 1
  722. }
  723. // Compute whether a line is hidden. Lines count as hidden when they
  724. // are part of a visual line that starts with another line, or when
  725. // they are entirely covered by collapsed, non-widget span.
  726. function lineIsHidden(doc, line) {
  727. var sps = sawCollapsedSpans && line.markedSpans;
  728. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  729. sp = sps[i];
  730. if (!sp.marker.collapsed) { continue }
  731. if (sp.from == null) { return true }
  732. if (sp.marker.widgetNode) { continue }
  733. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  734. { return true }
  735. } }
  736. }
  737. function lineIsHiddenInner(doc, line, span) {
  738. if (span.to == null) {
  739. var end = span.marker.find(1, true);
  740. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  741. }
  742. if (span.marker.inclusiveRight && span.to == line.text.length)
  743. { return true }
  744. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  745. sp = line.markedSpans[i];
  746. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  747. (sp.to == null || sp.to != span.from) &&
  748. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  749. lineIsHiddenInner(doc, line, sp)) { return true }
  750. }
  751. }
  752. // Find the height above the given line.
  753. function heightAtLine(lineObj) {
  754. lineObj = visualLine(lineObj);
  755. var h = 0, chunk = lineObj.parent;
  756. for (var i = 0; i < chunk.lines.length; ++i) {
  757. var line = chunk.lines[i];
  758. if (line == lineObj) { break }
  759. else { h += line.height; }
  760. }
  761. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  762. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  763. var cur = p.children[i$1];
  764. if (cur == chunk) { break }
  765. else { h += cur.height; }
  766. }
  767. }
  768. return h
  769. }
  770. // Compute the character length of a line, taking into account
  771. // collapsed ranges (see markText) that might hide parts, and join
  772. // other lines onto it.
  773. function lineLength(line) {
  774. if (line.height == 0) { return 0 }
  775. var len = line.text.length, merged, cur = line;
  776. while (merged = collapsedSpanAtStart(cur)) {
  777. var found = merged.find(0, true);
  778. cur = found.from.line;
  779. len += found.from.ch - found.to.ch;
  780. }
  781. cur = line;
  782. while (merged = collapsedSpanAtEnd(cur)) {
  783. var found$1 = merged.find(0, true);
  784. len -= cur.text.length - found$1.from.ch;
  785. cur = found$1.to.line;
  786. len += cur.text.length - found$1.to.ch;
  787. }
  788. return len
  789. }
  790. // Find the longest line in the document.
  791. function findMaxLine(cm) {
  792. var d = cm.display, doc = cm.doc;
  793. d.maxLine = getLine(doc, doc.first);
  794. d.maxLineLength = lineLength(d.maxLine);
  795. d.maxLineChanged = true;
  796. doc.iter(function (line) {
  797. var len = lineLength(line);
  798. if (len > d.maxLineLength) {
  799. d.maxLineLength = len;
  800. d.maxLine = line;
  801. }
  802. });
  803. }
  804. // BIDI HELPERS
  805. function iterateBidiSections(order, from, to, f) {
  806. if (!order) { return f(from, to, "ltr") }
  807. var found = false;
  808. for (var i = 0; i < order.length; ++i) {
  809. var part = order[i];
  810. if (part.from < to && part.to > from || from == to && part.to == from) {
  811. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  812. found = true;
  813. }
  814. }
  815. if (!found) { f(from, to, "ltr"); }
  816. }
  817. var bidiOther = null;
  818. function getBidiPartAt(order, ch, sticky) {
  819. var found;
  820. bidiOther = null;
  821. for (var i = 0; i < order.length; ++i) {
  822. var cur = order[i];
  823. if (cur.from < ch && cur.to > ch) { return i }
  824. if (cur.to == ch) {
  825. if (cur.from != cur.to && sticky == "before") { found = i; }
  826. else { bidiOther = i; }
  827. }
  828. if (cur.from == ch) {
  829. if (cur.from != cur.to && sticky != "before") { found = i; }
  830. else { bidiOther = i; }
  831. }
  832. }
  833. return found != null ? found : bidiOther
  834. }
  835. // Bidirectional ordering algorithm
  836. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  837. // that this (partially) implements.
  838. // One-char codes used for character types:
  839. // L (L): Left-to-Right
  840. // R (R): Right-to-Left
  841. // r (AL): Right-to-Left Arabic
  842. // 1 (EN): European Number
  843. // + (ES): European Number Separator
  844. // % (ET): European Number Terminator
  845. // n (AN): Arabic Number
  846. // , (CS): Common Number Separator
  847. // m (NSM): Non-Spacing Mark
  848. // b (BN): Boundary Neutral
  849. // s (B): Paragraph Separator
  850. // t (S): Segment Separator
  851. // w (WS): Whitespace
  852. // N (ON): Other Neutrals
  853. // Returns null if characters are ordered as they appear
  854. // (left-to-right), or an array of sections ({from, to, level}
  855. // objects) in the order in which they occur visually.
  856. var bidiOrdering = (function() {
  857. // Character types for codepoints 0 to 0xff
  858. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  859. // Character types for codepoints 0x600 to 0x6f9
  860. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  861. function charType(code) {
  862. if (code <= 0xf7) { return lowTypes.charAt(code) }
  863. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  864. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  865. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  866. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  867. else if (code == 0x200c) { return "b" }
  868. else { return "L" }
  869. }
  870. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  871. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  872. function BidiSpan(level, from, to) {
  873. this.level = level;
  874. this.from = from; this.to = to;
  875. }
  876. return function(str, direction) {
  877. var outerType = direction == "ltr" ? "L" : "R";
  878. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  879. var len = str.length, types = [];
  880. for (var i = 0; i < len; ++i)
  881. { types.push(charType(str.charCodeAt(i))); }
  882. // W1. Examine each non-spacing mark (NSM) in the level run, and
  883. // change the type of the NSM to the type of the previous
  884. // character. If the NSM is at the start of the level run, it will
  885. // get the type of sor.
  886. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  887. var type = types[i$1];
  888. if (type == "m") { types[i$1] = prev; }
  889. else { prev = type; }
  890. }
  891. // W2. Search backwards from each instance of a European number
  892. // until the first strong type (R, L, AL, or sor) is found. If an
  893. // AL is found, change the type of the European number to Arabic
  894. // number.
  895. // W3. Change all ALs to R.
  896. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  897. var type$1 = types[i$2];
  898. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  899. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  900. }
  901. // W4. A single European separator between two European numbers
  902. // changes to a European number. A single common separator between
  903. // two numbers of the same type changes to that type.
  904. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  905. var type$2 = types[i$3];
  906. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  907. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  908. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  909. prev$1 = type$2;
  910. }
  911. // W5. A sequence of European terminators adjacent to European
  912. // numbers changes to all European numbers.
  913. // W6. Otherwise, separators and terminators change to Other
  914. // Neutral.
  915. for (var i$4 = 0; i$4 < len; ++i$4) {
  916. var type$3 = types[i$4];
  917. if (type$3 == ",") { types[i$4] = "N"; }
  918. else if (type$3 == "%") {
  919. var end = (void 0);
  920. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  921. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  922. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  923. i$4 = end - 1;
  924. }
  925. }
  926. // W7. Search backwards from each instance of a European number
  927. // until the first strong type (R, L, or sor) is found. If an L is
  928. // found, then change the type of the European number to L.
  929. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  930. var type$4 = types[i$5];
  931. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  932. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  933. }
  934. // N1. A sequence of neutrals takes the direction of the
  935. // surrounding strong text if the text on both sides has the same
  936. // direction. European and Arabic numbers act as if they were R in
  937. // terms of their influence on neutrals. Start-of-level-run (sor)
  938. // and end-of-level-run (eor) are used at level run boundaries.
  939. // N2. Any remaining neutrals take the embedding direction.
  940. for (var i$6 = 0; i$6 < len; ++i$6) {
  941. if (isNeutral.test(types[i$6])) {
  942. var end$1 = (void 0);
  943. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  944. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  945. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  946. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  947. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  948. i$6 = end$1 - 1;
  949. }
  950. }
  951. // Here we depart from the documented algorithm, in order to avoid
  952. // building up an actual levels array. Since there are only three
  953. // levels (0, 1, 2) in an implementation that doesn't take
  954. // explicit embedding into account, we can build up the order on
  955. // the fly, without following the level-based algorithm.
  956. var order = [], m;
  957. for (var i$7 = 0; i$7 < len;) {
  958. if (countsAsLeft.test(types[i$7])) {
  959. var start = i$7;
  960. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  961. order.push(new BidiSpan(0, start, i$7));
  962. } else {
  963. var pos = i$7, at = order.length;
  964. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  965. for (var j$2 = pos; j$2 < i$7;) {
  966. if (countsAsNum.test(types[j$2])) {
  967. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  968. var nstart = j$2;
  969. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  970. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  971. pos = j$2;
  972. } else { ++j$2; }
  973. }
  974. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  975. }
  976. }
  977. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  978. order[0].from = m[0].length;
  979. order.unshift(new BidiSpan(0, 0, m[0].length));
  980. }
  981. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  982. lst(order).to -= m[0].length;
  983. order.push(new BidiSpan(0, len - m[0].length, len));
  984. }
  985. return direction == "rtl" ? order.reverse() : order
  986. }
  987. })();
  988. // Get the bidi ordering for the given line (and cache it). Returns
  989. // false for lines that are fully left-to-right, and an array of
  990. // BidiSpan objects otherwise.
  991. function getOrder(line, direction) {
  992. var order = line.order;
  993. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  994. return order
  995. }
  996. function moveCharLogically(line, ch, dir) {
  997. var target = skipExtendingChars(line.text, ch + dir, dir);
  998. return target < 0 || target > line.text.length ? null : target
  999. }
  1000. function moveLogically(line, start, dir) {
  1001. var ch = moveCharLogically(line, start.ch, dir);
  1002. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  1003. }
  1004. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  1005. if (visually) {
  1006. var order = getOrder(lineObj, cm.doc.direction);
  1007. if (order) {
  1008. var part = dir < 0 ? lst(order) : order[0];
  1009. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  1010. var sticky = moveInStorageOrder ? "after" : "before";
  1011. var ch;
  1012. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  1013. // it could be that the last bidi part is not on the last visual line,
  1014. // since visual lines contain content order-consecutive chunks.
  1015. // Thus, in rtl, we are looking for the first (content-order) character
  1016. // in the rtl chunk that is on the last line (that is, the same line
  1017. // as the last (content-order) character).
  1018. if (part.level > 0) {
  1019. var prep = prepareMeasureForLine(cm, lineObj);
  1020. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  1021. var targetTop = measureCharPrepared(cm, prep, ch).top;
  1022. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  1023. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1, true); }
  1024. } else { ch = dir < 0 ? part.to : part.from; }
  1025. return new Pos(lineNo, ch, sticky)
  1026. }
  1027. }
  1028. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  1029. }
  1030. function moveVisually(cm, line, start, dir) {
  1031. var bidi = getOrder(line, cm.doc.direction);
  1032. if (!bidi) { return moveLogically(line, start, dir) }
  1033. if (start.ch >= line.text.length) {
  1034. start.ch = line.text.length;
  1035. start.sticky = "before";
  1036. } else if (start.ch <= 0) {
  1037. start.ch = 0;
  1038. start.sticky = "after";
  1039. }
  1040. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  1041. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  1042. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  1043. // nothing interesting happens.
  1044. return moveLogically(line, start, dir)
  1045. }
  1046. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  1047. var prep;
  1048. var getWrappedLineExtent = function (ch) {
  1049. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  1050. prep = prep || prepareMeasureForLine(cm, line);
  1051. return wrappedLineExtentChar(cm, line, prep, ch)
  1052. };
  1053. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  1054. if (cm.doc.direction == "rtl" || part.level == 1) {
  1055. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  1056. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  1057. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  1058. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  1059. var sticky = moveInStorageOrder ? "before" : "after";
  1060. return new Pos(start.line, ch, sticky)
  1061. }
  1062. }
  1063. // Case 3: Could not move within this bidi part in this visual line, so leave
  1064. // the current bidi part
  1065. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  1066. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  1067. ? new Pos(start.line, mv(ch, 1), "before")
  1068. : new Pos(start.line, ch, "after"); };
  1069. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  1070. var part = bidi[partPos];
  1071. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  1072. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  1073. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  1074. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  1075. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  1076. }
  1077. };
  1078. // Case 3a: Look for other bidi parts on the same visual line
  1079. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  1080. if (res) { return res }
  1081. // Case 3b: Look for other bidi parts on the next visual line
  1082. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  1083. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  1084. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  1085. if (res) { return res }
  1086. }
  1087. // Case 4: Nowhere to move
  1088. return null
  1089. }
  1090. // EVENT HANDLING
  1091. // Lightweight event framework. on/off also work on DOM nodes,
  1092. // registering native DOM handlers.
  1093. var noHandlers = [];
  1094. var on = function(emitter, type, f) {
  1095. if (emitter.addEventListener) {
  1096. emitter.addEventListener(type, f, false);
  1097. } else if (emitter.attachEvent) {
  1098. emitter.attachEvent("on" + type, f);
  1099. } else {
  1100. var map$$1 = emitter._handlers || (emitter._handlers = {});
  1101. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  1102. }
  1103. };
  1104. function getHandlers(emitter, type) {
  1105. return emitter._handlers && emitter._handlers[type] || noHandlers
  1106. }
  1107. function off(emitter, type, f) {
  1108. if (emitter.removeEventListener) {
  1109. emitter.removeEventListener(type, f, false);
  1110. } else if (emitter.detachEvent) {
  1111. emitter.detachEvent("on" + type, f);
  1112. } else {
  1113. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  1114. if (arr) {
  1115. var index = indexOf(arr, f);
  1116. if (index > -1)
  1117. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  1118. }
  1119. }
  1120. }
  1121. function signal(emitter, type /*, values...*/) {
  1122. var handlers = getHandlers(emitter, type);
  1123. if (!handlers.length) { return }
  1124. var args = Array.prototype.slice.call(arguments, 2);
  1125. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  1126. }
  1127. // The DOM events that CodeMirror handles can be overridden by
  1128. // registering a (non-DOM) handler on the editor for the event name,
  1129. // and preventDefault-ing the event in that handler.
  1130. function signalDOMEvent(cm, e, override) {
  1131. if (typeof e == "string")
  1132. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  1133. signal(cm, override || e.type, cm, e);
  1134. return e_defaultPrevented(e) || e.codemirrorIgnore
  1135. }
  1136. function signalCursorActivity(cm) {
  1137. var arr = cm._handlers && cm._handlers.cursorActivity;
  1138. if (!arr) { return }
  1139. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  1140. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1141. { set.push(arr[i]); } }
  1142. }
  1143. function hasHandler(emitter, type) {
  1144. return getHandlers(emitter, type).length > 0
  1145. }
  1146. // Add on and off methods to a constructor's prototype, to make
  1147. // registering events on such objects more convenient.
  1148. function eventMixin(ctor) {
  1149. ctor.prototype.on = function(type, f) {on(this, type, f);};
  1150. ctor.prototype.off = function(type, f) {off(this, type, f);};
  1151. }
  1152. // Due to the fact that we still support jurassic IE versions, some
  1153. // compatibility wrappers are needed.
  1154. function e_preventDefault(e) {
  1155. if (e.preventDefault) { e.preventDefault(); }
  1156. else { e.returnValue = false; }
  1157. }
  1158. function e_stopPropagation(e) {
  1159. if (e.stopPropagation) { e.stopPropagation(); }
  1160. else { e.cancelBubble = true; }
  1161. }
  1162. function e_defaultPrevented(e) {
  1163. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1164. }
  1165. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  1166. function e_target(e) {return e.target || e.srcElement}
  1167. function e_button(e) {
  1168. var b = e.which;
  1169. if (b == null) {
  1170. if (e.button & 1) { b = 1; }
  1171. else if (e.button & 2) { b = 3; }
  1172. else if (e.button & 4) { b = 2; }
  1173. }
  1174. if (mac && e.ctrlKey && b == 1) { b = 3; }
  1175. return b
  1176. }
  1177. // Detect drag-and-drop
  1178. var dragAndDrop = function() {
  1179. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1180. // couldn't get it to work yet.
  1181. if (ie && ie_version < 9) { return false }
  1182. var div = elt('div');
  1183. return "draggable" in div || "dragDrop" in div
  1184. }();
  1185. var zwspSupported;
  1186. function zeroWidthElement(measure) {
  1187. if (zwspSupported == null) {
  1188. var test = elt("span", "\u200b");
  1189. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  1190. if (measure.firstChild.offsetHeight != 0)
  1191. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  1192. }
  1193. var node = zwspSupported ? elt("span", "\u200b") :
  1194. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  1195. node.setAttribute("cm-text", "");
  1196. return node
  1197. }
  1198. // Feature-detect IE's crummy client rect reporting for bidi text
  1199. var badBidiRects;
  1200. function hasBadBidiRects(measure) {
  1201. if (badBidiRects != null) { return badBidiRects }
  1202. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  1203. var r0 = range(txt, 0, 1).getBoundingClientRect();
  1204. var r1 = range(txt, 1, 2).getBoundingClientRect();
  1205. removeChildren(measure);
  1206. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1207. return badBidiRects = (r1.right - r0.right < 3)
  1208. }
  1209. // See if "".split is the broken IE version, if so, provide an
  1210. // alternative way to split lines.
  1211. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1212. var pos = 0, result = [], l = string.length;
  1213. while (pos <= l) {
  1214. var nl = string.indexOf("\n", pos);
  1215. if (nl == -1) { nl = string.length; }
  1216. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  1217. var rt = line.indexOf("\r");
  1218. if (rt != -1) {
  1219. result.push(line.slice(0, rt));
  1220. pos += rt + 1;
  1221. } else {
  1222. result.push(line);
  1223. pos = nl + 1;
  1224. }
  1225. }
  1226. return result
  1227. } : function (string) { return string.split(/\r\n?|\n/); };
  1228. var hasSelection = window.getSelection ? function (te) {
  1229. try { return te.selectionStart != te.selectionEnd }
  1230. catch(e) { return false }
  1231. } : function (te) {
  1232. var range$$1;
  1233. try {range$$1 = te.ownerDocument.selection.createRange();}
  1234. catch(e) {}
  1235. if (!range$$1 || range$$1.parentElement() != te) { return false }
  1236. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  1237. };
  1238. var hasCopyEvent = (function () {
  1239. var e = elt("div");
  1240. if ("oncopy" in e) { return true }
  1241. e.setAttribute("oncopy", "return;");
  1242. return typeof e.oncopy == "function"
  1243. })();
  1244. var badZoomedRects = null;
  1245. function hasBadZoomedRects(measure) {
  1246. if (badZoomedRects != null) { return badZoomedRects }
  1247. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  1248. var normal = node.getBoundingClientRect();
  1249. var fromRange = range(node, 0, 1).getBoundingClientRect();
  1250. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1251. }
  1252. // Known modes, by name and by MIME
  1253. var modes = {};
  1254. var mimeModes = {};
  1255. // Extra arguments are stored as the mode's dependencies, which is
  1256. // used by (legacy) mechanisms like loadmode.js to automatically
  1257. // load a mode. (Preferred mechanism is the require/define calls.)
  1258. function defineMode(name, mode) {
  1259. if (arguments.length > 2)
  1260. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  1261. modes[name] = mode;
  1262. }
  1263. function defineMIME(mime, spec) {
  1264. mimeModes[mime] = spec;
  1265. }
  1266. // Given a MIME type, a {name, ...options} config object, or a name
  1267. // string, return a mode config object.
  1268. function resolveMode(spec) {
  1269. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1270. spec = mimeModes[spec];
  1271. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1272. var found = mimeModes[spec.name];
  1273. if (typeof found == "string") { found = {name: found}; }
  1274. spec = createObj(found, spec);
  1275. spec.name = found.name;
  1276. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1277. return resolveMode("application/xml")
  1278. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1279. return resolveMode("application/json")
  1280. }
  1281. if (typeof spec == "string") { return {name: spec} }
  1282. else { return spec || {name: "null"} }
  1283. }
  1284. // Given a mode spec (anything that resolveMode accepts), find and
  1285. // initialize an actual mode object.
  1286. function getMode(options, spec) {
  1287. spec = resolveMode(spec);
  1288. var mfactory = modes[spec.name];
  1289. if (!mfactory) { return getMode(options, "text/plain") }
  1290. var modeObj = mfactory(options, spec);
  1291. if (modeExtensions.hasOwnProperty(spec.name)) {
  1292. var exts = modeExtensions[spec.name];
  1293. for (var prop in exts) {
  1294. if (!exts.hasOwnProperty(prop)) { continue }
  1295. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  1296. modeObj[prop] = exts[prop];
  1297. }
  1298. }
  1299. modeObj.name = spec.name;
  1300. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  1301. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1302. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  1303. return modeObj
  1304. }
  1305. // This can be used to attach properties to mode objects from
  1306. // outside the actual mode definition.
  1307. var modeExtensions = {};
  1308. function extendMode(mode, properties) {
  1309. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  1310. copyObj(properties, exts);
  1311. }
  1312. function copyState(mode, state) {
  1313. if (state === true) { return state }
  1314. if (mode.copyState) { return mode.copyState(state) }
  1315. var nstate = {};
  1316. for (var n in state) {
  1317. var val = state[n];
  1318. if (val instanceof Array) { val = val.concat([]); }
  1319. nstate[n] = val;
  1320. }
  1321. return nstate
  1322. }
  1323. // Given a mode and a state (for that mode), find the inner mode and
  1324. // state at the position that the state refers to.
  1325. function innerMode(mode, state) {
  1326. var info;
  1327. while (mode.innerMode) {
  1328. info = mode.innerMode(state);
  1329. if (!info || info.mode == mode) { break }
  1330. state = info.state;
  1331. mode = info.mode;
  1332. }
  1333. return info || {mode: mode, state: state}
  1334. }
  1335. function startState(mode, a1, a2) {
  1336. return mode.startState ? mode.startState(a1, a2) : true
  1337. }
  1338. // STRING STREAM
  1339. // Fed to the mode parsers, provides helper functions to make
  1340. // parsers more succinct.
  1341. var StringStream = function(string, tabSize) {
  1342. this.pos = this.start = 0;
  1343. this.string = string;
  1344. this.tabSize = tabSize || 8;
  1345. this.lastColumnPos = this.lastColumnValue = 0;
  1346. this.lineStart = 0;
  1347. };
  1348. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1349. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1350. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1351. StringStream.prototype.next = function () {
  1352. if (this.pos < this.string.length)
  1353. { return this.string.charAt(this.pos++) }
  1354. };
  1355. StringStream.prototype.eat = function (match) {
  1356. var ch = this.string.charAt(this.pos);
  1357. var ok;
  1358. if (typeof match == "string") { ok = ch == match; }
  1359. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  1360. if (ok) {++this.pos; return ch}
  1361. };
  1362. StringStream.prototype.eatWhile = function (match) {
  1363. var start = this.pos;
  1364. while (this.eat(match)){}
  1365. return this.pos > start
  1366. };
  1367. StringStream.prototype.eatSpace = function () {
  1368. var this$1 = this;
  1369. var start = this.pos;
  1370. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  1371. return this.pos > start
  1372. };
  1373. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  1374. StringStream.prototype.skipTo = function (ch) {
  1375. var found = this.string.indexOf(ch, this.pos);
  1376. if (found > -1) {this.pos = found; return true}
  1377. };
  1378. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  1379. StringStream.prototype.column = function () {
  1380. if (this.lastColumnPos < this.start) {
  1381. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  1382. this.lastColumnPos = this.start;
  1383. }
  1384. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1385. };
  1386. StringStream.prototype.indentation = function () {
  1387. return countColumn(this.string, null, this.tabSize) -
  1388. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1389. };
  1390. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1391. if (typeof pattern == "string") {
  1392. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  1393. var substr = this.string.substr(this.pos, pattern.length);
  1394. if (cased(substr) == cased(pattern)) {
  1395. if (consume !== false) { this.pos += pattern.length; }
  1396. return true
  1397. }
  1398. } else {
  1399. var match = this.string.slice(this.pos).match(pattern);
  1400. if (match && match.index > 0) { return null }
  1401. if (match && consume !== false) { this.pos += match[0].length; }
  1402. return match
  1403. }
  1404. };
  1405. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1406. StringStream.prototype.hideFirstChars = function (n, inner) {
  1407. this.lineStart += n;
  1408. try { return inner() }
  1409. finally { this.lineStart -= n; }
  1410. };
  1411. // Compute a style array (an array starting with a mode generation
  1412. // -- for invalidation -- followed by pairs of end positions and
  1413. // style strings), which is used to highlight the tokens on the
  1414. // line.
  1415. function highlightLine(cm, line, state, forceToEnd) {
  1416. // A styles array always starts with a number identifying the
  1417. // mode/overlays that it is based on (for easy invalidation).
  1418. var st = [cm.state.modeGen], lineClasses = {};
  1419. // Compute the base array of styles
  1420. runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
  1421. lineClasses, forceToEnd);
  1422. // Run overlays, adjust style array.
  1423. var loop = function ( o ) {
  1424. var overlay = cm.state.overlays[o], i = 1, at = 0;
  1425. runMode(cm, line.text, overlay.mode, true, function (end, style) {
  1426. var start = i;
  1427. // Ensure there's a token end at the current position, and that i points at it
  1428. while (at < end) {
  1429. var i_end = st[i];
  1430. if (i_end > end)
  1431. { st.splice(i, 1, end, st[i+1], i_end); }
  1432. i += 2;
  1433. at = Math.min(end, i_end);
  1434. }
  1435. if (!style) { return }
  1436. if (overlay.opaque) {
  1437. st.splice(start, i - start, end, "overlay " + style);
  1438. i = start + 2;
  1439. } else {
  1440. for (; start < i; start += 2) {
  1441. var cur = st[start+1];
  1442. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  1443. }
  1444. }
  1445. }, lineClasses);
  1446. };
  1447. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1448. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1449. }
  1450. function getLineStyles(cm, line, updateFrontier) {
  1451. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1452. var state = getStateBefore(cm, lineNo(line));
  1453. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  1454. line.stateAfter = state;
  1455. line.styles = result.styles;
  1456. if (result.classes) { line.styleClasses = result.classes; }
  1457. else if (line.styleClasses) { line.styleClasses = null; }
  1458. if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++; }
  1459. }
  1460. return line.styles
  1461. }
  1462. function getStateBefore(cm, n, precise) {
  1463. var doc = cm.doc, display = cm.display;
  1464. if (!doc.mode.startState) { return true }
  1465. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  1466. if (!state) { state = startState(doc.mode); }
  1467. else { state = copyState(doc.mode, state); }
  1468. doc.iter(pos, n, function (line) {
  1469. processLine(cm, line.text, state);
  1470. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  1471. line.stateAfter = save ? copyState(doc.mode, state) : null;
  1472. ++pos;
  1473. });
  1474. if (precise) { doc.frontier = pos; }
  1475. return state
  1476. }
  1477. // Lightweight form of highlight -- proceed over this line and
  1478. // update state, but don't save a style array. Used for lines that
  1479. // aren't currently visible.
  1480. function processLine(cm, text, state, startAt) {
  1481. var mode = cm.doc.mode;
  1482. var stream = new StringStream(text, cm.options.tabSize);
  1483. stream.start = stream.pos = startAt || 0;
  1484. if (text == "") { callBlankLine(mode, state); }
  1485. while (!stream.eol()) {
  1486. readToken(mode, stream, state);
  1487. stream.start = stream.pos;
  1488. }
  1489. }
  1490. function callBlankLine(mode, state) {
  1491. if (mode.blankLine) { return mode.blankLine(state) }
  1492. if (!mode.innerMode) { return }
  1493. var inner = innerMode(mode, state);
  1494. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1495. }
  1496. function readToken(mode, stream, state, inner) {
  1497. for (var i = 0; i < 10; i++) {
  1498. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1499. var style = mode.token(stream, state);
  1500. if (stream.pos > stream.start) { return style }
  1501. }
  1502. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1503. }
  1504. // Utility for getTokenAt and getLineTokens
  1505. function takeToken(cm, pos, precise, asArray) {
  1506. var getObj = function (copy) { return ({
  1507. start: stream.start, end: stream.pos,
  1508. string: stream.current(),
  1509. type: style || null,
  1510. state: copy ? copyState(doc.mode, state) : state
  1511. }); };
  1512. var doc = cm.doc, mode = doc.mode, style;
  1513. pos = clipPos(doc, pos);
  1514. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  1515. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  1516. if (asArray) { tokens = []; }
  1517. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1518. stream.start = stream.pos;
  1519. style = readToken(mode, stream, state);
  1520. if (asArray) { tokens.push(getObj(true)); }
  1521. }
  1522. return asArray ? tokens : getObj()
  1523. }
  1524. function extractLineClasses(type, output) {
  1525. if (type) { for (;;) {
  1526. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1527. if (!lineClass) { break }
  1528. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1529. var prop = lineClass[1] ? "bgClass" : "textClass";
  1530. if (output[prop] == null)
  1531. { output[prop] = lineClass[2]; }
  1532. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1533. { output[prop] += " " + lineClass[2]; }
  1534. } }
  1535. return type
  1536. }
  1537. // Run the given mode's parser over a line, calling f for each token.
  1538. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  1539. var flattenSpans = mode.flattenSpans;
  1540. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1541. var curStart = 0, curStyle = null;
  1542. var stream = new StringStream(text, cm.options.tabSize), style;
  1543. var inner = cm.options.addModeClass && [null];
  1544. if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses); }
  1545. while (!stream.eol()) {
  1546. if (stream.pos > cm.options.maxHighlightLength) {
  1547. flattenSpans = false;
  1548. if (forceToEnd) { processLine(cm, text, state, stream.pos); }
  1549. stream.pos = text.length;
  1550. style = null;
  1551. } else {
  1552. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  1553. }
  1554. if (inner) {
  1555. var mName = inner[0].name;
  1556. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1557. }
  1558. if (!flattenSpans || curStyle != style) {
  1559. while (curStart < stream.start) {
  1560. curStart = Math.min(stream.start, curStart + 5000);
  1561. f(curStart, curStyle);
  1562. }
  1563. curStyle = style;
  1564. }
  1565. stream.start = stream.pos;
  1566. }
  1567. while (curStart < stream.pos) {
  1568. // Webkit seems to refuse to render text nodes longer than 57444
  1569. // characters, and returns inaccurate measurements in nodes
  1570. // starting around 5000 chars.
  1571. var pos = Math.min(stream.pos, curStart + 5000);
  1572. f(pos, curStyle);
  1573. curStart = pos;
  1574. }
  1575. }
  1576. // Finds the line to start with when starting a parse. Tries to
  1577. // find a line with a stateAfter, so that it can start with a
  1578. // valid state. If that fails, it returns the line with the
  1579. // smallest indentation, which tends to need the least context to
  1580. // parse correctly.
  1581. function findStartLine(cm, n, precise) {
  1582. var minindent, minline, doc = cm.doc;
  1583. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1584. for (var search = n; search > lim; --search) {
  1585. if (search <= doc.first) { return doc.first }
  1586. var line = getLine(doc, search - 1);
  1587. if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
  1588. var indented = countColumn(line.text, null, cm.options.tabSize);
  1589. if (minline == null || minindent > indented) {
  1590. minline = search - 1;
  1591. minindent = indented;
  1592. }
  1593. }
  1594. return minline
  1595. }
  1596. // LINE DATA STRUCTURE
  1597. // Line objects. These hold state related to a line, including
  1598. // highlighting info (the styles array).
  1599. var Line = function(text, markedSpans, estimateHeight) {
  1600. this.text = text;
  1601. attachMarkedSpans(this, markedSpans);
  1602. this.height = estimateHeight ? estimateHeight(this) : 1;
  1603. };
  1604. Line.prototype.lineNo = function () { return lineNo(this) };
  1605. eventMixin(Line);
  1606. // Change the content (text, markers) of a line. Automatically
  1607. // invalidates cached information and tries to re-estimate the
  1608. // line's height.
  1609. function updateLine(line, text, markedSpans, estimateHeight) {
  1610. line.text = text;
  1611. if (line.stateAfter) { line.stateAfter = null; }
  1612. if (line.styles) { line.styles = null; }
  1613. if (line.order != null) { line.order = null; }
  1614. detachMarkedSpans(line);
  1615. attachMarkedSpans(line, markedSpans);
  1616. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1617. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1618. }
  1619. // Detach a line from the document tree and its markers.
  1620. function cleanUpLine(line) {
  1621. line.parent = null;
  1622. detachMarkedSpans(line);
  1623. }
  1624. // Convert a style as returned by a mode (either null, or a string
  1625. // containing one or more styles) to a CSS style. This is cached,
  1626. // and also looks for line-wide styles.
  1627. var styleToClassCache = {};
  1628. var styleToClassCacheWithMode = {};
  1629. function interpretTokenStyle(style, options) {
  1630. if (!style || /^\s*$/.test(style)) { return null }
  1631. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1632. return cache[style] ||
  1633. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1634. }
  1635. // Render the DOM representation of the text of a line. Also builds
  1636. // up a 'line map', which points at the DOM nodes that represent
  1637. // specific stretches of text, and is used by the measuring code.
  1638. // The returned object contains the DOM node, this map, and
  1639. // information about line-wide styles that were set by the mode.
  1640. function buildLineContent(cm, lineView) {
  1641. // The padding-right forces the element to have a 'border', which
  1642. // is needed on Webkit to be able to get line-level bounding
  1643. // rectangles for it (in measureChar).
  1644. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1645. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1646. col: 0, pos: 0, cm: cm,
  1647. trailingSpace: false,
  1648. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  1649. lineView.measure = {};
  1650. // Iterate over the logical lines that make up this visual line.
  1651. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1652. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1653. builder.pos = 0;
  1654. builder.addToken = buildToken;
  1655. // Optionally wire in some hacks into the token-rendering
  1656. // algorithm, to deal with browser quirks.
  1657. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1658. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1659. builder.map = [];
  1660. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1661. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1662. if (line.styleClasses) {
  1663. if (line.styleClasses.bgClass)
  1664. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1665. if (line.styleClasses.textClass)
  1666. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1667. }
  1668. // Ensure at least a single node is present, for measuring.
  1669. if (builder.map.length == 0)
  1670. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1671. // Store the map and a cache object for the current logical line
  1672. if (i == 0) {
  1673. lineView.measure.map = builder.map;
  1674. lineView.measure.cache = {};
  1675. } else {
  1676. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1677. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1678. }
  1679. }
  1680. // See issue #2901
  1681. if (webkit) {
  1682. var last = builder.content.lastChild;
  1683. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1684. { builder.content.className = "cm-tab-wrap-hack"; }
  1685. }
  1686. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1687. if (builder.pre.className)
  1688. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1689. return builder
  1690. }
  1691. function defaultSpecialCharPlaceholder(ch) {
  1692. var token = elt("span", "\u2022", "cm-invalidchar");
  1693. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1694. token.setAttribute("aria-label", token.title);
  1695. return token
  1696. }
  1697. // Build up the DOM representation for a single token, and add it to
  1698. // the line map. Takes care to render special characters separately.
  1699. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1700. if (!text) { return }
  1701. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1702. var special = builder.cm.state.specialChars, mustWrap = false;
  1703. var content;
  1704. if (!special.test(text)) {
  1705. builder.col += text.length;
  1706. content = document.createTextNode(displayText);
  1707. builder.map.push(builder.pos, builder.pos + text.length, content);
  1708. if (ie && ie_version < 9) { mustWrap = true; }
  1709. builder.pos += text.length;
  1710. } else {
  1711. content = document.createDocumentFragment();
  1712. var pos = 0;
  1713. while (true) {
  1714. special.lastIndex = pos;
  1715. var m = special.exec(text);
  1716. var skipped = m ? m.index - pos : text.length - pos;
  1717. if (skipped) {
  1718. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1719. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1720. else { content.appendChild(txt); }
  1721. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1722. builder.col += skipped;
  1723. builder.pos += skipped;
  1724. }
  1725. if (!m) { break }
  1726. pos += skipped + 1;
  1727. var txt$1 = (void 0);
  1728. if (m[0] == "\t") {
  1729. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1730. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1731. txt$1.setAttribute("role", "presentation");
  1732. txt$1.setAttribute("cm-text", "\t");
  1733. builder.col += tabWidth;
  1734. } else if (m[0] == "\r" || m[0] == "\n") {
  1735. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1736. txt$1.setAttribute("cm-text", m[0]);
  1737. builder.col += 1;
  1738. } else {
  1739. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1740. txt$1.setAttribute("cm-text", m[0]);
  1741. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1742. else { content.appendChild(txt$1); }
  1743. builder.col += 1;
  1744. }
  1745. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1746. builder.pos++;
  1747. }
  1748. }
  1749. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1750. if (style || startStyle || endStyle || mustWrap || css) {
  1751. var fullStyle = style || "";
  1752. if (startStyle) { fullStyle += startStyle; }
  1753. if (endStyle) { fullStyle += endStyle; }
  1754. var token = elt("span", [content], fullStyle, css);
  1755. if (title) { token.title = title; }
  1756. return builder.content.appendChild(token)
  1757. }
  1758. builder.content.appendChild(content);
  1759. }
  1760. function splitSpaces(text, trailingBefore) {
  1761. if (text.length > 1 && !/ /.test(text)) { return text }
  1762. var spaceBefore = trailingBefore, result = "";
  1763. for (var i = 0; i < text.length; i++) {
  1764. var ch = text.charAt(i);
  1765. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1766. { ch = "\u00a0"; }
  1767. result += ch;
  1768. spaceBefore = ch == " ";
  1769. }
  1770. return result
  1771. }
  1772. // Work around nonsense dimensions being reported for stretches of
  1773. // right-to-left text.
  1774. function buildTokenBadBidi(inner, order) {
  1775. return function (builder, text, style, startStyle, endStyle, title, css) {
  1776. style = style ? style + " cm-force-border" : "cm-force-border";
  1777. var start = builder.pos, end = start + text.length;
  1778. for (;;) {
  1779. // Find the part that overlaps with the start of this text
  1780. var part = (void 0);
  1781. for (var i = 0; i < order.length; i++) {
  1782. part = order[i];
  1783. if (part.to > start && part.from <= start) { break }
  1784. }
  1785. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1786. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  1787. startStyle = null;
  1788. text = text.slice(part.to - start);
  1789. start = part.to;
  1790. }
  1791. }
  1792. }
  1793. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1794. var widget = !ignoreWidget && marker.widgetNode;
  1795. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1796. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1797. if (!widget)
  1798. { widget = builder.content.appendChild(document.createElement("span")); }
  1799. widget.setAttribute("cm-marker", marker.id);
  1800. }
  1801. if (widget) {
  1802. builder.cm.display.input.setUneditable(widget);
  1803. builder.content.appendChild(widget);
  1804. }
  1805. builder.pos += size;
  1806. builder.trailingSpace = false;
  1807. }
  1808. // Outputs a number of spans to make up a line, taking highlighting
  1809. // and marked text into account.
  1810. function insertLineContent(line, builder, styles) {
  1811. var spans = line.markedSpans, allText = line.text, at = 0;
  1812. if (!spans) {
  1813. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1814. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1815. return
  1816. }
  1817. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1818. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  1819. for (;;) {
  1820. if (nextChange == pos) { // Update current marker set
  1821. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  1822. collapsed = null; nextChange = Infinity;
  1823. var foundBookmarks = [], endStyles = (void 0);
  1824. for (var j = 0; j < spans.length; ++j) {
  1825. var sp = spans[j], m = sp.marker;
  1826. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1827. foundBookmarks.push(m);
  1828. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1829. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1830. nextChange = sp.to;
  1831. spanEndStyle = "";
  1832. }
  1833. if (m.className) { spanStyle += " " + m.className; }
  1834. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1835. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1836. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1837. if (m.title && !title) { title = m.title; }
  1838. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1839. { collapsed = sp; }
  1840. } else if (sp.from > pos && nextChange > sp.from) {
  1841. nextChange = sp.from;
  1842. }
  1843. }
  1844. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1845. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1846. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1847. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1848. if (collapsed && (collapsed.from || 0) == pos) {
  1849. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1850. collapsed.marker, collapsed.from == null);
  1851. if (collapsed.to == null) { return }
  1852. if (collapsed.to == pos) { collapsed = false; }
  1853. }
  1854. }
  1855. if (pos >= len) { break }
  1856. var upto = Math.min(len, nextChange);
  1857. while (true) {
  1858. if (text) {
  1859. var end = pos + text.length;
  1860. if (!collapsed) {
  1861. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1862. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1863. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  1864. }
  1865. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1866. pos = end;
  1867. spanStartStyle = "";
  1868. }
  1869. text = allText.slice(at, at = styles[i++]);
  1870. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1871. }
  1872. }
  1873. }
  1874. // These objects are used to represent the visible (currently drawn)
  1875. // part of the document. A LineView may correspond to multiple
  1876. // logical lines, if those are connected by collapsed ranges.
  1877. function LineView(doc, line, lineN) {
  1878. // The starting line
  1879. this.line = line;
  1880. // Continuing lines, if any
  1881. this.rest = visualLineContinued(line);
  1882. // Number of logical lines in this visual line
  1883. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1884. this.node = this.text = null;
  1885. this.hidden = lineIsHidden(doc, line);
  1886. }
  1887. // Create a range of LineView objects for the given lines.
  1888. function buildViewArray(cm, from, to) {
  1889. var array = [], nextPos;
  1890. for (var pos = from; pos < to; pos = nextPos) {
  1891. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1892. nextPos = pos + view.size;
  1893. array.push(view);
  1894. }
  1895. return array
  1896. }
  1897. var operationGroup = null;
  1898. function pushOperation(op) {
  1899. if (operationGroup) {
  1900. operationGroup.ops.push(op);
  1901. } else {
  1902. op.ownsGroup = operationGroup = {
  1903. ops: [op],
  1904. delayedCallbacks: []
  1905. };
  1906. }
  1907. }
  1908. function fireCallbacksForOps(group) {
  1909. // Calls delayed callbacks and cursorActivity handlers until no
  1910. // new ones appear
  1911. var callbacks = group.delayedCallbacks, i = 0;
  1912. do {
  1913. for (; i < callbacks.length; i++)
  1914. { callbacks[i].call(null); }
  1915. for (var j = 0; j < group.ops.length; j++) {
  1916. var op = group.ops[j];
  1917. if (op.cursorActivityHandlers)
  1918. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1919. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1920. }
  1921. } while (i < callbacks.length)
  1922. }
  1923. function finishOperation(op, endCb) {
  1924. var group = op.ownsGroup;
  1925. if (!group) { return }
  1926. try { fireCallbacksForOps(group); }
  1927. finally {
  1928. operationGroup = null;
  1929. endCb(group);
  1930. }
  1931. }
  1932. var orphanDelayedCallbacks = null;
  1933. // Often, we want to signal events at a point where we are in the
  1934. // middle of some work, but don't want the handler to start calling
  1935. // other methods on the editor, which might be in an inconsistent
  1936. // state or simply not expect any other events to happen.
  1937. // signalLater looks whether there are any handlers, and schedules
  1938. // them to be executed when the last operation ends, or, if no
  1939. // operation is active, when a timeout fires.
  1940. function signalLater(emitter, type /*, values...*/) {
  1941. var arr = getHandlers(emitter, type);
  1942. if (!arr.length) { return }
  1943. var args = Array.prototype.slice.call(arguments, 2), list;
  1944. if (operationGroup) {
  1945. list = operationGroup.delayedCallbacks;
  1946. } else if (orphanDelayedCallbacks) {
  1947. list = orphanDelayedCallbacks;
  1948. } else {
  1949. list = orphanDelayedCallbacks = [];
  1950. setTimeout(fireOrphanDelayed, 0);
  1951. }
  1952. var loop = function ( i ) {
  1953. list.push(function () { return arr[i].apply(null, args); });
  1954. };
  1955. for (var i = 0; i < arr.length; ++i)
  1956. loop( i );
  1957. }
  1958. function fireOrphanDelayed() {
  1959. var delayed = orphanDelayedCallbacks;
  1960. orphanDelayedCallbacks = null;
  1961. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1962. }
  1963. // When an aspect of a line changes, a string is added to
  1964. // lineView.changes. This updates the relevant part of the line's
  1965. // DOM structure.
  1966. function updateLineForChanges(cm, lineView, lineN, dims) {
  1967. for (var j = 0; j < lineView.changes.length; j++) {
  1968. var type = lineView.changes[j];
  1969. if (type == "text") { updateLineText(cm, lineView); }
  1970. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1971. else if (type == "class") { updateLineClasses(cm, lineView); }
  1972. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1973. }
  1974. lineView.changes = null;
  1975. }
  1976. // Lines with gutter elements, widgets or a background class need to
  1977. // be wrapped, and have the extra elements added to the wrapper div
  1978. function ensureLineWrapped(lineView) {
  1979. if (lineView.node == lineView.text) {
  1980. lineView.node = elt("div", null, null, "position: relative");
  1981. if (lineView.text.parentNode)
  1982. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1983. lineView.node.appendChild(lineView.text);
  1984. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1985. }
  1986. return lineView.node
  1987. }
  1988. function updateLineBackground(cm, lineView) {
  1989. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1990. if (cls) { cls += " CodeMirror-linebackground"; }
  1991. if (lineView.background) {
  1992. if (cls) { lineView.background.className = cls; }
  1993. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1994. } else if (cls) {
  1995. var wrap = ensureLineWrapped(lineView);
  1996. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1997. cm.display.input.setUneditable(lineView.background);
  1998. }
  1999. }
  2000. // Wrapper around buildLineContent which will reuse the structure
  2001. // in display.externalMeasured when possible.
  2002. function getLineContent(cm, lineView) {
  2003. var ext = cm.display.externalMeasured;
  2004. if (ext && ext.line == lineView.line) {
  2005. cm.display.externalMeasured = null;
  2006. lineView.measure = ext.measure;
  2007. return ext.built
  2008. }
  2009. return buildLineContent(cm, lineView)
  2010. }
  2011. // Redraw the line's text. Interacts with the background and text
  2012. // classes because the mode may output tokens that influence these
  2013. // classes.
  2014. function updateLineText(cm, lineView) {
  2015. var cls = lineView.text.className;
  2016. var built = getLineContent(cm, lineView);
  2017. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  2018. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2019. lineView.text = built.pre;
  2020. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2021. lineView.bgClass = built.bgClass;
  2022. lineView.textClass = built.textClass;
  2023. updateLineClasses(cm, lineView);
  2024. } else if (cls) {
  2025. lineView.text.className = cls;
  2026. }
  2027. }
  2028. function updateLineClasses(cm, lineView) {
  2029. updateLineBackground(cm, lineView);
  2030. if (lineView.line.wrapClass)
  2031. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  2032. else if (lineView.node != lineView.text)
  2033. { lineView.node.className = ""; }
  2034. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2035. lineView.text.className = textClass || "";
  2036. }
  2037. function updateLineGutter(cm, lineView, lineN, dims) {
  2038. if (lineView.gutter) {
  2039. lineView.node.removeChild(lineView.gutter);
  2040. lineView.gutter = null;
  2041. }
  2042. if (lineView.gutterBackground) {
  2043. lineView.node.removeChild(lineView.gutterBackground);
  2044. lineView.gutterBackground = null;
  2045. }
  2046. if (lineView.line.gutterClass) {
  2047. var wrap = ensureLineWrapped(lineView);
  2048. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2049. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2050. cm.display.input.setUneditable(lineView.gutterBackground);
  2051. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2052. }
  2053. var markers = lineView.line.gutterMarkers;
  2054. if (cm.options.lineNumbers || markers) {
  2055. var wrap$1 = ensureLineWrapped(lineView);
  2056. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2057. cm.display.input.setUneditable(gutterWrap);
  2058. wrap$1.insertBefore(gutterWrap, lineView.text);
  2059. if (lineView.line.gutterClass)
  2060. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2061. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2062. { lineView.lineNumber = gutterWrap.appendChild(
  2063. elt("div", lineNumberFor(cm.options, lineN),
  2064. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2065. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2066. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2067. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  2068. if (found)
  2069. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2070. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2071. } }
  2072. }
  2073. }
  2074. function updateLineWidgets(cm, lineView, dims) {
  2075. if (lineView.alignable) { lineView.alignable = null; }
  2076. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2077. next = node.nextSibling;
  2078. if (node.className == "CodeMirror-linewidget")
  2079. { lineView.node.removeChild(node); }
  2080. }
  2081. insertLineWidgets(cm, lineView, dims);
  2082. }
  2083. // Build a line's DOM representation from scratch
  2084. function buildLineElement(cm, lineView, lineN, dims) {
  2085. var built = getLineContent(cm, lineView);
  2086. lineView.text = lineView.node = built.pre;
  2087. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2088. if (built.textClass) { lineView.textClass = built.textClass; }
  2089. updateLineClasses(cm, lineView);
  2090. updateLineGutter(cm, lineView, lineN, dims);
  2091. insertLineWidgets(cm, lineView, dims);
  2092. return lineView.node
  2093. }
  2094. // A lineView may contain multiple logical lines (when merged by
  2095. // collapsed spans). The widgets for all of them need to be drawn.
  2096. function insertLineWidgets(cm, lineView, dims) {
  2097. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2098. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2099. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2100. }
  2101. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2102. if (!line.widgets) { return }
  2103. var wrap = ensureLineWrapped(lineView);
  2104. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2105. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2106. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2107. positionLineWidget(widget, node, lineView, dims);
  2108. cm.display.input.setUneditable(node);
  2109. if (allowAbove && widget.above)
  2110. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2111. else
  2112. { wrap.appendChild(node); }
  2113. signalLater(widget, "redraw");
  2114. }
  2115. }
  2116. function positionLineWidget(widget, node, lineView, dims) {
  2117. if (widget.noHScroll) {
  2118. (lineView.alignable || (lineView.alignable = [])).push(node);
  2119. var width = dims.wrapperWidth;
  2120. node.style.left = dims.fixedPos + "px";
  2121. if (!widget.coverGutter) {
  2122. width -= dims.gutterTotalWidth;
  2123. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2124. }
  2125. node.style.width = width + "px";
  2126. }
  2127. if (widget.coverGutter) {
  2128. node.style.zIndex = 5;
  2129. node.style.position = "relative";
  2130. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2131. }
  2132. }
  2133. function widgetHeight(widget) {
  2134. if (widget.height != null) { return widget.height }
  2135. var cm = widget.doc.cm;
  2136. if (!cm) { return 0 }
  2137. if (!contains(document.body, widget.node)) {
  2138. var parentStyle = "position: relative;";
  2139. if (widget.coverGutter)
  2140. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2141. if (widget.noHScroll)
  2142. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2143. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2144. }
  2145. return widget.height = widget.node.parentNode.offsetHeight
  2146. }
  2147. // Return true when the given mouse event happened in a widget
  2148. function eventInWidget(display, e) {
  2149. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2150. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2151. (n.parentNode == display.sizer && n != display.mover))
  2152. { return true }
  2153. }
  2154. }
  2155. // POSITION MEASUREMENT
  2156. function paddingTop(display) {return display.lineSpace.offsetTop}
  2157. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2158. function paddingH(display) {
  2159. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2160. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2161. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2162. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2163. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2164. return data
  2165. }
  2166. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2167. function displayWidth(cm) {
  2168. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2169. }
  2170. function displayHeight(cm) {
  2171. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2172. }
  2173. // Ensure the lineView.wrapping.heights array is populated. This is
  2174. // an array of bottom offsets for the lines that make up a drawn
  2175. // line. When lineWrapping is on, there might be more than one
  2176. // height.
  2177. function ensureLineHeights(cm, lineView, rect) {
  2178. var wrapping = cm.options.lineWrapping;
  2179. var curWidth = wrapping && displayWidth(cm);
  2180. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2181. var heights = lineView.measure.heights = [];
  2182. if (wrapping) {
  2183. lineView.measure.width = curWidth;
  2184. var rects = lineView.text.firstChild.getClientRects();
  2185. for (var i = 0; i < rects.length - 1; i++) {
  2186. var cur = rects[i], next = rects[i + 1];
  2187. if (Math.abs(cur.bottom - next.bottom) > 2)
  2188. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2189. }
  2190. }
  2191. heights.push(rect.bottom - rect.top);
  2192. }
  2193. }
  2194. // Find a line map (mapping character offsets to text nodes) and a
  2195. // measurement cache for the given line number. (A line view might
  2196. // contain multiple lines when collapsed ranges are present.)
  2197. function mapFromLineView(lineView, line, lineN) {
  2198. if (lineView.line == line)
  2199. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2200. for (var i = 0; i < lineView.rest.length; i++)
  2201. { if (lineView.rest[i] == line)
  2202. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2203. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2204. { if (lineNo(lineView.rest[i$1]) > lineN)
  2205. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2206. }
  2207. // Render a line into the hidden node display.externalMeasured. Used
  2208. // when measurement is needed for a line that's not in the viewport.
  2209. function updateExternalMeasurement(cm, line) {
  2210. line = visualLine(line);
  2211. var lineN = lineNo(line);
  2212. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2213. view.lineN = lineN;
  2214. var built = view.built = buildLineContent(cm, view);
  2215. view.text = built.pre;
  2216. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2217. return view
  2218. }
  2219. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2220. // for a given character.
  2221. function measureChar(cm, line, ch, bias) {
  2222. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2223. }
  2224. // Find a line view that corresponds to the given line number.
  2225. function findViewForLine(cm, lineN) {
  2226. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2227. { return cm.display.view[findViewIndex(cm, lineN)] }
  2228. var ext = cm.display.externalMeasured;
  2229. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2230. { return ext }
  2231. }
  2232. // Measurement can be split in two steps, the set-up work that
  2233. // applies to the whole line, and the measurement of the actual
  2234. // character. Functions like coordsChar, that need to do a lot of
  2235. // measurements in a row, can thus ensure that the set-up work is
  2236. // only done once.
  2237. function prepareMeasureForLine(cm, line) {
  2238. var lineN = lineNo(line);
  2239. var view = findViewForLine(cm, lineN);
  2240. if (view && !view.text) {
  2241. view = null;
  2242. } else if (view && view.changes) {
  2243. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2244. cm.curOp.forceUpdate = true;
  2245. }
  2246. if (!view)
  2247. { view = updateExternalMeasurement(cm, line); }
  2248. var info = mapFromLineView(view, line, lineN);
  2249. return {
  2250. line: line, view: view, rect: null,
  2251. map: info.map, cache: info.cache, before: info.before,
  2252. hasHeights: false
  2253. }
  2254. }
  2255. // Given a prepared measurement object, measures the position of an
  2256. // actual character (or fetches it from the cache).
  2257. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2258. if (prepared.before) { ch = -1; }
  2259. var key = ch + (bias || ""), found;
  2260. if (prepared.cache.hasOwnProperty(key)) {
  2261. found = prepared.cache[key];
  2262. } else {
  2263. if (!prepared.rect)
  2264. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2265. if (!prepared.hasHeights) {
  2266. ensureLineHeights(cm, prepared.view, prepared.rect);
  2267. prepared.hasHeights = true;
  2268. }
  2269. found = measureCharInner(cm, prepared, ch, bias);
  2270. if (!found.bogus) { prepared.cache[key] = found; }
  2271. }
  2272. return {left: found.left, right: found.right,
  2273. top: varHeight ? found.rtop : found.top,
  2274. bottom: varHeight ? found.rbottom : found.bottom}
  2275. }
  2276. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2277. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  2278. var node, start, end, collapse, mStart, mEnd;
  2279. // First, search the line map for the text node corresponding to,
  2280. // or closest to, the target character.
  2281. for (var i = 0; i < map$$1.length; i += 3) {
  2282. mStart = map$$1[i];
  2283. mEnd = map$$1[i + 1];
  2284. if (ch < mStart) {
  2285. start = 0; end = 1;
  2286. collapse = "left";
  2287. } else if (ch < mEnd) {
  2288. start = ch - mStart;
  2289. end = start + 1;
  2290. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  2291. end = mEnd - mStart;
  2292. start = end - 1;
  2293. if (ch >= mEnd) { collapse = "right"; }
  2294. }
  2295. if (start != null) {
  2296. node = map$$1[i + 2];
  2297. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2298. { collapse = bias; }
  2299. if (bias == "left" && start == 0)
  2300. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  2301. node = map$$1[(i -= 3) + 2];
  2302. collapse = "left";
  2303. } }
  2304. if (bias == "right" && start == mEnd - mStart)
  2305. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  2306. node = map$$1[(i += 3) + 2];
  2307. collapse = "right";
  2308. } }
  2309. break
  2310. }
  2311. }
  2312. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2313. }
  2314. function getUsefulRect(rects, bias) {
  2315. var rect = nullRect;
  2316. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2317. if ((rect = rects[i]).left != rect.right) { break }
  2318. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2319. if ((rect = rects[i$1]).left != rect.right) { break }
  2320. } }
  2321. return rect
  2322. }
  2323. function measureCharInner(cm, prepared, ch, bias) {
  2324. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2325. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2326. var rect;
  2327. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2328. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2329. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2330. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2331. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2332. { rect = node.parentNode.getBoundingClientRect(); }
  2333. else
  2334. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2335. if (rect.left || rect.right || start == 0) { break }
  2336. end = start;
  2337. start = start - 1;
  2338. collapse = "right";
  2339. }
  2340. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2341. } else { // If it is a widget, simply get the box for the whole widget.
  2342. if (start > 0) { collapse = bias = "right"; }
  2343. var rects;
  2344. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2345. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2346. else
  2347. { rect = node.getBoundingClientRect(); }
  2348. }
  2349. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2350. var rSpan = node.parentNode.getClientRects()[0];
  2351. if (rSpan)
  2352. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2353. else
  2354. { rect = nullRect; }
  2355. }
  2356. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2357. var mid = (rtop + rbot) / 2;
  2358. var heights = prepared.view.measure.heights;
  2359. var i = 0;
  2360. for (; i < heights.length - 1; i++)
  2361. { if (mid < heights[i]) { break } }
  2362. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2363. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2364. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2365. top: top, bottom: bot};
  2366. if (!rect.left && !rect.right) { result.bogus = true; }
  2367. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2368. return result
  2369. }
  2370. // Work around problem with bounding client rects on ranges being
  2371. // returned incorrectly when zoomed on IE10 and below.
  2372. function maybeUpdateRectForZooming(measure, rect) {
  2373. if (!window.screen || screen.logicalXDPI == null ||
  2374. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2375. { return rect }
  2376. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2377. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2378. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2379. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2380. }
  2381. function clearLineMeasurementCacheFor(lineView) {
  2382. if (lineView.measure) {
  2383. lineView.measure.cache = {};
  2384. lineView.measure.heights = null;
  2385. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2386. { lineView.measure.caches[i] = {}; } }
  2387. }
  2388. }
  2389. function clearLineMeasurementCache(cm) {
  2390. cm.display.externalMeasure = null;
  2391. removeChildren(cm.display.lineMeasure);
  2392. for (var i = 0; i < cm.display.view.length; i++)
  2393. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2394. }
  2395. function clearCaches(cm) {
  2396. clearLineMeasurementCache(cm);
  2397. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2398. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2399. cm.display.lineNumChars = null;
  2400. }
  2401. function pageScrollX() {
  2402. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2403. // which causes page_Offset and bounding client rects to use
  2404. // different reference viewports and invalidate our calculations.
  2405. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2406. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2407. }
  2408. function pageScrollY() {
  2409. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2410. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2411. }
  2412. // Converts a {top, bottom, left, right} box from line-local
  2413. // coordinates into another coordinate system. Context may be one of
  2414. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2415. // or "page".
  2416. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2417. if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
  2418. var size = widgetHeight(lineObj.widgets[i]);
  2419. rect.top += size; rect.bottom += size;
  2420. } } }
  2421. if (context == "line") { return rect }
  2422. if (!context) { context = "local"; }
  2423. var yOff = heightAtLine(lineObj);
  2424. if (context == "local") { yOff += paddingTop(cm.display); }
  2425. else { yOff -= cm.display.viewOffset; }
  2426. if (context == "page" || context == "window") {
  2427. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2428. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2429. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2430. rect.left += xOff; rect.right += xOff;
  2431. }
  2432. rect.top += yOff; rect.bottom += yOff;
  2433. return rect
  2434. }
  2435. // Coverts a box from "div" coords to another coordinate system.
  2436. // Context may be "window", "page", "div", or "local"./null.
  2437. function fromCoordSystem(cm, coords, context) {
  2438. if (context == "div") { return coords }
  2439. var left = coords.left, top = coords.top;
  2440. // First move into "page" coordinate system
  2441. if (context == "page") {
  2442. left -= pageScrollX();
  2443. top -= pageScrollY();
  2444. } else if (context == "local" || !context) {
  2445. var localBox = cm.display.sizer.getBoundingClientRect();
  2446. left += localBox.left;
  2447. top += localBox.top;
  2448. }
  2449. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2450. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2451. }
  2452. function charCoords(cm, pos, context, lineObj, bias) {
  2453. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2454. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2455. }
  2456. // Returns a box for a given cursor position, which may have an
  2457. // 'other' property containing the position of the secondary cursor
  2458. // on a bidi boundary.
  2459. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2460. // and after `char - 1` in writing order of `char - 1`
  2461. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2462. // and before `char` in writing order of `char`
  2463. // Examples (upper-case letters are RTL, lower-case are LTR):
  2464. // Pos(0, 1, ...)
  2465. // before after
  2466. // ab a|b a|b
  2467. // aB a|B aB|
  2468. // Ab |Ab A|b
  2469. // AB B|A B|A
  2470. // Every position after the last character on a line is considered to stick
  2471. // to the last character on the line.
  2472. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2473. lineObj = lineObj || getLine(cm.doc, pos.line);
  2474. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2475. function get(ch, right) {
  2476. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2477. if (right) { m.left = m.right; } else { m.right = m.left; }
  2478. return intoCoordSystem(cm, lineObj, m, context)
  2479. }
  2480. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2481. if (ch >= lineObj.text.length) {
  2482. ch = lineObj.text.length;
  2483. sticky = "before";
  2484. } else if (ch <= 0) {
  2485. ch = 0;
  2486. sticky = "after";
  2487. }
  2488. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2489. function getBidi(ch, partPos, invert) {
  2490. var part = order[partPos], right = (part.level % 2) != 0;
  2491. return get(invert ? ch - 1 : ch, right != invert)
  2492. }
  2493. var partPos = getBidiPartAt(order, ch, sticky);
  2494. var other = bidiOther;
  2495. var val = getBidi(ch, partPos, sticky == "before");
  2496. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2497. return val
  2498. }
  2499. // Used to cheaply estimate the coordinates for a position. Used for
  2500. // intermediate scroll updates.
  2501. function estimateCoords(cm, pos) {
  2502. var left = 0;
  2503. pos = clipPos(cm.doc, pos);
  2504. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2505. var lineObj = getLine(cm.doc, pos.line);
  2506. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2507. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2508. }
  2509. // Positions returned by coordsChar contain some extra information.
  2510. // xRel is the relative x position of the input coordinates compared
  2511. // to the found position (so xRel > 0 means the coordinates are to
  2512. // the right of the character position, for example). When outside
  2513. // is true, that means the coordinates lie outside the line's
  2514. // vertical range.
  2515. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2516. var pos = Pos(line, ch, sticky);
  2517. pos.xRel = xRel;
  2518. if (outside) { pos.outside = true; }
  2519. return pos
  2520. }
  2521. // Compute the character position closest to the given coordinates.
  2522. // Input must be lineSpace-local ("div" coordinate system).
  2523. function coordsChar(cm, x, y) {
  2524. var doc = cm.doc;
  2525. y += cm.display.viewOffset;
  2526. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2527. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2528. if (lineN > last)
  2529. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2530. if (x < 0) { x = 0; }
  2531. var lineObj = getLine(doc, lineN);
  2532. for (;;) {
  2533. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2534. var merged = collapsedSpanAtEnd(lineObj);
  2535. var mergedPos = merged && merged.find(0, true);
  2536. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2537. { lineN = lineNo(lineObj = mergedPos.to.line); }
  2538. else
  2539. { return found }
  2540. }
  2541. }
  2542. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2543. var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); };
  2544. var end = lineObj.text.length;
  2545. var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0);
  2546. end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end);
  2547. return {begin: begin, end: end}
  2548. }
  2549. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2550. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2551. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2552. }
  2553. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  2554. y -= heightAtLine(lineObj);
  2555. var begin = 0, end = lineObj.text.length;
  2556. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2557. var pos;
  2558. var order = getOrder(lineObj, cm.doc.direction);
  2559. if (order) {
  2560. if (cm.options.lineWrapping) {
  2561. var assign;
  2562. ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign));
  2563. }
  2564. pos = new Pos(lineNo$$1, begin);
  2565. var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left;
  2566. var dir = beginLeft < x ? 1 : -1;
  2567. var prevDiff, diff = beginLeft - x, prevPos;
  2568. do {
  2569. prevDiff = diff;
  2570. prevPos = pos;
  2571. pos = moveVisually(cm, lineObj, pos, dir);
  2572. if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) {
  2573. pos = prevPos;
  2574. break
  2575. }
  2576. diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x;
  2577. } while ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff)))
  2578. if (Math.abs(diff) > Math.abs(prevDiff)) {
  2579. if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") }
  2580. pos = prevPos;
  2581. }
  2582. } else {
  2583. var ch = findFirst(function (ch) {
  2584. var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line");
  2585. if (box.top > y) {
  2586. // For the cursor stickiness
  2587. end = Math.min(ch, end);
  2588. return true
  2589. }
  2590. else if (box.bottom <= y) { return false }
  2591. else if (box.left > x) { return true }
  2592. else if (box.right < x) { return false }
  2593. else { return (x - box.left < box.right - x) }
  2594. }, begin, end);
  2595. ch = skipExtendingChars(lineObj.text, ch, 1);
  2596. pos = new Pos(lineNo$$1, ch, ch == end ? "before" : "after");
  2597. }
  2598. var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure);
  2599. if (y < coords.top || coords.bottom < y) { pos.outside = true; }
  2600. pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0);
  2601. return pos
  2602. }
  2603. var measureText;
  2604. // Compute the default text height.
  2605. function textHeight(display) {
  2606. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2607. if (measureText == null) {
  2608. measureText = elt("pre");
  2609. // Measure a bunch of lines, for browsers that compute
  2610. // fractional heights.
  2611. for (var i = 0; i < 49; ++i) {
  2612. measureText.appendChild(document.createTextNode("x"));
  2613. measureText.appendChild(elt("br"));
  2614. }
  2615. measureText.appendChild(document.createTextNode("x"));
  2616. }
  2617. removeChildrenAndAdd(display.measure, measureText);
  2618. var height = measureText.offsetHeight / 50;
  2619. if (height > 3) { display.cachedTextHeight = height; }
  2620. removeChildren(display.measure);
  2621. return height || 1
  2622. }
  2623. // Compute the default character width.
  2624. function charWidth(display) {
  2625. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2626. var anchor = elt("span", "xxxxxxxxxx");
  2627. var pre = elt("pre", [anchor]);
  2628. removeChildrenAndAdd(display.measure, pre);
  2629. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2630. if (width > 2) { display.cachedCharWidth = width; }
  2631. return width || 10
  2632. }
  2633. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2634. // view, so that we don't interleave reading and writing to the DOM.
  2635. function getDimensions(cm) {
  2636. var d = cm.display, left = {}, width = {};
  2637. var gutterLeft = d.gutters.clientLeft;
  2638. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2639. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  2640. width[cm.options.gutters[i]] = n.clientWidth;
  2641. }
  2642. return {fixedPos: compensateForHScroll(d),
  2643. gutterTotalWidth: d.gutters.offsetWidth,
  2644. gutterLeft: left,
  2645. gutterWidth: width,
  2646. wrapperWidth: d.wrapper.clientWidth}
  2647. }
  2648. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2649. // but using getBoundingClientRect to get a sub-pixel-accurate
  2650. // result.
  2651. function compensateForHScroll(display) {
  2652. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2653. }
  2654. // Returns a function that estimates the height of a line, to use as
  2655. // first approximation until the line becomes visible (and is thus
  2656. // properly measurable).
  2657. function estimateHeight(cm) {
  2658. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2659. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2660. return function (line) {
  2661. if (lineIsHidden(cm.doc, line)) { return 0 }
  2662. var widgetsHeight = 0;
  2663. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2664. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2665. } }
  2666. if (wrapping)
  2667. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2668. else
  2669. { return widgetsHeight + th }
  2670. }
  2671. }
  2672. function estimateLineHeights(cm) {
  2673. var doc = cm.doc, est = estimateHeight(cm);
  2674. doc.iter(function (line) {
  2675. var estHeight = est(line);
  2676. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2677. });
  2678. }
  2679. // Given a mouse event, find the corresponding position. If liberal
  2680. // is false, it checks whether a gutter or scrollbar was clicked,
  2681. // and returns null if it was. forRect is used by rectangular
  2682. // selections, and tries to estimate a character position even for
  2683. // coordinates beyond the right of the text.
  2684. function posFromMouse(cm, e, liberal, forRect) {
  2685. var display = cm.display;
  2686. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2687. var x, y, space = display.lineSpace.getBoundingClientRect();
  2688. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2689. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2690. catch (e) { return null }
  2691. var coords = coordsChar(cm, x, y), line;
  2692. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2693. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2694. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2695. }
  2696. return coords
  2697. }
  2698. // Find the view element corresponding to a given line. Return null
  2699. // when the line isn't visible.
  2700. function findViewIndex(cm, n) {
  2701. if (n >= cm.display.viewTo) { return null }
  2702. n -= cm.display.viewFrom;
  2703. if (n < 0) { return null }
  2704. var view = cm.display.view;
  2705. for (var i = 0; i < view.length; i++) {
  2706. n -= view[i].size;
  2707. if (n < 0) { return i }
  2708. }
  2709. }
  2710. function updateSelection(cm) {
  2711. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2712. }
  2713. function prepareSelection(cm, primary) {
  2714. var doc = cm.doc, result = {};
  2715. var curFragment = result.cursors = document.createDocumentFragment();
  2716. var selFragment = result.selection = document.createDocumentFragment();
  2717. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2718. if (primary === false && i == doc.sel.primIndex) { continue }
  2719. var range$$1 = doc.sel.ranges[i];
  2720. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  2721. var collapsed = range$$1.empty();
  2722. if (collapsed || cm.options.showCursorWhenSelecting)
  2723. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  2724. if (!collapsed)
  2725. { drawSelectionRange(cm, range$$1, selFragment); }
  2726. }
  2727. return result
  2728. }
  2729. // Draws a cursor for the given range
  2730. function drawSelectionCursor(cm, head, output) {
  2731. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2732. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2733. cursor.style.left = pos.left + "px";
  2734. cursor.style.top = pos.top + "px";
  2735. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2736. if (pos.other) {
  2737. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2738. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2739. otherCursor.style.display = "";
  2740. otherCursor.style.left = pos.other.left + "px";
  2741. otherCursor.style.top = pos.other.top + "px";
  2742. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2743. }
  2744. }
  2745. // Draws the given range as a highlighted selection
  2746. function drawSelectionRange(cm, range$$1, output) {
  2747. var display = cm.display, doc = cm.doc;
  2748. var fragment = document.createDocumentFragment();
  2749. var padding = paddingH(cm.display), leftSide = padding.left;
  2750. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2751. function add(left, top, width, bottom) {
  2752. if (top < 0) { top = 0; }
  2753. top = Math.round(top);
  2754. bottom = Math.round(bottom);
  2755. 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")));
  2756. }
  2757. function drawForLine(line, fromArg, toArg) {
  2758. var lineObj = getLine(doc, line);
  2759. var lineLen = lineObj.text.length;
  2760. var start, end;
  2761. function coords(ch, bias) {
  2762. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2763. }
  2764. iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2765. var leftPos = coords(from, "left"), rightPos, left, right;
  2766. if (from == to) {
  2767. rightPos = leftPos;
  2768. left = right = leftPos.left;
  2769. } else {
  2770. rightPos = coords(to - 1, "right");
  2771. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2772. left = leftPos.left;
  2773. right = rightPos.right;
  2774. }
  2775. if (fromArg == null && from == 0) { left = leftSide; }
  2776. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2777. add(left, leftPos.top, null, leftPos.bottom);
  2778. left = leftSide;
  2779. if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top); }
  2780. }
  2781. if (toArg == null && to == lineLen) { right = rightSide; }
  2782. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2783. { start = leftPos; }
  2784. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2785. { end = rightPos; }
  2786. if (left < leftSide + 1) { left = leftSide; }
  2787. add(left, rightPos.top, right - left, rightPos.bottom);
  2788. });
  2789. return {start: start, end: end}
  2790. }
  2791. var sFrom = range$$1.from(), sTo = range$$1.to();
  2792. if (sFrom.line == sTo.line) {
  2793. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2794. } else {
  2795. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2796. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2797. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2798. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2799. if (singleVLine) {
  2800. if (leftEnd.top < rightStart.top - 2) {
  2801. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2802. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2803. } else {
  2804. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2805. }
  2806. }
  2807. if (leftEnd.bottom < rightStart.top)
  2808. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2809. }
  2810. output.appendChild(fragment);
  2811. }
  2812. // Cursor-blinking
  2813. function restartBlink(cm) {
  2814. if (!cm.state.focused) { return }
  2815. var display = cm.display;
  2816. clearInterval(display.blinker);
  2817. var on = true;
  2818. display.cursorDiv.style.visibility = "";
  2819. if (cm.options.cursorBlinkRate > 0)
  2820. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2821. cm.options.cursorBlinkRate); }
  2822. else if (cm.options.cursorBlinkRate < 0)
  2823. { display.cursorDiv.style.visibility = "hidden"; }
  2824. }
  2825. function ensureFocus(cm) {
  2826. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2827. }
  2828. function delayBlurEvent(cm) {
  2829. cm.state.delayingBlurEvent = true;
  2830. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2831. cm.state.delayingBlurEvent = false;
  2832. onBlur(cm);
  2833. } }, 100);
  2834. }
  2835. function onFocus(cm, e) {
  2836. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  2837. if (cm.options.readOnly == "nocursor") { return }
  2838. if (!cm.state.focused) {
  2839. signal(cm, "focus", cm, e);
  2840. cm.state.focused = true;
  2841. addClass(cm.display.wrapper, "CodeMirror-focused");
  2842. // This test prevents this from firing when a context
  2843. // menu is closed (since the input reset would kill the
  2844. // select-all detection hack)
  2845. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2846. cm.display.input.reset();
  2847. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  2848. }
  2849. cm.display.input.receivedFocus();
  2850. }
  2851. restartBlink(cm);
  2852. }
  2853. function onBlur(cm, e) {
  2854. if (cm.state.delayingBlurEvent) { return }
  2855. if (cm.state.focused) {
  2856. signal(cm, "blur", cm, e);
  2857. cm.state.focused = false;
  2858. rmClass(cm.display.wrapper, "CodeMirror-focused");
  2859. }
  2860. clearInterval(cm.display.blinker);
  2861. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  2862. }
  2863. // Re-align line numbers and gutter marks to compensate for
  2864. // horizontal scrolling.
  2865. function alignHorizontally(cm) {
  2866. var display = cm.display, view = display.view;
  2867. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  2868. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  2869. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  2870. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  2871. if (cm.options.fixedGutter) {
  2872. if (view[i].gutter)
  2873. { view[i].gutter.style.left = left; }
  2874. if (view[i].gutterBackground)
  2875. { view[i].gutterBackground.style.left = left; }
  2876. }
  2877. var align = view[i].alignable;
  2878. if (align) { for (var j = 0; j < align.length; j++)
  2879. { align[j].style.left = left; } }
  2880. } }
  2881. if (cm.options.fixedGutter)
  2882. { display.gutters.style.left = (comp + gutterW) + "px"; }
  2883. }
  2884. // Used to ensure that the line number gutter is still the right
  2885. // size for the current document size. Returns true when an update
  2886. // is needed.
  2887. function maybeUpdateLineNumberWidth(cm) {
  2888. if (!cm.options.lineNumbers) { return false }
  2889. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  2890. if (last.length != display.lineNumChars) {
  2891. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2892. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  2893. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  2894. display.lineGutter.style.width = "";
  2895. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  2896. display.lineNumWidth = display.lineNumInnerWidth + padding;
  2897. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  2898. display.lineGutter.style.width = display.lineNumWidth + "px";
  2899. updateGutterSpace(cm);
  2900. return true
  2901. }
  2902. return false
  2903. }
  2904. // Read the actual heights of the rendered lines, and update their
  2905. // stored heights to match.
  2906. function updateHeightsInViewport(cm) {
  2907. var display = cm.display;
  2908. var prevBottom = display.lineDiv.offsetTop;
  2909. for (var i = 0; i < display.view.length; i++) {
  2910. var cur = display.view[i], height = (void 0);
  2911. if (cur.hidden) { continue }
  2912. if (ie && ie_version < 8) {
  2913. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  2914. height = bot - prevBottom;
  2915. prevBottom = bot;
  2916. } else {
  2917. var box = cur.node.getBoundingClientRect();
  2918. height = box.bottom - box.top;
  2919. }
  2920. var diff = cur.line.height - height;
  2921. if (height < 2) { height = textHeight(display); }
  2922. if (diff > .001 || diff < -.001) {
  2923. updateLineHeight(cur.line, height);
  2924. updateWidgetHeight(cur.line);
  2925. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2926. { updateWidgetHeight(cur.rest[j]); } }
  2927. }
  2928. }
  2929. }
  2930. // Read and store the height of line widgets associated with the
  2931. // given line.
  2932. function updateWidgetHeight(line) {
  2933. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
  2934. { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } }
  2935. }
  2936. // Compute the lines that are visible in a given viewport (defaults
  2937. // the the current scroll position). viewport may contain top,
  2938. // height, and ensure (see op.scrollToPos) properties.
  2939. function visibleLines(display, doc, viewport) {
  2940. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  2941. top = Math.floor(top - paddingTop(display));
  2942. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  2943. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  2944. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2945. // forces those lines into the viewport (if possible).
  2946. if (viewport && viewport.ensure) {
  2947. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  2948. if (ensureFrom < from) {
  2949. from = ensureFrom;
  2950. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  2951. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2952. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  2953. to = ensureTo;
  2954. }
  2955. }
  2956. return {from: from, to: Math.max(to, from + 1)}
  2957. }
  2958. // Sync the scrollable area and scrollbars, ensure the viewport
  2959. // covers the visible area.
  2960. function setScrollTop(cm, val) {
  2961. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  2962. cm.doc.scrollTop = val;
  2963. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  2964. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  2965. cm.display.scrollbars.setScrollTop(val);
  2966. if (gecko) { updateDisplaySimple(cm); }
  2967. startWorker(cm, 100);
  2968. }
  2969. // Sync scroller and scrollbar, ensure the gutter elements are
  2970. // aligned.
  2971. function setScrollLeft(cm, val, isScroller) {
  2972. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
  2973. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  2974. cm.doc.scrollLeft = val;
  2975. alignHorizontally(cm);
  2976. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  2977. cm.display.scrollbars.setScrollLeft(val);
  2978. }
  2979. // Since the delta values reported on mouse wheel events are
  2980. // unstandardized between browsers and even browser versions, and
  2981. // generally horribly unpredictable, this code starts by measuring
  2982. // the scroll effect that the first few mouse wheel events have,
  2983. // and, from that, detects the way it can convert deltas to pixel
  2984. // offsets afterwards.
  2985. //
  2986. // The reason we want to know the amount a wheel event will scroll
  2987. // is that it gives us a chance to update the display before the
  2988. // actual scrolling happens, reducing flickering.
  2989. var wheelSamples = 0;
  2990. var wheelPixelsPerUnit = null;
  2991. // Fill in a browser-detected starting value on browsers where we
  2992. // know one. These don't have to be accurate -- the result of them
  2993. // being wrong would just be a slight flicker on the first wheel
  2994. // scroll (if it is large enough).
  2995. if (ie) { wheelPixelsPerUnit = -.53; }
  2996. else if (gecko) { wheelPixelsPerUnit = 15; }
  2997. else if (chrome) { wheelPixelsPerUnit = -.7; }
  2998. else if (safari) { wheelPixelsPerUnit = -1/3; }
  2999. function wheelEventDelta(e) {
  3000. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3001. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  3002. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  3003. else if (dy == null) { dy = e.wheelDelta; }
  3004. return {x: dx, y: dy}
  3005. }
  3006. function wheelEventPixels(e) {
  3007. var delta = wheelEventDelta(e);
  3008. delta.x *= wheelPixelsPerUnit;
  3009. delta.y *= wheelPixelsPerUnit;
  3010. return delta
  3011. }
  3012. function onScrollWheel(cm, e) {
  3013. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3014. var display = cm.display, scroll = display.scroller;
  3015. // Quit if there's nothing to scroll here
  3016. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3017. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3018. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3019. // Webkit browsers on OS X abort momentum scrolls when the target
  3020. // of the scroll event is removed from the scrollable element.
  3021. // This hack (see related code in patchDisplay) makes sure the
  3022. // element is kept around.
  3023. if (dy && mac && webkit) {
  3024. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3025. for (var i = 0; i < view.length; i++) {
  3026. if (view[i].node == cur) {
  3027. cm.display.currentWheelTarget = cur;
  3028. break outer
  3029. }
  3030. }
  3031. }
  3032. }
  3033. // On some browsers, horizontal scrolling will cause redraws to
  3034. // happen before the gutter has been realigned, causing it to
  3035. // wriggle around in a most unseemly way. When we have an
  3036. // estimated pixels/delta value, we just handle horizontal
  3037. // scrolling entirely here. It'll be slightly off from native, but
  3038. // better than glitching out.
  3039. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3040. if (dy && canScrollY)
  3041. { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); }
  3042. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3043. // Only prevent default scrolling if vertical scrolling is
  3044. // actually possible. Otherwise, it causes vertical scroll
  3045. // jitter on OSX trackpads when deltaX is small and deltaY
  3046. // is large (issue #3579)
  3047. if (!dy || (dy && canScrollY))
  3048. { e_preventDefault(e); }
  3049. display.wheelStartX = null; // Abort measurement, if in progress
  3050. return
  3051. }
  3052. // 'Project' the visible viewport to cover the area that is being
  3053. // scrolled into view (if we know enough to estimate it).
  3054. if (dy && wheelPixelsPerUnit != null) {
  3055. var pixels = dy * wheelPixelsPerUnit;
  3056. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3057. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  3058. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  3059. updateDisplaySimple(cm, {top: top, bottom: bot});
  3060. }
  3061. if (wheelSamples < 20) {
  3062. if (display.wheelStartX == null) {
  3063. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3064. display.wheelDX = dx; display.wheelDY = dy;
  3065. setTimeout(function () {
  3066. if (display.wheelStartX == null) { return }
  3067. var movedX = scroll.scrollLeft - display.wheelStartX;
  3068. var movedY = scroll.scrollTop - display.wheelStartY;
  3069. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3070. (movedX && display.wheelDX && movedX / display.wheelDX);
  3071. display.wheelStartX = display.wheelStartY = null;
  3072. if (!sample) { return }
  3073. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3074. ++wheelSamples;
  3075. }, 200);
  3076. } else {
  3077. display.wheelDX += dx; display.wheelDY += dy;
  3078. }
  3079. }
  3080. }
  3081. // SCROLLBARS
  3082. // Prepare DOM reads needed to update the scrollbars. Done in one
  3083. // shot to minimize update/measure roundtrips.
  3084. function measureForScrollbars(cm) {
  3085. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3086. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3087. return {
  3088. clientHeight: d.scroller.clientHeight,
  3089. viewHeight: d.wrapper.clientHeight,
  3090. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3091. viewWidth: d.wrapper.clientWidth,
  3092. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3093. docHeight: docH,
  3094. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3095. nativeBarWidth: d.nativeBarWidth,
  3096. gutterWidth: gutterW
  3097. }
  3098. }
  3099. var NativeScrollbars = function(place, scroll, cm) {
  3100. this.cm = cm;
  3101. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3102. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3103. place(vert); place(horiz);
  3104. on(vert, "scroll", function () {
  3105. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3106. });
  3107. on(horiz, "scroll", function () {
  3108. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3109. });
  3110. this.checkedZeroWidth = false;
  3111. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3112. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3113. };
  3114. NativeScrollbars.prototype.update = function (measure) {
  3115. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3116. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3117. var sWidth = measure.nativeBarWidth;
  3118. if (needsV) {
  3119. this.vert.style.display = "block";
  3120. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3121. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3122. // A bug in IE8 can cause this value to be negative, so guard it.
  3123. this.vert.firstChild.style.height =
  3124. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3125. } else {
  3126. this.vert.style.display = "";
  3127. this.vert.firstChild.style.height = "0";
  3128. }
  3129. if (needsH) {
  3130. this.horiz.style.display = "block";
  3131. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3132. this.horiz.style.left = measure.barLeft + "px";
  3133. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3134. this.horiz.firstChild.style.width =
  3135. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3136. } else {
  3137. this.horiz.style.display = "";
  3138. this.horiz.firstChild.style.width = "0";
  3139. }
  3140. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3141. if (sWidth == 0) { this.zeroWidthHack(); }
  3142. this.checkedZeroWidth = true;
  3143. }
  3144. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3145. };
  3146. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3147. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3148. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3149. };
  3150. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3151. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3152. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3153. };
  3154. NativeScrollbars.prototype.zeroWidthHack = function () {
  3155. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3156. this.horiz.style.height = this.vert.style.width = w;
  3157. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3158. this.disableHoriz = new Delayed;
  3159. this.disableVert = new Delayed;
  3160. };
  3161. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3162. bar.style.pointerEvents = "auto";
  3163. function maybeDisable() {
  3164. // To find out whether the scrollbar is still visible, we
  3165. // check whether the element under the pixel in the bottom
  3166. // right corner of the scrollbar box is the scrollbar box
  3167. // itself (when the bar is still visible) or its filler child
  3168. // (when the bar is hidden). If it is still visible, we keep
  3169. // it enabled, if it's hidden, we disable pointer events.
  3170. var box = bar.getBoundingClientRect();
  3171. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3172. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3173. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  3174. else { delay.set(1000, maybeDisable); }
  3175. }
  3176. delay.set(1000, maybeDisable);
  3177. };
  3178. NativeScrollbars.prototype.clear = function () {
  3179. var parent = this.horiz.parentNode;
  3180. parent.removeChild(this.horiz);
  3181. parent.removeChild(this.vert);
  3182. };
  3183. var NullScrollbars = function () {};
  3184. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3185. NullScrollbars.prototype.setScrollLeft = function () {};
  3186. NullScrollbars.prototype.setScrollTop = function () {};
  3187. NullScrollbars.prototype.clear = function () {};
  3188. function updateScrollbars(cm, measure) {
  3189. if (!measure) { measure = measureForScrollbars(cm); }
  3190. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3191. updateScrollbarsInner(cm, measure);
  3192. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3193. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3194. { updateHeightsInViewport(cm); }
  3195. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3196. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3197. }
  3198. }
  3199. // Re-synchronize the fake scrollbars with the actual size of the
  3200. // content.
  3201. function updateScrollbarsInner(cm, measure) {
  3202. var d = cm.display;
  3203. var sizes = d.scrollbars.update(measure);
  3204. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3205. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3206. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3207. if (sizes.right && sizes.bottom) {
  3208. d.scrollbarFiller.style.display = "block";
  3209. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3210. d.scrollbarFiller.style.width = sizes.right + "px";
  3211. } else { d.scrollbarFiller.style.display = ""; }
  3212. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3213. d.gutterFiller.style.display = "block";
  3214. d.gutterFiller.style.height = sizes.bottom + "px";
  3215. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3216. } else { d.gutterFiller.style.display = ""; }
  3217. }
  3218. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3219. function initScrollbars(cm) {
  3220. if (cm.display.scrollbars) {
  3221. cm.display.scrollbars.clear();
  3222. if (cm.display.scrollbars.addClass)
  3223. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3224. }
  3225. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3226. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3227. // Prevent clicks in the scrollbars from killing focus
  3228. on(node, "mousedown", function () {
  3229. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3230. });
  3231. node.setAttribute("cm-not-content", "true");
  3232. }, function (pos, axis) {
  3233. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3234. else { setScrollTop(cm, pos); }
  3235. }, cm);
  3236. if (cm.display.scrollbars.addClass)
  3237. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3238. }
  3239. // SCROLLING THINGS INTO VIEW
  3240. // If an editor sits on the top or bottom of the window, partially
  3241. // scrolled out of view, this ensures that the cursor is visible.
  3242. function maybeScrollWindow(cm, rect) {
  3243. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3244. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3245. if (rect.top + box.top < 0) { doScroll = true; }
  3246. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3247. if (doScroll != null && !phantom) {
  3248. 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;"));
  3249. cm.display.lineSpace.appendChild(scrollNode);
  3250. scrollNode.scrollIntoView(doScroll);
  3251. cm.display.lineSpace.removeChild(scrollNode);
  3252. }
  3253. }
  3254. // Scroll a given position into view (immediately), verifying that
  3255. // it actually became visible (as line heights are accurately
  3256. // measured, the position of something may 'drift' during drawing).
  3257. function scrollPosIntoView(cm, pos, end, margin) {
  3258. if (margin == null) { margin = 0; }
  3259. var rect;
  3260. for (var limit = 0; limit < 5; limit++) {
  3261. var changed = false;
  3262. var coords = cursorCoords(cm, pos);
  3263. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3264. rect = {left: Math.min(coords.left, endCoords.left),
  3265. top: Math.min(coords.top, endCoords.top) - margin,
  3266. right: Math.max(coords.left, endCoords.left),
  3267. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3268. var scrollPos = calculateScrollPos(cm, rect);
  3269. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3270. if (scrollPos.scrollTop != null) {
  3271. setScrollTop(cm, scrollPos.scrollTop);
  3272. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3273. }
  3274. if (scrollPos.scrollLeft != null) {
  3275. setScrollLeft(cm, scrollPos.scrollLeft);
  3276. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3277. }
  3278. if (!changed) { break }
  3279. }
  3280. return rect
  3281. }
  3282. // Scroll a given set of coordinates into view (immediately).
  3283. function scrollIntoView(cm, rect) {
  3284. var scrollPos = calculateScrollPos(cm, rect);
  3285. if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop); }
  3286. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3287. }
  3288. // Calculate a new scroll position needed to scroll the given
  3289. // rectangle into view. Returns an object with scrollTop and
  3290. // scrollLeft properties. When these are undefined, the
  3291. // vertical/horizontal position does not need to be adjusted.
  3292. function calculateScrollPos(cm, rect) {
  3293. var display = cm.display, snapMargin = textHeight(cm.display);
  3294. if (rect.top < 0) { rect.top = 0; }
  3295. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3296. var screen = displayHeight(cm), result = {};
  3297. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3298. var docBottom = cm.doc.height + paddingVert(display);
  3299. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3300. if (rect.top < screentop) {
  3301. result.scrollTop = atTop ? 0 : rect.top;
  3302. } else if (rect.bottom > screentop + screen) {
  3303. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3304. if (newTop != screentop) { result.scrollTop = newTop; }
  3305. }
  3306. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3307. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3308. var tooWide = rect.right - rect.left > screenw;
  3309. if (tooWide) { rect.right = rect.left + screenw; }
  3310. if (rect.left < 10)
  3311. { result.scrollLeft = 0; }
  3312. else if (rect.left < screenleft)
  3313. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  3314. else if (rect.right > screenw + screenleft - 3)
  3315. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3316. return result
  3317. }
  3318. // Store a relative adjustment to the scroll position in the current
  3319. // operation (to be applied when the operation finishes).
  3320. function addToScrollPos(cm, left, top) {
  3321. if (left != null || top != null) { resolveScrollToPos(cm); }
  3322. if (left != null)
  3323. { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; }
  3324. if (top != null)
  3325. { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; }
  3326. }
  3327. // Make sure that at the end of the operation the current cursor is
  3328. // shown.
  3329. function ensureCursorVisible(cm) {
  3330. resolveScrollToPos(cm);
  3331. var cur = cm.getCursor(), from = cur, to = cur;
  3332. if (!cm.options.lineWrapping) {
  3333. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  3334. to = Pos(cur.line, cur.ch + 1);
  3335. }
  3336. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin};
  3337. }
  3338. // When an operation has its scrollToPos property set, and another
  3339. // scroll action is applied before the end of the operation, this
  3340. // 'simulates' scrolling that position into view in a cheap way, so
  3341. // that the effect of intermediate scroll commands is not ignored.
  3342. function resolveScrollToPos(cm) {
  3343. var range$$1 = cm.curOp.scrollToPos;
  3344. if (range$$1) {
  3345. cm.curOp.scrollToPos = null;
  3346. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  3347. var sPos = calculateScrollPos(cm, {
  3348. left: Math.min(from.left, to.left),
  3349. top: Math.min(from.top, to.top) - range$$1.margin,
  3350. right: Math.max(from.right, to.right),
  3351. bottom: Math.max(from.bottom, to.bottom) + range$$1.margin
  3352. });
  3353. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  3354. }
  3355. }
  3356. // Operations are used to wrap a series of changes to the editor
  3357. // state in such a way that each change won't have to update the
  3358. // cursor and display (which would be awkward, slow, and
  3359. // error-prone). Instead, display updates are batched and then all
  3360. // combined and executed at once.
  3361. var nextOpId = 0;
  3362. // Start a new operation.
  3363. function startOperation(cm) {
  3364. cm.curOp = {
  3365. cm: cm,
  3366. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3367. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3368. forceUpdate: false, // Used to force a redraw
  3369. updateInput: null, // Whether to reset the input textarea
  3370. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3371. changeObjs: null, // Accumulated changes, for firing change events
  3372. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3373. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3374. selectionChanged: false, // Whether the selection needs to be redrawn
  3375. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3376. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3377. scrollToPos: null, // Used to scroll to a specific position
  3378. focus: false,
  3379. id: ++nextOpId // Unique ID
  3380. };
  3381. pushOperation(cm.curOp);
  3382. }
  3383. // Finish an operation, updating the display and signalling delayed events
  3384. function endOperation(cm) {
  3385. var op = cm.curOp;
  3386. finishOperation(op, function (group) {
  3387. for (var i = 0; i < group.ops.length; i++)
  3388. { group.ops[i].cm.curOp = null; }
  3389. endOperations(group);
  3390. });
  3391. }
  3392. // The DOM updates done when an operation finishes are batched so
  3393. // that the minimum number of relayouts are required.
  3394. function endOperations(group) {
  3395. var ops = group.ops;
  3396. for (var i = 0; i < ops.length; i++) // Read DOM
  3397. { endOperation_R1(ops[i]); }
  3398. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3399. { endOperation_W1(ops[i$1]); }
  3400. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3401. { endOperation_R2(ops[i$2]); }
  3402. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3403. { endOperation_W2(ops[i$3]); }
  3404. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3405. { endOperation_finish(ops[i$4]); }
  3406. }
  3407. function endOperation_R1(op) {
  3408. var cm = op.cm, display = cm.display;
  3409. maybeClipScrollbars(cm);
  3410. if (op.updateMaxLine) { findMaxLine(cm); }
  3411. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3412. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3413. op.scrollToPos.to.line >= display.viewTo) ||
  3414. display.maxLineChanged && cm.options.lineWrapping;
  3415. op.update = op.mustUpdate &&
  3416. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3417. }
  3418. function endOperation_W1(op) {
  3419. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3420. }
  3421. function endOperation_R2(op) {
  3422. var cm = op.cm, display = cm.display;
  3423. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3424. op.barMeasure = measureForScrollbars(cm);
  3425. // If the max line changed since it was last measured, measure it,
  3426. // and ensure the document's width matches it.
  3427. // updateDisplay_W2 will use these properties to do the actual resizing
  3428. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3429. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3430. cm.display.sizerWidth = op.adjustWidthTo;
  3431. op.barMeasure.scrollWidth =
  3432. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3433. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3434. }
  3435. if (op.updatedDisplay || op.selectionChanged)
  3436. { op.preparedSelection = display.input.prepareSelection(op.focus); }
  3437. }
  3438. function endOperation_W2(op) {
  3439. var cm = op.cm;
  3440. if (op.adjustWidthTo != null) {
  3441. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3442. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3443. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3444. cm.display.maxLineChanged = false;
  3445. }
  3446. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus());
  3447. if (op.preparedSelection)
  3448. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3449. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3450. { updateScrollbars(cm, op.barMeasure); }
  3451. if (op.updatedDisplay)
  3452. { setDocumentHeight(cm, op.barMeasure); }
  3453. if (op.selectionChanged) { restartBlink(cm); }
  3454. if (cm.state.focused && op.updateInput)
  3455. { cm.display.input.reset(op.typing); }
  3456. if (takeFocus) { ensureFocus(op.cm); }
  3457. }
  3458. function endOperation_finish(op) {
  3459. var cm = op.cm, display = cm.display, doc = cm.doc;
  3460. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3461. // Abort mouse wheel delta measurement, when scrolling explicitly
  3462. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3463. { display.wheelStartX = display.wheelStartY = null; }
  3464. // Propagate the scroll position to the actual DOM scroller
  3465. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  3466. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  3467. display.scrollbars.setScrollTop(doc.scrollTop);
  3468. display.scroller.scrollTop = doc.scrollTop;
  3469. }
  3470. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  3471. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  3472. display.scrollbars.setScrollLeft(doc.scrollLeft);
  3473. display.scroller.scrollLeft = doc.scrollLeft;
  3474. alignHorizontally(cm);
  3475. }
  3476. // If we need to scroll a specific position into view, do so.
  3477. if (op.scrollToPos) {
  3478. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3479. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3480. maybeScrollWindow(cm, rect);
  3481. }
  3482. // Fire events for markers that are hidden/unidden by editing or
  3483. // undoing
  3484. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3485. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3486. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3487. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3488. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3489. if (display.wrapper.offsetHeight)
  3490. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3491. // Fire change events, and delayed event handlers
  3492. if (op.changeObjs)
  3493. { signal(cm, "changes", cm, op.changeObjs); }
  3494. if (op.update)
  3495. { op.update.finish(); }
  3496. }
  3497. // Run the given function in an operation
  3498. function runInOp(cm, f) {
  3499. if (cm.curOp) { return f() }
  3500. startOperation(cm);
  3501. try { return f() }
  3502. finally { endOperation(cm); }
  3503. }
  3504. // Wraps a function in an operation. Returns the wrapped function.
  3505. function operation(cm, f) {
  3506. return function() {
  3507. if (cm.curOp) { return f.apply(cm, arguments) }
  3508. startOperation(cm);
  3509. try { return f.apply(cm, arguments) }
  3510. finally { endOperation(cm); }
  3511. }
  3512. }
  3513. // Used to add methods to editor and doc instances, wrapping them in
  3514. // operations.
  3515. function methodOp(f) {
  3516. return function() {
  3517. if (this.curOp) { return f.apply(this, arguments) }
  3518. startOperation(this);
  3519. try { return f.apply(this, arguments) }
  3520. finally { endOperation(this); }
  3521. }
  3522. }
  3523. function docMethodOp(f) {
  3524. return function() {
  3525. var cm = this.cm;
  3526. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3527. startOperation(cm);
  3528. try { return f.apply(this, arguments) }
  3529. finally { endOperation(cm); }
  3530. }
  3531. }
  3532. // Updates the display.view data structure for a given change to the
  3533. // document. From and to are in pre-change coordinates. Lendiff is
  3534. // the amount of lines added or subtracted by the change. This is
  3535. // used for changes that span multiple lines, or change the way
  3536. // lines are divided into visual lines. regLineChange (below)
  3537. // registers single-line changes.
  3538. function regChange(cm, from, to, lendiff) {
  3539. if (from == null) { from = cm.doc.first; }
  3540. if (to == null) { to = cm.doc.first + cm.doc.size; }
  3541. if (!lendiff) { lendiff = 0; }
  3542. var display = cm.display;
  3543. if (lendiff && to < display.viewTo &&
  3544. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3545. { display.updateLineNumbers = from; }
  3546. cm.curOp.viewChanged = true;
  3547. if (from >= display.viewTo) { // Change after
  3548. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3549. { resetView(cm); }
  3550. } else if (to <= display.viewFrom) { // Change before
  3551. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3552. resetView(cm);
  3553. } else {
  3554. display.viewFrom += lendiff;
  3555. display.viewTo += lendiff;
  3556. }
  3557. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3558. resetView(cm);
  3559. } else if (from <= display.viewFrom) { // Top overlap
  3560. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  3561. if (cut) {
  3562. display.view = display.view.slice(cut.index);
  3563. display.viewFrom = cut.lineN;
  3564. display.viewTo += lendiff;
  3565. } else {
  3566. resetView(cm);
  3567. }
  3568. } else if (to >= display.viewTo) { // Bottom overlap
  3569. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  3570. if (cut$1) {
  3571. display.view = display.view.slice(0, cut$1.index);
  3572. display.viewTo = cut$1.lineN;
  3573. } else {
  3574. resetView(cm);
  3575. }
  3576. } else { // Gap in the middle
  3577. var cutTop = viewCuttingPoint(cm, from, from, -1);
  3578. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  3579. if (cutTop && cutBot) {
  3580. display.view = display.view.slice(0, cutTop.index)
  3581. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3582. .concat(display.view.slice(cutBot.index));
  3583. display.viewTo += lendiff;
  3584. } else {
  3585. resetView(cm);
  3586. }
  3587. }
  3588. var ext = display.externalMeasured;
  3589. if (ext) {
  3590. if (to < ext.lineN)
  3591. { ext.lineN += lendiff; }
  3592. else if (from < ext.lineN + ext.size)
  3593. { display.externalMeasured = null; }
  3594. }
  3595. }
  3596. // Register a change to a single line. Type must be one of "text",
  3597. // "gutter", "class", "widget"
  3598. function regLineChange(cm, line, type) {
  3599. cm.curOp.viewChanged = true;
  3600. var display = cm.display, ext = cm.display.externalMeasured;
  3601. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3602. { display.externalMeasured = null; }
  3603. if (line < display.viewFrom || line >= display.viewTo) { return }
  3604. var lineView = display.view[findViewIndex(cm, line)];
  3605. if (lineView.node == null) { return }
  3606. var arr = lineView.changes || (lineView.changes = []);
  3607. if (indexOf(arr, type) == -1) { arr.push(type); }
  3608. }
  3609. // Clear the view.
  3610. function resetView(cm) {
  3611. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  3612. cm.display.view = [];
  3613. cm.display.viewOffset = 0;
  3614. }
  3615. function viewCuttingPoint(cm, oldN, newN, dir) {
  3616. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3617. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3618. { return {index: index, lineN: newN} }
  3619. var n = cm.display.viewFrom;
  3620. for (var i = 0; i < index; i++)
  3621. { n += view[i].size; }
  3622. if (n != oldN) {
  3623. if (dir > 0) {
  3624. if (index == view.length - 1) { return null }
  3625. diff = (n + view[index].size) - oldN;
  3626. index++;
  3627. } else {
  3628. diff = n - oldN;
  3629. }
  3630. oldN += diff; newN += diff;
  3631. }
  3632. while (visualLineNo(cm.doc, newN) != newN) {
  3633. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3634. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3635. index += dir;
  3636. }
  3637. return {index: index, lineN: newN}
  3638. }
  3639. // Force the view to cover a given range, adding empty view element
  3640. // or clipping off existing ones as needed.
  3641. function adjustView(cm, from, to) {
  3642. var display = cm.display, view = display.view;
  3643. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3644. display.view = buildViewArray(cm, from, to);
  3645. display.viewFrom = from;
  3646. } else {
  3647. if (display.viewFrom > from)
  3648. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  3649. else if (display.viewFrom < from)
  3650. { display.view = display.view.slice(findViewIndex(cm, from)); }
  3651. display.viewFrom = from;
  3652. if (display.viewTo < to)
  3653. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  3654. else if (display.viewTo > to)
  3655. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  3656. }
  3657. display.viewTo = to;
  3658. }
  3659. // Count the number of lines in the view whose DOM representation is
  3660. // out of date (or nonexistent).
  3661. function countDirtyView(cm) {
  3662. var view = cm.display.view, dirty = 0;
  3663. for (var i = 0; i < view.length; i++) {
  3664. var lineView = view[i];
  3665. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  3666. }
  3667. return dirty
  3668. }
  3669. // HIGHLIGHT WORKER
  3670. function startWorker(cm, time) {
  3671. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  3672. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3673. }
  3674. function highlightWorker(cm) {
  3675. var doc = cm.doc;
  3676. if (doc.frontier < doc.first) { doc.frontier = doc.first; }
  3677. if (doc.frontier >= cm.display.viewTo) { return }
  3678. var end = +new Date + cm.options.workTime;
  3679. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  3680. var changedLines = [];
  3681. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3682. if (doc.frontier >= cm.display.viewFrom) { // Visible
  3683. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  3684. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  3685. line.styles = highlighted.styles;
  3686. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3687. if (newCls) { line.styleClasses = newCls; }
  3688. else if (oldCls) { line.styleClasses = null; }
  3689. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3690. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3691. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3692. if (ischange) { changedLines.push(doc.frontier); }
  3693. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  3694. } else {
  3695. if (line.text.length <= cm.options.maxHighlightLength)
  3696. { processLine(cm, line.text, state); }
  3697. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  3698. }
  3699. ++doc.frontier;
  3700. if (+new Date > end) {
  3701. startWorker(cm, cm.options.workDelay);
  3702. return true
  3703. }
  3704. });
  3705. if (changedLines.length) { runInOp(cm, function () {
  3706. for (var i = 0; i < changedLines.length; i++)
  3707. { regLineChange(cm, changedLines[i], "text"); }
  3708. }); }
  3709. }
  3710. // DISPLAY DRAWING
  3711. var DisplayUpdate = function(cm, viewport, force) {
  3712. var display = cm.display;
  3713. this.viewport = viewport;
  3714. // Store some values that we'll need later (but don't want to force a relayout for)
  3715. this.visible = visibleLines(display, cm.doc, viewport);
  3716. this.editorIsHidden = !display.wrapper.offsetWidth;
  3717. this.wrapperHeight = display.wrapper.clientHeight;
  3718. this.wrapperWidth = display.wrapper.clientWidth;
  3719. this.oldDisplayWidth = displayWidth(cm);
  3720. this.force = force;
  3721. this.dims = getDimensions(cm);
  3722. this.events = [];
  3723. };
  3724. DisplayUpdate.prototype.signal = function (emitter, type) {
  3725. if (hasHandler(emitter, type))
  3726. { this.events.push(arguments); }
  3727. };
  3728. DisplayUpdate.prototype.finish = function () {
  3729. var this$1 = this;
  3730. for (var i = 0; i < this.events.length; i++)
  3731. { signal.apply(null, this$1.events[i]); }
  3732. };
  3733. function maybeClipScrollbars(cm) {
  3734. var display = cm.display;
  3735. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3736. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3737. display.heightForcer.style.height = scrollGap(cm) + "px";
  3738. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3739. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3740. display.scrollbarsClipped = true;
  3741. }
  3742. }
  3743. // Does the actual updating of the line display. Bails out
  3744. // (returning false) when there is nothing to be done and forced is
  3745. // false.
  3746. function updateDisplayIfNeeded(cm, update) {
  3747. var display = cm.display, doc = cm.doc;
  3748. if (update.editorIsHidden) {
  3749. resetView(cm);
  3750. return false
  3751. }
  3752. // Bail out if the visible area is already rendered and nothing changed.
  3753. if (!update.force &&
  3754. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3755. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3756. display.renderedView == display.view && countDirtyView(cm) == 0)
  3757. { return false }
  3758. if (maybeUpdateLineNumberWidth(cm)) {
  3759. resetView(cm);
  3760. update.dims = getDimensions(cm);
  3761. }
  3762. // Compute a suitable new viewport (from & to)
  3763. var end = doc.first + doc.size;
  3764. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3765. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3766. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3767. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3768. if (sawCollapsedSpans) {
  3769. from = visualLineNo(cm.doc, from);
  3770. to = visualLineEndNo(cm.doc, to);
  3771. }
  3772. var different = from != display.viewFrom || to != display.viewTo ||
  3773. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3774. adjustView(cm, from, to);
  3775. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3776. // Position the mover div to align with the current scroll position
  3777. cm.display.mover.style.top = display.viewOffset + "px";
  3778. var toUpdate = countDirtyView(cm);
  3779. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3780. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3781. { return false }
  3782. // For big changes, we hide the enclosing element during the
  3783. // update, since that speeds up the operations on most browsers.
  3784. var focused = activeElt();
  3785. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3786. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3787. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3788. display.renderedView = display.view;
  3789. // There might have been a widget with a focused element that got
  3790. // hidden or updated, if so re-focus it.
  3791. if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus(); }
  3792. // Prevent selection and cursors from interfering with the scroll
  3793. // width and height.
  3794. removeChildren(display.cursorDiv);
  3795. removeChildren(display.selectionDiv);
  3796. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3797. if (different) {
  3798. display.lastWrapHeight = update.wrapperHeight;
  3799. display.lastWrapWidth = update.wrapperWidth;
  3800. startWorker(cm, 400);
  3801. }
  3802. display.updateLineNumbers = null;
  3803. return true
  3804. }
  3805. function postUpdateDisplay(cm, update) {
  3806. var viewport = update.viewport;
  3807. for (var first = true;; first = false) {
  3808. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3809. // Clip forced viewport to actual scrollable area.
  3810. if (viewport && viewport.top != null)
  3811. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3812. // Updated line heights might result in the drawn area not
  3813. // actually covering the viewport. Keep looping until it does.
  3814. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3815. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3816. { break }
  3817. }
  3818. if (!updateDisplayIfNeeded(cm, update)) { break }
  3819. updateHeightsInViewport(cm);
  3820. var barMeasure = measureForScrollbars(cm);
  3821. updateSelection(cm);
  3822. updateScrollbars(cm, barMeasure);
  3823. setDocumentHeight(cm, barMeasure);
  3824. }
  3825. update.signal(cm, "update", cm);
  3826. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3827. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3828. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3829. }
  3830. }
  3831. function updateDisplaySimple(cm, viewport) {
  3832. var update = new DisplayUpdate(cm, viewport);
  3833. if (updateDisplayIfNeeded(cm, update)) {
  3834. updateHeightsInViewport(cm);
  3835. postUpdateDisplay(cm, update);
  3836. var barMeasure = measureForScrollbars(cm);
  3837. updateSelection(cm);
  3838. updateScrollbars(cm, barMeasure);
  3839. setDocumentHeight(cm, barMeasure);
  3840. update.finish();
  3841. }
  3842. }
  3843. // Sync the actual display DOM structure with display.view, removing
  3844. // nodes for lines that are no longer in view, and creating the ones
  3845. // that are not there yet, and updating the ones that are out of
  3846. // date.
  3847. function patchDisplay(cm, updateNumbersFrom, dims) {
  3848. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3849. var container = display.lineDiv, cur = container.firstChild;
  3850. function rm(node) {
  3851. var next = node.nextSibling;
  3852. // Works around a throw-scroll bug in OS X Webkit
  3853. if (webkit && mac && cm.display.currentWheelTarget == node)
  3854. { node.style.display = "none"; }
  3855. else
  3856. { node.parentNode.removeChild(node); }
  3857. return next
  3858. }
  3859. var view = display.view, lineN = display.viewFrom;
  3860. // Loop over the elements in the view, syncing cur (the DOM nodes
  3861. // in display.lineDiv) with the view as we go.
  3862. for (var i = 0; i < view.length; i++) {
  3863. var lineView = view[i];
  3864. if (lineView.hidden) {
  3865. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3866. var node = buildLineElement(cm, lineView, lineN, dims);
  3867. container.insertBefore(node, cur);
  3868. } else { // Already drawn
  3869. while (cur != lineView.node) { cur = rm(cur); }
  3870. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3871. updateNumbersFrom <= lineN && lineView.lineNumber;
  3872. if (lineView.changes) {
  3873. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3874. updateLineForChanges(cm, lineView, lineN, dims);
  3875. }
  3876. if (updateNumber) {
  3877. removeChildren(lineView.lineNumber);
  3878. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3879. }
  3880. cur = lineView.node.nextSibling;
  3881. }
  3882. lineN += lineView.size;
  3883. }
  3884. while (cur) { cur = rm(cur); }
  3885. }
  3886. function updateGutterSpace(cm) {
  3887. var width = cm.display.gutters.offsetWidth;
  3888. cm.display.sizer.style.marginLeft = width + "px";
  3889. }
  3890. function setDocumentHeight(cm, measure) {
  3891. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3892. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3893. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3894. }
  3895. // Rebuild the gutter elements, ensure the margin to the left of the
  3896. // code matches their width.
  3897. function updateGutters(cm) {
  3898. var gutters = cm.display.gutters, specs = cm.options.gutters;
  3899. removeChildren(gutters);
  3900. var i = 0;
  3901. for (; i < specs.length; ++i) {
  3902. var gutterClass = specs[i];
  3903. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  3904. if (gutterClass == "CodeMirror-linenumbers") {
  3905. cm.display.lineGutter = gElt;
  3906. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  3907. }
  3908. }
  3909. gutters.style.display = i ? "" : "none";
  3910. updateGutterSpace(cm);
  3911. }
  3912. // Make sure the gutters options contains the element
  3913. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3914. function setGuttersForLineNumbers(options) {
  3915. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  3916. if (found == -1 && options.lineNumbers) {
  3917. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  3918. } else if (found > -1 && !options.lineNumbers) {
  3919. options.gutters = options.gutters.slice(0);
  3920. options.gutters.splice(found, 1);
  3921. }
  3922. }
  3923. // Selection objects are immutable. A new one is created every time
  3924. // the selection changes. A selection is one or more non-overlapping
  3925. // (and non-touching) ranges, sorted, and an integer that indicates
  3926. // which one is the primary selection (the one that's scrolled into
  3927. // view, that getCursor returns, etc).
  3928. var Selection = function(ranges, primIndex) {
  3929. this.ranges = ranges;
  3930. this.primIndex = primIndex;
  3931. };
  3932. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  3933. Selection.prototype.equals = function (other) {
  3934. var this$1 = this;
  3935. if (other == this) { return true }
  3936. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  3937. for (var i = 0; i < this.ranges.length; i++) {
  3938. var here = this$1.ranges[i], there = other.ranges[i];
  3939. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  3940. }
  3941. return true
  3942. };
  3943. Selection.prototype.deepCopy = function () {
  3944. var this$1 = this;
  3945. var out = [];
  3946. for (var i = 0; i < this.ranges.length; i++)
  3947. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  3948. return new Selection(out, this.primIndex)
  3949. };
  3950. Selection.prototype.somethingSelected = function () {
  3951. var this$1 = this;
  3952. for (var i = 0; i < this.ranges.length; i++)
  3953. { if (!this$1.ranges[i].empty()) { return true } }
  3954. return false
  3955. };
  3956. Selection.prototype.contains = function (pos, end) {
  3957. var this$1 = this;
  3958. if (!end) { end = pos; }
  3959. for (var i = 0; i < this.ranges.length; i++) {
  3960. var range = this$1.ranges[i];
  3961. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3962. { return i }
  3963. }
  3964. return -1
  3965. };
  3966. var Range = function(anchor, head) {
  3967. this.anchor = anchor; this.head = head;
  3968. };
  3969. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  3970. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  3971. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  3972. // Take an unsorted, potentially overlapping set of ranges, and
  3973. // build a selection out of it. 'Consumes' ranges array (modifying
  3974. // it).
  3975. function normalizeSelection(ranges, primIndex) {
  3976. var prim = ranges[primIndex];
  3977. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  3978. primIndex = indexOf(ranges, prim);
  3979. for (var i = 1; i < ranges.length; i++) {
  3980. var cur = ranges[i], prev = ranges[i - 1];
  3981. if (cmp(prev.to(), cur.from()) >= 0) {
  3982. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  3983. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  3984. if (i <= primIndex) { --primIndex; }
  3985. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  3986. }
  3987. }
  3988. return new Selection(ranges, primIndex)
  3989. }
  3990. function simpleSelection(anchor, head) {
  3991. return new Selection([new Range(anchor, head || anchor)], 0)
  3992. }
  3993. // Compute the position of the end of a change (its 'to' property
  3994. // refers to the pre-change end).
  3995. function changeEnd(change) {
  3996. if (!change.text) { return change.to }
  3997. return Pos(change.from.line + change.text.length - 1,
  3998. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  3999. }
  4000. // Adjust a position to refer to the post-change position of the
  4001. // same text, or the end of the change if the change covers it.
  4002. function adjustForChange(pos, change) {
  4003. if (cmp(pos, change.from) < 0) { return pos }
  4004. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4005. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4006. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4007. return Pos(line, ch)
  4008. }
  4009. function computeSelAfterChange(doc, change) {
  4010. var out = [];
  4011. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4012. var range = doc.sel.ranges[i];
  4013. out.push(new Range(adjustForChange(range.anchor, change),
  4014. adjustForChange(range.head, change)));
  4015. }
  4016. return normalizeSelection(out, doc.sel.primIndex)
  4017. }
  4018. function offsetPos(pos, old, nw) {
  4019. if (pos.line == old.line)
  4020. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4021. else
  4022. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4023. }
  4024. // Used by replaceSelections to allow moving the selection to the
  4025. // start or around the replaced test. Hint may be "start" or "around".
  4026. function computeReplacedSel(doc, changes, hint) {
  4027. var out = [];
  4028. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4029. for (var i = 0; i < changes.length; i++) {
  4030. var change = changes[i];
  4031. var from = offsetPos(change.from, oldPrev, newPrev);
  4032. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4033. oldPrev = change.to;
  4034. newPrev = to;
  4035. if (hint == "around") {
  4036. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4037. out[i] = new Range(inv ? to : from, inv ? from : to);
  4038. } else {
  4039. out[i] = new Range(from, from);
  4040. }
  4041. }
  4042. return new Selection(out, doc.sel.primIndex)
  4043. }
  4044. // Used to get the editor into a consistent state again when options change.
  4045. function loadMode(cm) {
  4046. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4047. resetModeState(cm);
  4048. }
  4049. function resetModeState(cm) {
  4050. cm.doc.iter(function (line) {
  4051. if (line.stateAfter) { line.stateAfter = null; }
  4052. if (line.styles) { line.styles = null; }
  4053. });
  4054. cm.doc.frontier = cm.doc.first;
  4055. startWorker(cm, 100);
  4056. cm.state.modeGen++;
  4057. if (cm.curOp) { regChange(cm); }
  4058. }
  4059. // DOCUMENT DATA STRUCTURE
  4060. // By default, updates that start and end at the beginning of a line
  4061. // are treated specially, in order to make the association of line
  4062. // widgets and marker elements with the text behave more intuitive.
  4063. function isWholeLineUpdate(doc, change) {
  4064. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4065. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4066. }
  4067. // Perform a change on the document data structure.
  4068. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  4069. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4070. function update(line, text, spans) {
  4071. updateLine(line, text, spans, estimateHeight$$1);
  4072. signalLater(line, "change", line, change);
  4073. }
  4074. function linesFor(start, end) {
  4075. var result = [];
  4076. for (var i = start; i < end; ++i)
  4077. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  4078. return result
  4079. }
  4080. var from = change.from, to = change.to, text = change.text;
  4081. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4082. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4083. // Adjust the line structure
  4084. if (change.full) {
  4085. doc.insert(0, linesFor(0, text.length));
  4086. doc.remove(text.length, doc.size - text.length);
  4087. } else if (isWholeLineUpdate(doc, change)) {
  4088. // This is a whole-line replace. Treated specially to make
  4089. // sure line objects move the way they are supposed to.
  4090. var added = linesFor(0, text.length - 1);
  4091. update(lastLine, lastLine.text, lastSpans);
  4092. if (nlines) { doc.remove(from.line, nlines); }
  4093. if (added.length) { doc.insert(from.line, added); }
  4094. } else if (firstLine == lastLine) {
  4095. if (text.length == 1) {
  4096. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4097. } else {
  4098. var added$1 = linesFor(1, text.length - 1);
  4099. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  4100. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4101. doc.insert(from.line + 1, added$1);
  4102. }
  4103. } else if (text.length == 1) {
  4104. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4105. doc.remove(from.line + 1, nlines);
  4106. } else {
  4107. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4108. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4109. var added$2 = linesFor(1, text.length - 1);
  4110. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4111. doc.insert(from.line + 1, added$2);
  4112. }
  4113. signalLater(doc, "change", doc, change);
  4114. }
  4115. // Call f for all linked documents.
  4116. function linkedDocs(doc, f, sharedHistOnly) {
  4117. function propagate(doc, skip, sharedHist) {
  4118. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4119. var rel = doc.linked[i];
  4120. if (rel.doc == skip) { continue }
  4121. var shared = sharedHist && rel.sharedHist;
  4122. if (sharedHistOnly && !shared) { continue }
  4123. f(rel.doc, shared);
  4124. propagate(rel.doc, doc, shared);
  4125. } }
  4126. }
  4127. propagate(doc, null, true);
  4128. }
  4129. // Attach a document to an editor.
  4130. function attachDoc(cm, doc) {
  4131. if (doc.cm) { throw new Error("This document is already in use.") }
  4132. cm.doc = doc;
  4133. doc.cm = cm;
  4134. estimateLineHeights(cm);
  4135. loadMode(cm);
  4136. setDirectionClass(cm);
  4137. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4138. cm.options.mode = doc.modeOption;
  4139. regChange(cm);
  4140. }
  4141. function setDirectionClass(cm) {
  4142. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4143. }
  4144. function directionChanged(cm) {
  4145. runInOp(cm, function () {
  4146. setDirectionClass(cm);
  4147. regChange(cm);
  4148. });
  4149. }
  4150. function History(startGen) {
  4151. // Arrays of change events and selections. Doing something adds an
  4152. // event to done and clears undo. Undoing moves events from done
  4153. // to undone, redoing moves them in the other direction.
  4154. this.done = []; this.undone = [];
  4155. this.undoDepth = Infinity;
  4156. // Used to track when changes can be merged into a single undo
  4157. // event
  4158. this.lastModTime = this.lastSelTime = 0;
  4159. this.lastOp = this.lastSelOp = null;
  4160. this.lastOrigin = this.lastSelOrigin = null;
  4161. // Used by the isClean() method
  4162. this.generation = this.maxGeneration = startGen || 1;
  4163. }
  4164. // Create a history change event from an updateDoc-style change
  4165. // object.
  4166. function historyChangeFromChange(doc, change) {
  4167. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4168. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4169. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4170. return histChange
  4171. }
  4172. // Pop all selection events off the end of a history array. Stop at
  4173. // a change event.
  4174. function clearSelectionEvents(array) {
  4175. while (array.length) {
  4176. var last = lst(array);
  4177. if (last.ranges) { array.pop(); }
  4178. else { break }
  4179. }
  4180. }
  4181. // Find the top change event in the history. Pop off selection
  4182. // events that are in the way.
  4183. function lastChangeEvent(hist, force) {
  4184. if (force) {
  4185. clearSelectionEvents(hist.done);
  4186. return lst(hist.done)
  4187. } else if (hist.done.length && !lst(hist.done).ranges) {
  4188. return lst(hist.done)
  4189. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4190. hist.done.pop();
  4191. return lst(hist.done)
  4192. }
  4193. }
  4194. // Register a change in the history. Merges changes that are within
  4195. // a single operation, or are close together with an origin that
  4196. // allows merging (starting with "+") into a single event.
  4197. function addChangeToHistory(doc, change, selAfter, opId) {
  4198. var hist = doc.history;
  4199. hist.undone.length = 0;
  4200. var time = +new Date, cur;
  4201. var last;
  4202. if ((hist.lastOp == opId ||
  4203. hist.lastOrigin == change.origin && change.origin &&
  4204. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4205. change.origin.charAt(0) == "*")) &&
  4206. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4207. // Merge this change into the last event
  4208. last = lst(cur.changes);
  4209. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4210. // Optimized case for simple insertion -- don't want to add
  4211. // new changesets for every character typed
  4212. last.to = changeEnd(change);
  4213. } else {
  4214. // Add new sub-event
  4215. cur.changes.push(historyChangeFromChange(doc, change));
  4216. }
  4217. } else {
  4218. // Can not be merged, start a new event.
  4219. var before = lst(hist.done);
  4220. if (!before || !before.ranges)
  4221. { pushSelectionToHistory(doc.sel, hist.done); }
  4222. cur = {changes: [historyChangeFromChange(doc, change)],
  4223. generation: hist.generation};
  4224. hist.done.push(cur);
  4225. while (hist.done.length > hist.undoDepth) {
  4226. hist.done.shift();
  4227. if (!hist.done[0].ranges) { hist.done.shift(); }
  4228. }
  4229. }
  4230. hist.done.push(selAfter);
  4231. hist.generation = ++hist.maxGeneration;
  4232. hist.lastModTime = hist.lastSelTime = time;
  4233. hist.lastOp = hist.lastSelOp = opId;
  4234. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4235. if (!last) { signal(doc, "historyAdded"); }
  4236. }
  4237. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4238. var ch = origin.charAt(0);
  4239. return ch == "*" ||
  4240. ch == "+" &&
  4241. prev.ranges.length == sel.ranges.length &&
  4242. prev.somethingSelected() == sel.somethingSelected() &&
  4243. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4244. }
  4245. // Called whenever the selection changes, sets the new selection as
  4246. // the pending selection in the history, and pushes the old pending
  4247. // selection into the 'done' array when it was significantly
  4248. // different (in number of selected ranges, emptiness, or time).
  4249. function addSelectionToHistory(doc, sel, opId, options) {
  4250. var hist = doc.history, origin = options && options.origin;
  4251. // A new event is started when the previous origin does not match
  4252. // the current, or the origins don't allow matching. Origins
  4253. // starting with * are always merged, those starting with + are
  4254. // merged when similar and close together in time.
  4255. if (opId == hist.lastSelOp ||
  4256. (origin && hist.lastSelOrigin == origin &&
  4257. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4258. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4259. { hist.done[hist.done.length - 1] = sel; }
  4260. else
  4261. { pushSelectionToHistory(sel, hist.done); }
  4262. hist.lastSelTime = +new Date;
  4263. hist.lastSelOrigin = origin;
  4264. hist.lastSelOp = opId;
  4265. if (options && options.clearRedo !== false)
  4266. { clearSelectionEvents(hist.undone); }
  4267. }
  4268. function pushSelectionToHistory(sel, dest) {
  4269. var top = lst(dest);
  4270. if (!(top && top.ranges && top.equals(sel)))
  4271. { dest.push(sel); }
  4272. }
  4273. // Used to store marked span information in the history.
  4274. function attachLocalSpans(doc, change, from, to) {
  4275. var existing = change["spans_" + doc.id], n = 0;
  4276. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4277. if (line.markedSpans)
  4278. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4279. ++n;
  4280. });
  4281. }
  4282. // When un/re-doing restores text containing marked spans, those
  4283. // that have been explicitly cleared should not be restored.
  4284. function removeClearedSpans(spans) {
  4285. if (!spans) { return null }
  4286. var out;
  4287. for (var i = 0; i < spans.length; ++i) {
  4288. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4289. else if (out) { out.push(spans[i]); }
  4290. }
  4291. return !out ? spans : out.length ? out : null
  4292. }
  4293. // Retrieve and filter the old marked spans stored in a change event.
  4294. function getOldSpans(doc, change) {
  4295. var found = change["spans_" + doc.id];
  4296. if (!found) { return null }
  4297. var nw = [];
  4298. for (var i = 0; i < change.text.length; ++i)
  4299. { nw.push(removeClearedSpans(found[i])); }
  4300. return nw
  4301. }
  4302. // Used for un/re-doing changes from the history. Combines the
  4303. // result of computing the existing spans with the set of spans that
  4304. // existed in the history (so that deleting around a span and then
  4305. // undoing brings back the span).
  4306. function mergeOldSpans(doc, change) {
  4307. var old = getOldSpans(doc, change);
  4308. var stretched = stretchSpansOverChange(doc, change);
  4309. if (!old) { return stretched }
  4310. if (!stretched) { return old }
  4311. for (var i = 0; i < old.length; ++i) {
  4312. var oldCur = old[i], stretchCur = stretched[i];
  4313. if (oldCur && stretchCur) {
  4314. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4315. var span = stretchCur[j];
  4316. for (var k = 0; k < oldCur.length; ++k)
  4317. { if (oldCur[k].marker == span.marker) { continue spans } }
  4318. oldCur.push(span);
  4319. }
  4320. } else if (stretchCur) {
  4321. old[i] = stretchCur;
  4322. }
  4323. }
  4324. return old
  4325. }
  4326. // Used both to provide a JSON-safe object in .getHistory, and, when
  4327. // detaching a document, to split the history in two
  4328. function copyHistoryArray(events, newGroup, instantiateSel) {
  4329. var copy = [];
  4330. for (var i = 0; i < events.length; ++i) {
  4331. var event = events[i];
  4332. if (event.ranges) {
  4333. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4334. continue
  4335. }
  4336. var changes = event.changes, newChanges = [];
  4337. copy.push({changes: newChanges});
  4338. for (var j = 0; j < changes.length; ++j) {
  4339. var change = changes[j], m = (void 0);
  4340. newChanges.push({from: change.from, to: change.to, text: change.text});
  4341. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4342. if (indexOf(newGroup, Number(m[1])) > -1) {
  4343. lst(newChanges)[prop] = change[prop];
  4344. delete change[prop];
  4345. }
  4346. } } }
  4347. }
  4348. }
  4349. return copy
  4350. }
  4351. // The 'scroll' parameter given to many of these indicated whether
  4352. // the new cursor position should be scrolled into view after
  4353. // modifying the selection.
  4354. // If shift is held or the extend flag is set, extends a range to
  4355. // include a given position (and optionally a second position).
  4356. // Otherwise, simply returns the range between the given positions.
  4357. // Used for cursor motion and such.
  4358. function extendRange(doc, range, head, other) {
  4359. if (doc.cm && doc.cm.display.shift || doc.extend) {
  4360. var anchor = range.anchor;
  4361. if (other) {
  4362. var posBefore = cmp(head, anchor) < 0;
  4363. if (posBefore != (cmp(other, anchor) < 0)) {
  4364. anchor = head;
  4365. head = other;
  4366. } else if (posBefore != (cmp(head, other) < 0)) {
  4367. head = other;
  4368. }
  4369. }
  4370. return new Range(anchor, head)
  4371. } else {
  4372. return new Range(other || head, head)
  4373. }
  4374. }
  4375. // Extend the primary selection range, discard the rest.
  4376. function extendSelection(doc, head, other, options) {
  4377. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  4378. }
  4379. // Extend all selections (pos is an array of selections with length
  4380. // equal the number of selections)
  4381. function extendSelections(doc, heads, options) {
  4382. var out = [];
  4383. for (var i = 0; i < doc.sel.ranges.length; i++)
  4384. { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); }
  4385. var newSel = normalizeSelection(out, doc.sel.primIndex);
  4386. setSelection(doc, newSel, options);
  4387. }
  4388. // Updates a single range in the selection.
  4389. function replaceOneSelection(doc, i, range, options) {
  4390. var ranges = doc.sel.ranges.slice(0);
  4391. ranges[i] = range;
  4392. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  4393. }
  4394. // Reset the selection to a single range.
  4395. function setSimpleSelection(doc, anchor, head, options) {
  4396. setSelection(doc, simpleSelection(anchor, head), options);
  4397. }
  4398. // Give beforeSelectionChange handlers a change to influence a
  4399. // selection update.
  4400. function filterSelectionChange(doc, sel, options) {
  4401. var obj = {
  4402. ranges: sel.ranges,
  4403. update: function(ranges) {
  4404. var this$1 = this;
  4405. this.ranges = [];
  4406. for (var i = 0; i < ranges.length; i++)
  4407. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4408. clipPos(doc, ranges[i].head)); }
  4409. },
  4410. origin: options && options.origin
  4411. };
  4412. signal(doc, "beforeSelectionChange", doc, obj);
  4413. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4414. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4415. else { return sel }
  4416. }
  4417. function setSelectionReplaceHistory(doc, sel, options) {
  4418. var done = doc.history.done, last = lst(done);
  4419. if (last && last.ranges) {
  4420. done[done.length - 1] = sel;
  4421. setSelectionNoUndo(doc, sel, options);
  4422. } else {
  4423. setSelection(doc, sel, options);
  4424. }
  4425. }
  4426. // Set a new selection.
  4427. function setSelection(doc, sel, options) {
  4428. setSelectionNoUndo(doc, sel, options);
  4429. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4430. }
  4431. function setSelectionNoUndo(doc, sel, options) {
  4432. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4433. { sel = filterSelectionChange(doc, sel, options); }
  4434. var bias = options && options.bias ||
  4435. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4436. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4437. if (!(options && options.scroll === false) && doc.cm)
  4438. { ensureCursorVisible(doc.cm); }
  4439. }
  4440. function setSelectionInner(doc, sel) {
  4441. if (sel.equals(doc.sel)) { return }
  4442. doc.sel = sel;
  4443. if (doc.cm) {
  4444. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  4445. signalCursorActivity(doc.cm);
  4446. }
  4447. signalLater(doc, "cursorActivity", doc);
  4448. }
  4449. // Verify that the selection does not partially select any atomic
  4450. // marked ranges.
  4451. function reCheckSelection(doc) {
  4452. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  4453. }
  4454. // Return a selection that does not partially select any atomic
  4455. // ranges.
  4456. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4457. var out;
  4458. for (var i = 0; i < sel.ranges.length; i++) {
  4459. var range = sel.ranges[i];
  4460. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4461. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4462. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4463. if (out || newAnchor != range.anchor || newHead != range.head) {
  4464. if (!out) { out = sel.ranges.slice(0, i); }
  4465. out[i] = new Range(newAnchor, newHead);
  4466. }
  4467. }
  4468. return out ? normalizeSelection(out, sel.primIndex) : sel
  4469. }
  4470. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4471. var line = getLine(doc, pos.line);
  4472. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4473. var sp = line.markedSpans[i], m = sp.marker;
  4474. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4475. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4476. if (mayClear) {
  4477. signal(m, "beforeCursorEnter");
  4478. if (m.explicitlyCleared) {
  4479. if (!line.markedSpans) { break }
  4480. else {--i; continue}
  4481. }
  4482. }
  4483. if (!m.atomic) { continue }
  4484. if (oldPos) {
  4485. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4486. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4487. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4488. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4489. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4490. }
  4491. var far = m.find(dir < 0 ? -1 : 1);
  4492. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4493. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4494. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4495. }
  4496. } }
  4497. return pos
  4498. }
  4499. // Ensure a given position is not inside an atomic range.
  4500. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4501. var dir = bias || 1;
  4502. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4503. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4504. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4505. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4506. if (!found) {
  4507. doc.cantEdit = true;
  4508. return Pos(doc.first, 0)
  4509. }
  4510. return found
  4511. }
  4512. function movePos(doc, pos, dir, line) {
  4513. if (dir < 0 && pos.ch == 0) {
  4514. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4515. else { return null }
  4516. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4517. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4518. else { return null }
  4519. } else {
  4520. return new Pos(pos.line, pos.ch + dir)
  4521. }
  4522. }
  4523. function selectAll(cm) {
  4524. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4525. }
  4526. // UPDATING
  4527. // Allow "beforeChange" event handlers to influence a change
  4528. function filterChange(doc, change, update) {
  4529. var obj = {
  4530. canceled: false,
  4531. from: change.from,
  4532. to: change.to,
  4533. text: change.text,
  4534. origin: change.origin,
  4535. cancel: function () { return obj.canceled = true; }
  4536. };
  4537. if (update) { obj.update = function (from, to, text, origin) {
  4538. if (from) { obj.from = clipPos(doc, from); }
  4539. if (to) { obj.to = clipPos(doc, to); }
  4540. if (text) { obj.text = text; }
  4541. if (origin !== undefined) { obj.origin = origin; }
  4542. }; }
  4543. signal(doc, "beforeChange", doc, obj);
  4544. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4545. if (obj.canceled) { return null }
  4546. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4547. }
  4548. // Apply a change to a document, and add it to the document's
  4549. // history, and propagating it to all linked documents.
  4550. function makeChange(doc, change, ignoreReadOnly) {
  4551. if (doc.cm) {
  4552. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4553. if (doc.cm.state.suppressEdits) { return }
  4554. }
  4555. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4556. change = filterChange(doc, change, true);
  4557. if (!change) { return }
  4558. }
  4559. // Possibly split or suppress the update based on the presence
  4560. // of read-only spans in its range.
  4561. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4562. if (split) {
  4563. for (var i = split.length - 1; i >= 0; --i)
  4564. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); }
  4565. } else {
  4566. makeChangeInner(doc, change);
  4567. }
  4568. }
  4569. function makeChangeInner(doc, change) {
  4570. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4571. var selAfter = computeSelAfterChange(doc, change);
  4572. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4573. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4574. var rebased = [];
  4575. linkedDocs(doc, function (doc, sharedHist) {
  4576. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4577. rebaseHist(doc.history, change);
  4578. rebased.push(doc.history);
  4579. }
  4580. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4581. });
  4582. }
  4583. // Revert a change stored in a document's history.
  4584. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4585. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4586. var hist = doc.history, event, selAfter = doc.sel;
  4587. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4588. // Verify that there is a useable event (so that ctrl-z won't
  4589. // needlessly clear selection events)
  4590. var i = 0;
  4591. for (; i < source.length; i++) {
  4592. event = source[i];
  4593. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4594. { break }
  4595. }
  4596. if (i == source.length) { return }
  4597. hist.lastOrigin = hist.lastSelOrigin = null;
  4598. for (;;) {
  4599. event = source.pop();
  4600. if (event.ranges) {
  4601. pushSelectionToHistory(event, dest);
  4602. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4603. setSelection(doc, event, {clearRedo: false});
  4604. return
  4605. }
  4606. selAfter = event;
  4607. }
  4608. else { break }
  4609. }
  4610. // Build up a reverse change object to add to the opposite history
  4611. // stack (redo when undoing, and vice versa).
  4612. var antiChanges = [];
  4613. pushSelectionToHistory(selAfter, dest);
  4614. dest.push({changes: antiChanges, generation: hist.generation});
  4615. hist.generation = event.generation || ++hist.maxGeneration;
  4616. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4617. var loop = function ( i ) {
  4618. var change = event.changes[i];
  4619. change.origin = type;
  4620. if (filter && !filterChange(doc, change, false)) {
  4621. source.length = 0;
  4622. return {}
  4623. }
  4624. antiChanges.push(historyChangeFromChange(doc, change));
  4625. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4626. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4627. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4628. var rebased = [];
  4629. // Propagate to the linked documents
  4630. linkedDocs(doc, function (doc, sharedHist) {
  4631. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4632. rebaseHist(doc.history, change);
  4633. rebased.push(doc.history);
  4634. }
  4635. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4636. });
  4637. };
  4638. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4639. var returned = loop( i$1 );
  4640. if ( returned ) return returned.v;
  4641. }
  4642. }
  4643. // Sub-views need their line numbers shifted when text is added
  4644. // above or below them in the parent document.
  4645. function shiftDoc(doc, distance) {
  4646. if (distance == 0) { return }
  4647. doc.first += distance;
  4648. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4649. Pos(range.anchor.line + distance, range.anchor.ch),
  4650. Pos(range.head.line + distance, range.head.ch)
  4651. ); }), doc.sel.primIndex);
  4652. if (doc.cm) {
  4653. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4654. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4655. { regLineChange(doc.cm, l, "gutter"); }
  4656. }
  4657. }
  4658. // More lower-level change function, handling only a single document
  4659. // (not linked ones).
  4660. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4661. if (doc.cm && !doc.cm.curOp)
  4662. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4663. if (change.to.line < doc.first) {
  4664. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4665. return
  4666. }
  4667. if (change.from.line > doc.lastLine()) { return }
  4668. // Clip the change to the size of this doc
  4669. if (change.from.line < doc.first) {
  4670. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4671. shiftDoc(doc, shift);
  4672. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4673. text: [lst(change.text)], origin: change.origin};
  4674. }
  4675. var last = doc.lastLine();
  4676. if (change.to.line > last) {
  4677. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4678. text: [change.text[0]], origin: change.origin};
  4679. }
  4680. change.removed = getBetween(doc, change.from, change.to);
  4681. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4682. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4683. else { updateDoc(doc, change, spans); }
  4684. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4685. }
  4686. // Handle the interaction of a change to a document with the editor
  4687. // that this document is part of.
  4688. function makeChangeSingleDocInEditor(cm, change, spans) {
  4689. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4690. var recomputeMaxLength = false, checkWidthStart = from.line;
  4691. if (!cm.options.lineWrapping) {
  4692. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4693. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4694. if (line == display.maxLine) {
  4695. recomputeMaxLength = true;
  4696. return true
  4697. }
  4698. });
  4699. }
  4700. if (doc.sel.contains(change.from, change.to) > -1)
  4701. { signalCursorActivity(cm); }
  4702. updateDoc(doc, change, spans, estimateHeight(cm));
  4703. if (!cm.options.lineWrapping) {
  4704. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4705. var len = lineLength(line);
  4706. if (len > display.maxLineLength) {
  4707. display.maxLine = line;
  4708. display.maxLineLength = len;
  4709. display.maxLineChanged = true;
  4710. recomputeMaxLength = false;
  4711. }
  4712. });
  4713. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4714. }
  4715. // Adjust frontier, schedule worker
  4716. doc.frontier = Math.min(doc.frontier, from.line);
  4717. startWorker(cm, 400);
  4718. var lendiff = change.text.length - (to.line - from.line) - 1;
  4719. // Remember that these lines changed, for updating the display
  4720. if (change.full)
  4721. { regChange(cm); }
  4722. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4723. { regLineChange(cm, from.line, "text"); }
  4724. else
  4725. { regChange(cm, from.line, to.line + 1, lendiff); }
  4726. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4727. if (changeHandler || changesHandler) {
  4728. var obj = {
  4729. from: from, to: to,
  4730. text: change.text,
  4731. removed: change.removed,
  4732. origin: change.origin
  4733. };
  4734. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4735. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4736. }
  4737. cm.display.selForContextMenu = null;
  4738. }
  4739. function replaceRange(doc, code, from, to, origin) {
  4740. if (!to) { to = from; }
  4741. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4742. if (typeof code == "string") { code = doc.splitLines(code); }
  4743. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4744. }
  4745. // Rebasing/resetting history to deal with externally-sourced changes
  4746. function rebaseHistSelSingle(pos, from, to, diff) {
  4747. if (to < pos.line) {
  4748. pos.line += diff;
  4749. } else if (from < pos.line) {
  4750. pos.line = from;
  4751. pos.ch = 0;
  4752. }
  4753. }
  4754. // Tries to rebase an array of history events given a change in the
  4755. // document. If the change touches the same lines as the event, the
  4756. // event, and everything 'behind' it, is discarded. If the change is
  4757. // before the event, the event's positions are updated. Uses a
  4758. // copy-on-write scheme for the positions, to avoid having to
  4759. // reallocate them all on every rebase, but also avoid problems with
  4760. // shared position objects being unsafely updated.
  4761. function rebaseHistArray(array, from, to, diff) {
  4762. for (var i = 0; i < array.length; ++i) {
  4763. var sub = array[i], ok = true;
  4764. if (sub.ranges) {
  4765. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4766. for (var j = 0; j < sub.ranges.length; j++) {
  4767. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4768. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4769. }
  4770. continue
  4771. }
  4772. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4773. var cur = sub.changes[j$1];
  4774. if (to < cur.from.line) {
  4775. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4776. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4777. } else if (from <= cur.to.line) {
  4778. ok = false;
  4779. break
  4780. }
  4781. }
  4782. if (!ok) {
  4783. array.splice(0, i + 1);
  4784. i = 0;
  4785. }
  4786. }
  4787. }
  4788. function rebaseHist(hist, change) {
  4789. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4790. rebaseHistArray(hist.done, from, to, diff);
  4791. rebaseHistArray(hist.undone, from, to, diff);
  4792. }
  4793. // Utility for applying a change to a line by handle or number,
  4794. // returning the number and optionally registering the line as
  4795. // changed.
  4796. function changeLine(doc, handle, changeType, op) {
  4797. var no = handle, line = handle;
  4798. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  4799. else { no = lineNo(handle); }
  4800. if (no == null) { return null }
  4801. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  4802. return line
  4803. }
  4804. // The document is represented as a BTree consisting of leaves, with
  4805. // chunk of lines in them, and branches, with up to ten leaves or
  4806. // other branch nodes below them. The top node is always a branch
  4807. // node, and is the document object itself (meaning it has
  4808. // additional methods and properties).
  4809. //
  4810. // All nodes have parent links. The tree is used both to go from
  4811. // line numbers to line objects, and to go from objects to numbers.
  4812. // It also indexes by height, and is used to convert between height
  4813. // and line object, and to find the total height of the document.
  4814. //
  4815. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4816. var LeafChunk = function(lines) {
  4817. var this$1 = this;
  4818. this.lines = lines;
  4819. this.parent = null;
  4820. var height = 0;
  4821. for (var i = 0; i < lines.length; ++i) {
  4822. lines[i].parent = this$1;
  4823. height += lines[i].height;
  4824. }
  4825. this.height = height;
  4826. };
  4827. LeafChunk.prototype.chunkSize = function () { return this.lines.length };
  4828. // Remove the n lines at offset 'at'.
  4829. LeafChunk.prototype.removeInner = function (at, n) {
  4830. var this$1 = this;
  4831. for (var i = at, e = at + n; i < e; ++i) {
  4832. var line = this$1.lines[i];
  4833. this$1.height -= line.height;
  4834. cleanUpLine(line);
  4835. signalLater(line, "delete");
  4836. }
  4837. this.lines.splice(at, n);
  4838. };
  4839. // Helper used to collapse a small branch into a single leaf.
  4840. LeafChunk.prototype.collapse = function (lines) {
  4841. lines.push.apply(lines, this.lines);
  4842. };
  4843. // Insert the given array of lines at offset 'at', count them as
  4844. // having the given height.
  4845. LeafChunk.prototype.insertInner = function (at, lines, height) {
  4846. var this$1 = this;
  4847. this.height += height;
  4848. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  4849. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  4850. };
  4851. // Used to iterate over a part of the tree.
  4852. LeafChunk.prototype.iterN = function (at, n, op) {
  4853. var this$1 = this;
  4854. for (var e = at + n; at < e; ++at)
  4855. { if (op(this$1.lines[at])) { return true } }
  4856. };
  4857. var BranchChunk = function(children) {
  4858. var this$1 = this;
  4859. this.children = children;
  4860. var size = 0, height = 0;
  4861. for (var i = 0; i < children.length; ++i) {
  4862. var ch = children[i];
  4863. size += ch.chunkSize(); height += ch.height;
  4864. ch.parent = this$1;
  4865. }
  4866. this.size = size;
  4867. this.height = height;
  4868. this.parent = null;
  4869. };
  4870. BranchChunk.prototype.chunkSize = function () { return this.size };
  4871. BranchChunk.prototype.removeInner = function (at, n) {
  4872. var this$1 = this;
  4873. this.size -= n;
  4874. for (var i = 0; i < this.children.length; ++i) {
  4875. var child = this$1.children[i], sz = child.chunkSize();
  4876. if (at < sz) {
  4877. var rm = Math.min(n, sz - at), oldHeight = child.height;
  4878. child.removeInner(at, rm);
  4879. this$1.height -= oldHeight - child.height;
  4880. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  4881. if ((n -= rm) == 0) { break }
  4882. at = 0;
  4883. } else { at -= sz; }
  4884. }
  4885. // If the result is smaller than 25 lines, ensure that it is a
  4886. // single leaf node.
  4887. if (this.size - n < 25 &&
  4888. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  4889. var lines = [];
  4890. this.collapse(lines);
  4891. this.children = [new LeafChunk(lines)];
  4892. this.children[0].parent = this;
  4893. }
  4894. };
  4895. BranchChunk.prototype.collapse = function (lines) {
  4896. var this$1 = this;
  4897. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  4898. };
  4899. BranchChunk.prototype.insertInner = function (at, lines, height) {
  4900. var this$1 = this;
  4901. this.size += lines.length;
  4902. this.height += height;
  4903. for (var i = 0; i < this.children.length; ++i) {
  4904. var child = this$1.children[i], sz = child.chunkSize();
  4905. if (at <= sz) {
  4906. child.insertInner(at, lines, height);
  4907. if (child.lines && child.lines.length > 50) {
  4908. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  4909. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  4910. var remaining = child.lines.length % 25 + 25;
  4911. for (var pos = remaining; pos < child.lines.length;) {
  4912. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  4913. child.height -= leaf.height;
  4914. this$1.children.splice(++i, 0, leaf);
  4915. leaf.parent = this$1;
  4916. }
  4917. child.lines = child.lines.slice(0, remaining);
  4918. this$1.maybeSpill();
  4919. }
  4920. break
  4921. }
  4922. at -= sz;
  4923. }
  4924. };
  4925. // When a node has grown, check whether it should be split.
  4926. BranchChunk.prototype.maybeSpill = function () {
  4927. if (this.children.length <= 10) { return }
  4928. var me = this;
  4929. do {
  4930. var spilled = me.children.splice(me.children.length - 5, 5);
  4931. var sibling = new BranchChunk(spilled);
  4932. if (!me.parent) { // Become the parent node
  4933. var copy = new BranchChunk(me.children);
  4934. copy.parent = me;
  4935. me.children = [copy, sibling];
  4936. me = copy;
  4937. } else {
  4938. me.size -= sibling.size;
  4939. me.height -= sibling.height;
  4940. var myIndex = indexOf(me.parent.children, me);
  4941. me.parent.children.splice(myIndex + 1, 0, sibling);
  4942. }
  4943. sibling.parent = me.parent;
  4944. } while (me.children.length > 10)
  4945. me.parent.maybeSpill();
  4946. };
  4947. BranchChunk.prototype.iterN = function (at, n, op) {
  4948. var this$1 = this;
  4949. for (var i = 0; i < this.children.length; ++i) {
  4950. var child = this$1.children[i], sz = child.chunkSize();
  4951. if (at < sz) {
  4952. var used = Math.min(n, sz - at);
  4953. if (child.iterN(at, used, op)) { return true }
  4954. if ((n -= used) == 0) { break }
  4955. at = 0;
  4956. } else { at -= sz; }
  4957. }
  4958. };
  4959. // Line widgets are block elements displayed above or below a line.
  4960. var LineWidget = function(doc, node, options) {
  4961. var this$1 = this;
  4962. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  4963. { this$1[opt] = options[opt]; } } }
  4964. this.doc = doc;
  4965. this.node = node;
  4966. };
  4967. LineWidget.prototype.clear = function () {
  4968. var this$1 = this;
  4969. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  4970. if (no == null || !ws) { return }
  4971. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  4972. if (!ws.length) { line.widgets = null; }
  4973. var height = widgetHeight(this);
  4974. updateLineHeight(line, Math.max(0, line.height - height));
  4975. if (cm) {
  4976. runInOp(cm, function () {
  4977. adjustScrollWhenAboveVisible(cm, line, -height);
  4978. regLineChange(cm, no, "widget");
  4979. });
  4980. signalLater(cm, "lineWidgetCleared", cm, this, no);
  4981. }
  4982. };
  4983. LineWidget.prototype.changed = function () {
  4984. var this$1 = this;
  4985. var oldH = this.height, cm = this.doc.cm, line = this.line;
  4986. this.height = null;
  4987. var diff = widgetHeight(this) - oldH;
  4988. if (!diff) { return }
  4989. updateLineHeight(line, line.height + diff);
  4990. if (cm) {
  4991. runInOp(cm, function () {
  4992. cm.curOp.forceUpdate = true;
  4993. adjustScrollWhenAboveVisible(cm, line, diff);
  4994. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  4995. });
  4996. }
  4997. };
  4998. eventMixin(LineWidget);
  4999. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5000. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5001. { addToScrollPos(cm, null, diff); }
  5002. }
  5003. function addLineWidget(doc, handle, node, options) {
  5004. var widget = new LineWidget(doc, node, options);
  5005. var cm = doc.cm;
  5006. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5007. changeLine(doc, handle, "widget", function (line) {
  5008. var widgets = line.widgets || (line.widgets = []);
  5009. if (widget.insertAt == null) { widgets.push(widget); }
  5010. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  5011. widget.line = line;
  5012. if (cm && !lineIsHidden(doc, line)) {
  5013. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5014. updateLineHeight(line, line.height + widgetHeight(widget));
  5015. if (aboveVisible) { addToScrollPos(cm, null, widget.height); }
  5016. cm.curOp.forceUpdate = true;
  5017. }
  5018. return true
  5019. });
  5020. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
  5021. return widget
  5022. }
  5023. // TEXTMARKERS
  5024. // Created with markText and setBookmark methods. A TextMarker is a
  5025. // handle that can be used to clear or find a marked position in the
  5026. // document. Line objects hold arrays (markedSpans) containing
  5027. // {from, to, marker} object pointing to such marker objects, and
  5028. // indicating that such a marker is present on that line. Multiple
  5029. // lines may point to the same marker when it spans across lines.
  5030. // The spans will have null for their from/to properties when the
  5031. // marker continues beyond the start/end of the line. Markers have
  5032. // links back to the lines they currently touch.
  5033. // Collapsed markers have unique ids, in order to be able to order
  5034. // them, which is needed for uniquely determining an outer marker
  5035. // when they overlap (they may nest, but not partially overlap).
  5036. var nextMarkerId = 0;
  5037. var TextMarker = function(doc, type) {
  5038. this.lines = [];
  5039. this.type = type;
  5040. this.doc = doc;
  5041. this.id = ++nextMarkerId;
  5042. };
  5043. // Clear the marker.
  5044. TextMarker.prototype.clear = function () {
  5045. var this$1 = this;
  5046. if (this.explicitlyCleared) { return }
  5047. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5048. if (withOp) { startOperation(cm); }
  5049. if (hasHandler(this, "clear")) {
  5050. var found = this.find();
  5051. if (found) { signalLater(this, "clear", found.from, found.to); }
  5052. }
  5053. var min = null, max = null;
  5054. for (var i = 0; i < this.lines.length; ++i) {
  5055. var line = this$1.lines[i];
  5056. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5057. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5058. else if (cm) {
  5059. if (span.to != null) { max = lineNo(line); }
  5060. if (span.from != null) { min = lineNo(line); }
  5061. }
  5062. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5063. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5064. { updateLineHeight(line, textHeight(cm.display)); }
  5065. }
  5066. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5067. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  5068. if (len > cm.display.maxLineLength) {
  5069. cm.display.maxLine = visual;
  5070. cm.display.maxLineLength = len;
  5071. cm.display.maxLineChanged = true;
  5072. }
  5073. } }
  5074. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5075. this.lines.length = 0;
  5076. this.explicitlyCleared = true;
  5077. if (this.atomic && this.doc.cantEdit) {
  5078. this.doc.cantEdit = false;
  5079. if (cm) { reCheckSelection(cm.doc); }
  5080. }
  5081. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5082. if (withOp) { endOperation(cm); }
  5083. if (this.parent) { this.parent.clear(); }
  5084. };
  5085. // Find the position of the marker in the document. Returns a {from,
  5086. // to} object by default. Side can be passed to get a specific side
  5087. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5088. // Pos objects returned contain a line object, rather than a line
  5089. // number (used to prevent looking up the same line twice).
  5090. TextMarker.prototype.find = function (side, lineObj) {
  5091. var this$1 = this;
  5092. if (side == null && this.type == "bookmark") { side = 1; }
  5093. var from, to;
  5094. for (var i = 0; i < this.lines.length; ++i) {
  5095. var line = this$1.lines[i];
  5096. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5097. if (span.from != null) {
  5098. from = Pos(lineObj ? line : lineNo(line), span.from);
  5099. if (side == -1) { return from }
  5100. }
  5101. if (span.to != null) {
  5102. to = Pos(lineObj ? line : lineNo(line), span.to);
  5103. if (side == 1) { return to }
  5104. }
  5105. }
  5106. return from && {from: from, to: to}
  5107. };
  5108. // Signals that the marker's widget changed, and surrounding layout
  5109. // should be recomputed.
  5110. TextMarker.prototype.changed = function () {
  5111. var this$1 = this;
  5112. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5113. if (!pos || !cm) { return }
  5114. runInOp(cm, function () {
  5115. var line = pos.line, lineN = lineNo(pos.line);
  5116. var view = findViewForLine(cm, lineN);
  5117. if (view) {
  5118. clearLineMeasurementCacheFor(view);
  5119. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5120. }
  5121. cm.curOp.updateMaxLine = true;
  5122. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5123. var oldHeight = widget.height;
  5124. widget.height = null;
  5125. var dHeight = widgetHeight(widget) - oldHeight;
  5126. if (dHeight)
  5127. { updateLineHeight(line, line.height + dHeight); }
  5128. }
  5129. signalLater(cm, "markerChanged", cm, this$1);
  5130. });
  5131. };
  5132. TextMarker.prototype.attachLine = function (line) {
  5133. if (!this.lines.length && this.doc.cm) {
  5134. var op = this.doc.cm.curOp;
  5135. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5136. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5137. }
  5138. this.lines.push(line);
  5139. };
  5140. TextMarker.prototype.detachLine = function (line) {
  5141. this.lines.splice(indexOf(this.lines, line), 1);
  5142. if (!this.lines.length && this.doc.cm) {
  5143. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5144. }
  5145. };
  5146. eventMixin(TextMarker);
  5147. // Create a marker, wire it up to the right lines, and
  5148. function markText(doc, from, to, options, type) {
  5149. // Shared markers (across linked documents) are handled separately
  5150. // (markTextShared will call out to this again, once per
  5151. // document).
  5152. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5153. // Ensure we are in an operation.
  5154. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5155. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5156. if (options) { copyObj(options, marker, false); }
  5157. // Don't connect empty markers unless clearWhenEmpty is false
  5158. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5159. { return marker }
  5160. if (marker.replacedWith) {
  5161. // Showing up as a widget implies collapsed (widget replaces text)
  5162. marker.collapsed = true;
  5163. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5164. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5165. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5166. }
  5167. if (marker.collapsed) {
  5168. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5169. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5170. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5171. seeCollapsedSpans();
  5172. }
  5173. if (marker.addToHistory)
  5174. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5175. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5176. doc.iter(curLine, to.line + 1, function (line) {
  5177. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5178. { updateMaxLine = true; }
  5179. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5180. addMarkedSpan(line, new MarkedSpan(marker,
  5181. curLine == from.line ? from.ch : null,
  5182. curLine == to.line ? to.ch : null));
  5183. ++curLine;
  5184. });
  5185. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5186. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5187. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5188. }); }
  5189. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5190. if (marker.readOnly) {
  5191. seeReadOnlySpans();
  5192. if (doc.history.done.length || doc.history.undone.length)
  5193. { doc.clearHistory(); }
  5194. }
  5195. if (marker.collapsed) {
  5196. marker.id = ++nextMarkerId;
  5197. marker.atomic = true;
  5198. }
  5199. if (cm) {
  5200. // Sync editor state
  5201. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5202. if (marker.collapsed)
  5203. { regChange(cm, from.line, to.line + 1); }
  5204. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5205. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5206. if (marker.atomic) { reCheckSelection(cm.doc); }
  5207. signalLater(cm, "markerAdded", cm, marker);
  5208. }
  5209. return marker
  5210. }
  5211. // SHARED TEXTMARKERS
  5212. // A shared marker spans multiple linked documents. It is
  5213. // implemented as a meta-marker-object controlling multiple normal
  5214. // markers.
  5215. var SharedTextMarker = function(markers, primary) {
  5216. var this$1 = this;
  5217. this.markers = markers;
  5218. this.primary = primary;
  5219. for (var i = 0; i < markers.length; ++i)
  5220. { markers[i].parent = this$1; }
  5221. };
  5222. SharedTextMarker.prototype.clear = function () {
  5223. var this$1 = this;
  5224. if (this.explicitlyCleared) { return }
  5225. this.explicitlyCleared = true;
  5226. for (var i = 0; i < this.markers.length; ++i)
  5227. { this$1.markers[i].clear(); }
  5228. signalLater(this, "clear");
  5229. };
  5230. SharedTextMarker.prototype.find = function (side, lineObj) {
  5231. return this.primary.find(side, lineObj)
  5232. };
  5233. eventMixin(SharedTextMarker);
  5234. function markTextShared(doc, from, to, options, type) {
  5235. options = copyObj(options);
  5236. options.shared = false;
  5237. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5238. var widget = options.widgetNode;
  5239. linkedDocs(doc, function (doc) {
  5240. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5241. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5242. for (var i = 0; i < doc.linked.length; ++i)
  5243. { if (doc.linked[i].isParent) { return } }
  5244. primary = lst(markers);
  5245. });
  5246. return new SharedTextMarker(markers, primary)
  5247. }
  5248. function findSharedMarkers(doc) {
  5249. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5250. }
  5251. function copySharedMarkers(doc, markers) {
  5252. for (var i = 0; i < markers.length; i++) {
  5253. var marker = markers[i], pos = marker.find();
  5254. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5255. if (cmp(mFrom, mTo)) {
  5256. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5257. marker.markers.push(subMark);
  5258. subMark.parent = marker;
  5259. }
  5260. }
  5261. }
  5262. function detachSharedMarkers(markers) {
  5263. var loop = function ( i ) {
  5264. var marker = markers[i], linked = [marker.primary.doc];
  5265. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5266. for (var j = 0; j < marker.markers.length; j++) {
  5267. var subMarker = marker.markers[j];
  5268. if (indexOf(linked, subMarker.doc) == -1) {
  5269. subMarker.parent = null;
  5270. marker.markers.splice(j--, 1);
  5271. }
  5272. }
  5273. };
  5274. for (var i = 0; i < markers.length; i++) loop( i );
  5275. }
  5276. var nextDocId = 0;
  5277. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5278. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5279. if (firstLine == null) { firstLine = 0; }
  5280. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5281. this.first = firstLine;
  5282. this.scrollTop = this.scrollLeft = 0;
  5283. this.cantEdit = false;
  5284. this.cleanGeneration = 1;
  5285. this.frontier = firstLine;
  5286. var start = Pos(firstLine, 0);
  5287. this.sel = simpleSelection(start);
  5288. this.history = new History(null);
  5289. this.id = ++nextDocId;
  5290. this.modeOption = mode;
  5291. this.lineSep = lineSep;
  5292. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5293. this.extend = false;
  5294. if (typeof text == "string") { text = this.splitLines(text); }
  5295. updateDoc(this, {from: start, to: start, text: text});
  5296. setSelection(this, simpleSelection(start), sel_dontScroll);
  5297. };
  5298. Doc.prototype = createObj(BranchChunk.prototype, {
  5299. constructor: Doc,
  5300. // Iterate over the document. Supports two forms -- with only one
  5301. // argument, it calls that for each line in the document. With
  5302. // three, it iterates over the range given by the first two (with
  5303. // the second being non-inclusive).
  5304. iter: function(from, to, op) {
  5305. if (op) { this.iterN(from - this.first, to - from, op); }
  5306. else { this.iterN(this.first, this.first + this.size, from); }
  5307. },
  5308. // Non-public interface for adding and removing lines.
  5309. insert: function(at, lines) {
  5310. var height = 0;
  5311. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5312. this.insertInner(at - this.first, lines, height);
  5313. },
  5314. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5315. // From here, the methods are part of the public interface. Most
  5316. // are also available from CodeMirror (editor) instances.
  5317. getValue: function(lineSep) {
  5318. var lines = getLines(this, this.first, this.first + this.size);
  5319. if (lineSep === false) { return lines }
  5320. return lines.join(lineSep || this.lineSeparator())
  5321. },
  5322. setValue: docMethodOp(function(code) {
  5323. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5324. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5325. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5326. if (this.cm) { this.cm.scrollTo(0, 0); }
  5327. setSelection(this, simpleSelection(top), sel_dontScroll);
  5328. }),
  5329. replaceRange: function(code, from, to, origin) {
  5330. from = clipPos(this, from);
  5331. to = to ? clipPos(this, to) : from;
  5332. replaceRange(this, code, from, to, origin);
  5333. },
  5334. getRange: function(from, to, lineSep) {
  5335. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5336. if (lineSep === false) { return lines }
  5337. return lines.join(lineSep || this.lineSeparator())
  5338. },
  5339. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5340. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5341. getLineNumber: function(line) {return lineNo(line)},
  5342. getLineHandleVisualStart: function(line) {
  5343. if (typeof line == "number") { line = getLine(this, line); }
  5344. return visualLine(line)
  5345. },
  5346. lineCount: function() {return this.size},
  5347. firstLine: function() {return this.first},
  5348. lastLine: function() {return this.first + this.size - 1},
  5349. clipPos: function(pos) {return clipPos(this, pos)},
  5350. getCursor: function(start) {
  5351. var range$$1 = this.sel.primary(), pos;
  5352. if (start == null || start == "head") { pos = range$$1.head; }
  5353. else if (start == "anchor") { pos = range$$1.anchor; }
  5354. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  5355. else { pos = range$$1.from(); }
  5356. return pos
  5357. },
  5358. listSelections: function() { return this.sel.ranges },
  5359. somethingSelected: function() {return this.sel.somethingSelected()},
  5360. setCursor: docMethodOp(function(line, ch, options) {
  5361. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5362. }),
  5363. setSelection: docMethodOp(function(anchor, head, options) {
  5364. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5365. }),
  5366. extendSelection: docMethodOp(function(head, other, options) {
  5367. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5368. }),
  5369. extendSelections: docMethodOp(function(heads, options) {
  5370. extendSelections(this, clipPosArray(this, heads), options);
  5371. }),
  5372. extendSelectionsBy: docMethodOp(function(f, options) {
  5373. var heads = map(this.sel.ranges, f);
  5374. extendSelections(this, clipPosArray(this, heads), options);
  5375. }),
  5376. setSelections: docMethodOp(function(ranges, primary, options) {
  5377. var this$1 = this;
  5378. if (!ranges.length) { return }
  5379. var out = [];
  5380. for (var i = 0; i < ranges.length; i++)
  5381. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5382. clipPos(this$1, ranges[i].head)); }
  5383. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5384. setSelection(this, normalizeSelection(out, primary), options);
  5385. }),
  5386. addSelection: docMethodOp(function(anchor, head, options) {
  5387. var ranges = this.sel.ranges.slice(0);
  5388. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5389. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  5390. }),
  5391. getSelection: function(lineSep) {
  5392. var this$1 = this;
  5393. var ranges = this.sel.ranges, lines;
  5394. for (var i = 0; i < ranges.length; i++) {
  5395. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5396. lines = lines ? lines.concat(sel) : sel;
  5397. }
  5398. if (lineSep === false) { return lines }
  5399. else { return lines.join(lineSep || this.lineSeparator()) }
  5400. },
  5401. getSelections: function(lineSep) {
  5402. var this$1 = this;
  5403. var parts = [], ranges = this.sel.ranges;
  5404. for (var i = 0; i < ranges.length; i++) {
  5405. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5406. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  5407. parts[i] = sel;
  5408. }
  5409. return parts
  5410. },
  5411. replaceSelection: function(code, collapse, origin) {
  5412. var dup = [];
  5413. for (var i = 0; i < this.sel.ranges.length; i++)
  5414. { dup[i] = code; }
  5415. this.replaceSelections(dup, collapse, origin || "+input");
  5416. },
  5417. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5418. var this$1 = this;
  5419. var changes = [], sel = this.sel;
  5420. for (var i = 0; i < sel.ranges.length; i++) {
  5421. var range$$1 = sel.ranges[i];
  5422. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  5423. }
  5424. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5425. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5426. { makeChange(this$1, changes[i$1]); }
  5427. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5428. else if (this.cm) { ensureCursorVisible(this.cm); }
  5429. }),
  5430. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5431. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5432. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5433. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5434. setExtending: function(val) {this.extend = val;},
  5435. getExtending: function() {return this.extend},
  5436. historySize: function() {
  5437. var hist = this.history, done = 0, undone = 0;
  5438. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5439. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5440. return {undo: done, redo: undone}
  5441. },
  5442. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  5443. markClean: function() {
  5444. this.cleanGeneration = this.changeGeneration(true);
  5445. },
  5446. changeGeneration: function(forceSplit) {
  5447. if (forceSplit)
  5448. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5449. return this.history.generation
  5450. },
  5451. isClean: function (gen) {
  5452. return this.history.generation == (gen || this.cleanGeneration)
  5453. },
  5454. getHistory: function() {
  5455. return {done: copyHistoryArray(this.history.done),
  5456. undone: copyHistoryArray(this.history.undone)}
  5457. },
  5458. setHistory: function(histData) {
  5459. var hist = this.history = new History(this.history.maxGeneration);
  5460. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5461. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5462. },
  5463. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5464. return changeLine(this, line, "gutter", function (line) {
  5465. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5466. markers[gutterID] = value;
  5467. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5468. return true
  5469. })
  5470. }),
  5471. clearGutter: docMethodOp(function(gutterID) {
  5472. var this$1 = this;
  5473. this.iter(function (line) {
  5474. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5475. changeLine(this$1, line, "gutter", function () {
  5476. line.gutterMarkers[gutterID] = null;
  5477. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5478. return true
  5479. });
  5480. }
  5481. });
  5482. }),
  5483. lineInfo: function(line) {
  5484. var n;
  5485. if (typeof line == "number") {
  5486. if (!isLine(this, line)) { return null }
  5487. n = line;
  5488. line = getLine(this, line);
  5489. if (!line) { return null }
  5490. } else {
  5491. n = lineNo(line);
  5492. if (n == null) { return null }
  5493. }
  5494. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5495. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5496. widgets: line.widgets}
  5497. },
  5498. addLineClass: docMethodOp(function(handle, where, cls) {
  5499. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5500. var prop = where == "text" ? "textClass"
  5501. : where == "background" ? "bgClass"
  5502. : where == "gutter" ? "gutterClass" : "wrapClass";
  5503. if (!line[prop]) { line[prop] = cls; }
  5504. else if (classTest(cls).test(line[prop])) { return false }
  5505. else { line[prop] += " " + cls; }
  5506. return true
  5507. })
  5508. }),
  5509. removeLineClass: docMethodOp(function(handle, where, cls) {
  5510. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5511. var prop = where == "text" ? "textClass"
  5512. : where == "background" ? "bgClass"
  5513. : where == "gutter" ? "gutterClass" : "wrapClass";
  5514. var cur = line[prop];
  5515. if (!cur) { return false }
  5516. else if (cls == null) { line[prop] = null; }
  5517. else {
  5518. var found = cur.match(classTest(cls));
  5519. if (!found) { return false }
  5520. var end = found.index + found[0].length;
  5521. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5522. }
  5523. return true
  5524. })
  5525. }),
  5526. addLineWidget: docMethodOp(function(handle, node, options) {
  5527. return addLineWidget(this, handle, node, options)
  5528. }),
  5529. removeLineWidget: function(widget) { widget.clear(); },
  5530. markText: function(from, to, options) {
  5531. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5532. },
  5533. setBookmark: function(pos, options) {
  5534. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5535. insertLeft: options && options.insertLeft,
  5536. clearWhenEmpty: false, shared: options && options.shared,
  5537. handleMouseEvents: options && options.handleMouseEvents};
  5538. pos = clipPos(this, pos);
  5539. return markText(this, pos, pos, realOpts, "bookmark")
  5540. },
  5541. findMarksAt: function(pos) {
  5542. pos = clipPos(this, pos);
  5543. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5544. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5545. var span = spans[i];
  5546. if ((span.from == null || span.from <= pos.ch) &&
  5547. (span.to == null || span.to >= pos.ch))
  5548. { markers.push(span.marker.parent || span.marker); }
  5549. } }
  5550. return markers
  5551. },
  5552. findMarks: function(from, to, filter) {
  5553. from = clipPos(this, from); to = clipPos(this, to);
  5554. var found = [], lineNo$$1 = from.line;
  5555. this.iter(from.line, to.line + 1, function (line) {
  5556. var spans = line.markedSpans;
  5557. if (spans) { for (var i = 0; i < spans.length; i++) {
  5558. var span = spans[i];
  5559. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  5560. span.from == null && lineNo$$1 != from.line ||
  5561. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  5562. (!filter || filter(span.marker)))
  5563. { found.push(span.marker.parent || span.marker); }
  5564. } }
  5565. ++lineNo$$1;
  5566. });
  5567. return found
  5568. },
  5569. getAllMarks: function() {
  5570. var markers = [];
  5571. this.iter(function (line) {
  5572. var sps = line.markedSpans;
  5573. if (sps) { for (var i = 0; i < sps.length; ++i)
  5574. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5575. });
  5576. return markers
  5577. },
  5578. posFromIndex: function(off) {
  5579. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  5580. this.iter(function (line) {
  5581. var sz = line.text.length + sepSize;
  5582. if (sz > off) { ch = off; return true }
  5583. off -= sz;
  5584. ++lineNo$$1;
  5585. });
  5586. return clipPos(this, Pos(lineNo$$1, ch))
  5587. },
  5588. indexFromPos: function (coords) {
  5589. coords = clipPos(this, coords);
  5590. var index = coords.ch;
  5591. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5592. var sepSize = this.lineSeparator().length;
  5593. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5594. index += line.text.length + sepSize;
  5595. });
  5596. return index
  5597. },
  5598. copy: function(copyHistory) {
  5599. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5600. this.modeOption, this.first, this.lineSep, this.direction);
  5601. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5602. doc.sel = this.sel;
  5603. doc.extend = false;
  5604. if (copyHistory) {
  5605. doc.history.undoDepth = this.history.undoDepth;
  5606. doc.setHistory(this.getHistory());
  5607. }
  5608. return doc
  5609. },
  5610. linkedDoc: function(options) {
  5611. if (!options) { options = {}; }
  5612. var from = this.first, to = this.first + this.size;
  5613. if (options.from != null && options.from > from) { from = options.from; }
  5614. if (options.to != null && options.to < to) { to = options.to; }
  5615. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5616. if (options.sharedHist) { copy.history = this.history
  5617. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5618. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5619. copySharedMarkers(copy, findSharedMarkers(this));
  5620. return copy
  5621. },
  5622. unlinkDoc: function(other) {
  5623. var this$1 = this;
  5624. if (other instanceof CodeMirror$1) { other = other.doc; }
  5625. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5626. var link = this$1.linked[i];
  5627. if (link.doc != other) { continue }
  5628. this$1.linked.splice(i, 1);
  5629. other.unlinkDoc(this$1);
  5630. detachSharedMarkers(findSharedMarkers(this$1));
  5631. break
  5632. } }
  5633. // If the histories were shared, split them again
  5634. if (other.history == this.history) {
  5635. var splitIds = [other.id];
  5636. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5637. other.history = new History(null);
  5638. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5639. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5640. }
  5641. },
  5642. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5643. getMode: function() {return this.mode},
  5644. getEditor: function() {return this.cm},
  5645. splitLines: function(str) {
  5646. if (this.lineSep) { return str.split(this.lineSep) }
  5647. return splitLinesAuto(str)
  5648. },
  5649. lineSeparator: function() { return this.lineSep || "\n" },
  5650. setDirection: docMethodOp(function (dir) {
  5651. if (dir != "rtl") { dir = "ltr"; }
  5652. if (dir == this.direction) { return }
  5653. this.direction = dir;
  5654. this.iter(function (line) { return line.order = null; });
  5655. if (this.cm) { directionChanged(this.cm); }
  5656. })
  5657. });
  5658. // Public alias.
  5659. Doc.prototype.eachLine = Doc.prototype.iter;
  5660. // Kludge to work around strange IE behavior where it'll sometimes
  5661. // re-fire a series of drag-related events right after the drop (#1551)
  5662. var lastDrop = 0;
  5663. function onDrop(e) {
  5664. var cm = this;
  5665. clearDragCursor(cm);
  5666. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5667. { return }
  5668. e_preventDefault(e);
  5669. if (ie) { lastDrop = +new Date; }
  5670. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5671. if (!pos || cm.isReadOnly()) { return }
  5672. // Might be a file drop, in which case we simply extract the text
  5673. // and insert it.
  5674. if (files && files.length && window.FileReader && window.File) {
  5675. var n = files.length, text = Array(n), read = 0;
  5676. var loadFile = function (file, i) {
  5677. if (cm.options.allowDropFileTypes &&
  5678. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5679. { return }
  5680. var reader = new FileReader;
  5681. reader.onload = operation(cm, function () {
  5682. var content = reader.result;
  5683. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  5684. text[i] = content;
  5685. if (++read == n) {
  5686. pos = clipPos(cm.doc, pos);
  5687. var change = {from: pos, to: pos,
  5688. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5689. origin: "paste"};
  5690. makeChange(cm.doc, change);
  5691. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5692. }
  5693. });
  5694. reader.readAsText(file);
  5695. };
  5696. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  5697. } else { // Normal drop
  5698. // Don't do a replace if the drop happened inside of the selected text.
  5699. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5700. cm.state.draggingText(e);
  5701. // Ensure the editor is re-focused
  5702. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5703. return
  5704. }
  5705. try {
  5706. var text$1 = e.dataTransfer.getData("Text");
  5707. if (text$1) {
  5708. var selected;
  5709. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5710. { selected = cm.listSelections(); }
  5711. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5712. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5713. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5714. cm.replaceSelection(text$1, "around", "paste");
  5715. cm.display.input.focus();
  5716. }
  5717. }
  5718. catch(e){}
  5719. }
  5720. }
  5721. function onDragStart(cm, e) {
  5722. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5723. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5724. e.dataTransfer.setData("Text", cm.getSelection());
  5725. e.dataTransfer.effectAllowed = "copyMove";
  5726. // Use dummy image instead of default browsers image.
  5727. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5728. if (e.dataTransfer.setDragImage && !safari) {
  5729. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5730. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5731. if (presto) {
  5732. img.width = img.height = 1;
  5733. cm.display.wrapper.appendChild(img);
  5734. // Force a relayout, or Opera won't use our image for some obscure reason
  5735. img._top = img.offsetTop;
  5736. }
  5737. e.dataTransfer.setDragImage(img, 0, 0);
  5738. if (presto) { img.parentNode.removeChild(img); }
  5739. }
  5740. }
  5741. function onDragOver(cm, e) {
  5742. var pos = posFromMouse(cm, e);
  5743. if (!pos) { return }
  5744. var frag = document.createDocumentFragment();
  5745. drawSelectionCursor(cm, pos, frag);
  5746. if (!cm.display.dragCursor) {
  5747. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5748. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5749. }
  5750. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5751. }
  5752. function clearDragCursor(cm) {
  5753. if (cm.display.dragCursor) {
  5754. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5755. cm.display.dragCursor = null;
  5756. }
  5757. }
  5758. // These must be handled carefully, because naively registering a
  5759. // handler for each editor will cause the editors to never be
  5760. // garbage collected.
  5761. function forEachCodeMirror(f) {
  5762. if (!document.body.getElementsByClassName) { return }
  5763. var byClass = document.body.getElementsByClassName("CodeMirror");
  5764. for (var i = 0; i < byClass.length; i++) {
  5765. var cm = byClass[i].CodeMirror;
  5766. if (cm) { f(cm); }
  5767. }
  5768. }
  5769. var globalsRegistered = false;
  5770. function ensureGlobalHandlers() {
  5771. if (globalsRegistered) { return }
  5772. registerGlobalHandlers();
  5773. globalsRegistered = true;
  5774. }
  5775. function registerGlobalHandlers() {
  5776. // When the window resizes, we need to refresh active editors.
  5777. var resizeTimer;
  5778. on(window, "resize", function () {
  5779. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5780. resizeTimer = null;
  5781. forEachCodeMirror(onResize);
  5782. }, 100); }
  5783. });
  5784. // When the window loses focus, we want to show the editor as blurred
  5785. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  5786. }
  5787. // Called when the window resizes
  5788. function onResize(cm) {
  5789. var d = cm.display;
  5790. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5791. { return }
  5792. // Might be a text scaling operation, clear size caches.
  5793. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5794. d.scrollbarsClipped = false;
  5795. cm.setSize();
  5796. }
  5797. var keyNames = {
  5798. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5799. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5800. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5801. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5802. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5803. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5804. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5805. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5806. };
  5807. // Number keys
  5808. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  5809. // Alphabetic keys
  5810. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  5811. // Function keys
  5812. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  5813. var keyMap = {};
  5814. keyMap.basic = {
  5815. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5816. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5817. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5818. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5819. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5820. "Esc": "singleSelection"
  5821. };
  5822. // Note that the save and find-related commands aren't defined by
  5823. // default. User code or addons can define them. Unknown commands
  5824. // are simply ignored.
  5825. keyMap.pcDefault = {
  5826. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5827. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5828. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5829. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5830. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5831. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5832. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5833. fallthrough: "basic"
  5834. };
  5835. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5836. keyMap.emacsy = {
  5837. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5838. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5839. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5840. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5841. "Ctrl-O": "openLine"
  5842. };
  5843. keyMap.macDefault = {
  5844. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5845. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5846. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5847. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5848. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5849. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5850. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5851. fallthrough: ["basic", "emacsy"]
  5852. };
  5853. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5854. // KEYMAP DISPATCH
  5855. function normalizeKeyName(name) {
  5856. var parts = name.split(/-(?!$)/);
  5857. name = parts[parts.length - 1];
  5858. var alt, ctrl, shift, cmd;
  5859. for (var i = 0; i < parts.length - 1; i++) {
  5860. var mod = parts[i];
  5861. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  5862. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  5863. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  5864. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  5865. else { throw new Error("Unrecognized modifier name: " + mod) }
  5866. }
  5867. if (alt) { name = "Alt-" + name; }
  5868. if (ctrl) { name = "Ctrl-" + name; }
  5869. if (cmd) { name = "Cmd-" + name; }
  5870. if (shift) { name = "Shift-" + name; }
  5871. return name
  5872. }
  5873. // This is a kludge to keep keymaps mostly working as raw objects
  5874. // (backwards compatibility) while at the same time support features
  5875. // like normalization and multi-stroke key bindings. It compiles a
  5876. // new normalized keymap, and then updates the old object to reflect
  5877. // this.
  5878. function normalizeKeyMap(keymap) {
  5879. var copy = {};
  5880. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  5881. var value = keymap[keyname];
  5882. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  5883. if (value == "...") { delete keymap[keyname]; continue }
  5884. var keys = map(keyname.split(" "), normalizeKeyName);
  5885. for (var i = 0; i < keys.length; i++) {
  5886. var val = (void 0), name = (void 0);
  5887. if (i == keys.length - 1) {
  5888. name = keys.join(" ");
  5889. val = value;
  5890. } else {
  5891. name = keys.slice(0, i + 1).join(" ");
  5892. val = "...";
  5893. }
  5894. var prev = copy[name];
  5895. if (!prev) { copy[name] = val; }
  5896. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  5897. }
  5898. delete keymap[keyname];
  5899. } }
  5900. for (var prop in copy) { keymap[prop] = copy[prop]; }
  5901. return keymap
  5902. }
  5903. function lookupKey(key, map$$1, handle, context) {
  5904. map$$1 = getKeyMap(map$$1);
  5905. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  5906. if (found === false) { return "nothing" }
  5907. if (found === "...") { return "multi" }
  5908. if (found != null && handle(found)) { return "handled" }
  5909. if (map$$1.fallthrough) {
  5910. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  5911. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  5912. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  5913. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  5914. if (result) { return result }
  5915. }
  5916. }
  5917. }
  5918. // Modifier key presses don't count as 'real' key presses for the
  5919. // purpose of keymap fallthrough.
  5920. function isModifierKey(value) {
  5921. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5922. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  5923. }
  5924. // Look up the name of a key as indicated by an event object.
  5925. function keyName(event, noShift) {
  5926. if (presto && event.keyCode == 34 && event["char"]) { return false }
  5927. var base = keyNames[event.keyCode], name = base;
  5928. if (name == null || event.altGraphKey) { return false }
  5929. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  5930. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  5931. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  5932. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  5933. return name
  5934. }
  5935. function getKeyMap(val) {
  5936. return typeof val == "string" ? keyMap[val] : val
  5937. }
  5938. // Helper for deleting text near the selection(s), used to implement
  5939. // backspace, delete, and similar functionality.
  5940. function deleteNearSelection(cm, compute) {
  5941. var ranges = cm.doc.sel.ranges, kill = [];
  5942. // Build up a set of ranges to kill first, merging overlapping
  5943. // ranges.
  5944. for (var i = 0; i < ranges.length; i++) {
  5945. var toKill = compute(ranges[i]);
  5946. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  5947. var replaced = kill.pop();
  5948. if (cmp(replaced.from, toKill.from) < 0) {
  5949. toKill.from = replaced.from;
  5950. break
  5951. }
  5952. }
  5953. kill.push(toKill);
  5954. }
  5955. // Next, remove those actual ranges.
  5956. runInOp(cm, function () {
  5957. for (var i = kill.length - 1; i >= 0; i--)
  5958. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  5959. ensureCursorVisible(cm);
  5960. });
  5961. }
  5962. // Commands are parameter-less actions that can be performed on an
  5963. // editor, mostly used for keybindings.
  5964. var commands = {
  5965. selectAll: selectAll,
  5966. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  5967. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  5968. if (range.empty()) {
  5969. var len = getLine(cm.doc, range.head.line).text.length;
  5970. if (range.head.ch == len && range.head.line < cm.lastLine())
  5971. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  5972. else
  5973. { return {from: range.head, to: Pos(range.head.line, len)} }
  5974. } else {
  5975. return {from: range.from(), to: range.to()}
  5976. }
  5977. }); },
  5978. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5979. from: Pos(range.from().line, 0),
  5980. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  5981. }); }); },
  5982. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5983. from: Pos(range.from().line, 0), to: range.from()
  5984. }); }); },
  5985. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  5986. var top = cm.charCoords(range.head, "div").top + 5;
  5987. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  5988. return {from: leftPos, to: range.from()}
  5989. }); },
  5990. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  5991. var top = cm.charCoords(range.head, "div").top + 5;
  5992. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5993. return {from: range.from(), to: rightPos }
  5994. }); },
  5995. undo: function (cm) { return cm.undo(); },
  5996. redo: function (cm) { return cm.redo(); },
  5997. undoSelection: function (cm) { return cm.undoSelection(); },
  5998. redoSelection: function (cm) { return cm.redoSelection(); },
  5999. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6000. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6001. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6002. {origin: "+move", bias: 1}
  6003. ); },
  6004. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6005. {origin: "+move", bias: 1}
  6006. ); },
  6007. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6008. {origin: "+move", bias: -1}
  6009. ); },
  6010. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6011. var top = cm.charCoords(range.head, "div").top + 5;
  6012. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6013. }, sel_move); },
  6014. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6015. var top = cm.charCoords(range.head, "div").top + 5;
  6016. return cm.coordsChar({left: 0, top: top}, "div")
  6017. }, sel_move); },
  6018. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6019. var top = cm.charCoords(range.head, "div").top + 5;
  6020. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6021. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6022. return pos
  6023. }, sel_move); },
  6024. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6025. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6026. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6027. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6028. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6029. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6030. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6031. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6032. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6033. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6034. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6035. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6036. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6037. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6038. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6039. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6040. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6041. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6042. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6043. indentMore: function (cm) { return cm.indentSelection("add"); },
  6044. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6045. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6046. insertSoftTab: function (cm) {
  6047. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6048. for (var i = 0; i < ranges.length; i++) {
  6049. var pos = ranges[i].from();
  6050. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6051. spaces.push(spaceStr(tabSize - col % tabSize));
  6052. }
  6053. cm.replaceSelections(spaces);
  6054. },
  6055. defaultTab: function (cm) {
  6056. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6057. else { cm.execCommand("insertTab"); }
  6058. },
  6059. // Swap the two chars left and right of each selection's head.
  6060. // Move cursor behind the two swapped characters afterwards.
  6061. //
  6062. // Doesn't consider line feeds a character.
  6063. // Doesn't scan more than one line above to find a character.
  6064. // Doesn't do anything on an empty line.
  6065. // Doesn't do anything with non-empty selections.
  6066. transposeChars: function (cm) { return runInOp(cm, function () {
  6067. var ranges = cm.listSelections(), newSel = [];
  6068. for (var i = 0; i < ranges.length; i++) {
  6069. if (!ranges[i].empty()) { continue }
  6070. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6071. if (line) {
  6072. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6073. if (cur.ch > 0) {
  6074. cur = new Pos(cur.line, cur.ch + 1);
  6075. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6076. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6077. } else if (cur.line > cm.doc.first) {
  6078. var prev = getLine(cm.doc, cur.line - 1).text;
  6079. if (prev) {
  6080. cur = new Pos(cur.line, 1);
  6081. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6082. prev.charAt(prev.length - 1),
  6083. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6084. }
  6085. }
  6086. }
  6087. newSel.push(new Range(cur, cur));
  6088. }
  6089. cm.setSelections(newSel);
  6090. }); },
  6091. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6092. var sels = cm.listSelections();
  6093. for (var i = sels.length - 1; i >= 0; i--)
  6094. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6095. sels = cm.listSelections();
  6096. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6097. { cm.indentLine(sels[i$1].from().line, null, true); }
  6098. ensureCursorVisible(cm);
  6099. }); },
  6100. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6101. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6102. };
  6103. function lineStart(cm, lineN) {
  6104. var line = getLine(cm.doc, lineN);
  6105. var visual = visualLine(line);
  6106. if (visual != line) { lineN = lineNo(visual); }
  6107. return endOfLine(true, cm, visual, lineN, 1)
  6108. }
  6109. function lineEnd(cm, lineN) {
  6110. var line = getLine(cm.doc, lineN);
  6111. var visual = visualLineEnd(line);
  6112. if (visual != line) { lineN = lineNo(visual); }
  6113. return endOfLine(true, cm, line, lineN, -1)
  6114. }
  6115. function lineStartSmart(cm, pos) {
  6116. var start = lineStart(cm, pos.line);
  6117. var line = getLine(cm.doc, start.line);
  6118. var order = getOrder(line, cm.doc.direction);
  6119. if (!order || order[0].level == 0) {
  6120. var firstNonWS = Math.max(0, line.text.search(/\S/));
  6121. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6122. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6123. }
  6124. return start
  6125. }
  6126. // Run a handler that was bound to a key.
  6127. function doHandleBinding(cm, bound, dropShift) {
  6128. if (typeof bound == "string") {
  6129. bound = commands[bound];
  6130. if (!bound) { return false }
  6131. }
  6132. // Ensure previous input has been read, so that the handler sees a
  6133. // consistent view of the document
  6134. cm.display.input.ensurePolled();
  6135. var prevShift = cm.display.shift, done = false;
  6136. try {
  6137. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6138. if (dropShift) { cm.display.shift = false; }
  6139. done = bound(cm) != Pass;
  6140. } finally {
  6141. cm.display.shift = prevShift;
  6142. cm.state.suppressEdits = false;
  6143. }
  6144. return done
  6145. }
  6146. function lookupKeyForEditor(cm, name, handle) {
  6147. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6148. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6149. if (result) { return result }
  6150. }
  6151. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6152. || lookupKey(name, cm.options.keyMap, handle, cm)
  6153. }
  6154. var stopSeq = new Delayed;
  6155. function dispatchKey(cm, name, e, handle) {
  6156. var seq = cm.state.keySeq;
  6157. if (seq) {
  6158. if (isModifierKey(name)) { return "handled" }
  6159. stopSeq.set(50, function () {
  6160. if (cm.state.keySeq == seq) {
  6161. cm.state.keySeq = null;
  6162. cm.display.input.reset();
  6163. }
  6164. });
  6165. name = seq + " " + name;
  6166. }
  6167. var result = lookupKeyForEditor(cm, name, handle);
  6168. if (result == "multi")
  6169. { cm.state.keySeq = name; }
  6170. if (result == "handled")
  6171. { signalLater(cm, "keyHandled", cm, name, e); }
  6172. if (result == "handled" || result == "multi") {
  6173. e_preventDefault(e);
  6174. restartBlink(cm);
  6175. }
  6176. if (seq && !result && /\'$/.test(name)) {
  6177. e_preventDefault(e);
  6178. return true
  6179. }
  6180. return !!result
  6181. }
  6182. // Handle a key from the keydown event.
  6183. function handleKeyBinding(cm, e) {
  6184. var name = keyName(e, true);
  6185. if (!name) { return false }
  6186. if (e.shiftKey && !cm.state.keySeq) {
  6187. // First try to resolve full name (including 'Shift-'). Failing
  6188. // that, see if there is a cursor-motion command (starting with
  6189. // 'go') bound to the keyname without 'Shift-'.
  6190. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6191. || dispatchKey(cm, name, e, function (b) {
  6192. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6193. { return doHandleBinding(cm, b) }
  6194. })
  6195. } else {
  6196. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6197. }
  6198. }
  6199. // Handle a key from the keypress event
  6200. function handleCharBinding(cm, e, ch) {
  6201. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6202. }
  6203. var lastStoppedKey = null;
  6204. function onKeyDown(e) {
  6205. var cm = this;
  6206. cm.curOp.focus = activeElt();
  6207. if (signalDOMEvent(cm, e)) { return }
  6208. // IE does strange things with escape.
  6209. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6210. var code = e.keyCode;
  6211. cm.display.shift = code == 16 || e.shiftKey;
  6212. var handled = handleKeyBinding(cm, e);
  6213. if (presto) {
  6214. lastStoppedKey = handled ? code : null;
  6215. // Opera has no cut event... we try to at least catch the key combo
  6216. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6217. { cm.replaceSelection("", null, "cut"); }
  6218. }
  6219. // Turn mouse into crosshair when Alt is held on Mac.
  6220. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6221. { showCrossHair(cm); }
  6222. }
  6223. function showCrossHair(cm) {
  6224. var lineDiv = cm.display.lineDiv;
  6225. addClass(lineDiv, "CodeMirror-crosshair");
  6226. function up(e) {
  6227. if (e.keyCode == 18 || !e.altKey) {
  6228. rmClass(lineDiv, "CodeMirror-crosshair");
  6229. off(document, "keyup", up);
  6230. off(document, "mouseover", up);
  6231. }
  6232. }
  6233. on(document, "keyup", up);
  6234. on(document, "mouseover", up);
  6235. }
  6236. function onKeyUp(e) {
  6237. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6238. signalDOMEvent(this, e);
  6239. }
  6240. function onKeyPress(e) {
  6241. var cm = this;
  6242. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6243. var keyCode = e.keyCode, charCode = e.charCode;
  6244. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6245. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6246. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6247. // Some browsers fire keypress events for backspace
  6248. if (ch == "\x08") { return }
  6249. if (handleCharBinding(cm, e, ch)) { return }
  6250. cm.display.input.onKeyPress(e);
  6251. }
  6252. // A mouse down can be a single click, double click, triple click,
  6253. // start of selection drag, start of text drag, new cursor
  6254. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6255. // middle-click-paste. Or it might be a click on something we should
  6256. // not interfere with, such as a scrollbar or widget.
  6257. function onMouseDown(e) {
  6258. var cm = this, display = cm.display;
  6259. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6260. display.input.ensurePolled();
  6261. display.shift = e.shiftKey;
  6262. if (eventInWidget(display, e)) {
  6263. if (!webkit) {
  6264. // Briefly turn off draggability, to allow widgets to do
  6265. // normal dragging things.
  6266. display.scroller.draggable = false;
  6267. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6268. }
  6269. return
  6270. }
  6271. if (clickInGutter(cm, e)) { return }
  6272. var start = posFromMouse(cm, e);
  6273. window.focus();
  6274. switch (e_button(e)) {
  6275. case 1:
  6276. // #3261: make sure, that we're not starting a second selection
  6277. if (cm.state.selectingText)
  6278. { cm.state.selectingText(e); }
  6279. else if (start)
  6280. { leftButtonDown(cm, e, start); }
  6281. else if (e_target(e) == display.scroller)
  6282. { e_preventDefault(e); }
  6283. break
  6284. case 2:
  6285. if (webkit) { cm.state.lastMiddleDown = +new Date; }
  6286. if (start) { extendSelection(cm.doc, start); }
  6287. setTimeout(function () { return display.input.focus(); }, 20);
  6288. e_preventDefault(e);
  6289. break
  6290. case 3:
  6291. if (captureRightClick) { onContextMenu(cm, e); }
  6292. else { delayBlurEvent(cm); }
  6293. break
  6294. }
  6295. }
  6296. var lastClick;
  6297. var lastDoubleClick;
  6298. function leftButtonDown(cm, e, start) {
  6299. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6300. else { cm.curOp.focus = activeElt(); }
  6301. var now = +new Date, type;
  6302. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  6303. type = "triple";
  6304. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  6305. type = "double";
  6306. lastDoubleClick = {time: now, pos: start};
  6307. } else {
  6308. type = "single";
  6309. lastClick = {time: now, pos: start};
  6310. }
  6311. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  6312. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6313. type == "single" && (contained = sel.contains(start)) > -1 &&
  6314. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  6315. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  6316. { leftButtonStartDrag(cm, e, start, modifier); }
  6317. else
  6318. { leftButtonSelect(cm, e, start, type, modifier); }
  6319. }
  6320. // Start a text drag. When it ends, see if any dragging actually
  6321. // happen, and treat as a click if it didn't.
  6322. function leftButtonStartDrag(cm, e, start, modifier) {
  6323. var display = cm.display, moved = false;
  6324. var dragEnd = operation(cm, function (e) {
  6325. if (webkit) { display.scroller.draggable = false; }
  6326. cm.state.draggingText = false;
  6327. off(document, "mouseup", dragEnd);
  6328. off(document, "mousemove", mouseMove);
  6329. off(display.scroller, "dragstart", dragStart);
  6330. off(display.scroller, "drop", dragEnd);
  6331. if (!moved) {
  6332. e_preventDefault(e);
  6333. if (!modifier)
  6334. { extendSelection(cm.doc, start); }
  6335. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6336. if (webkit || ie && ie_version == 9)
  6337. { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
  6338. else
  6339. { display.input.focus(); }
  6340. }
  6341. });
  6342. var mouseMove = function(e2) {
  6343. moved = moved || Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) >= 10;
  6344. };
  6345. var dragStart = function () { return moved = true; };
  6346. // Let the drag handler handle this.
  6347. if (webkit) { display.scroller.draggable = true; }
  6348. cm.state.draggingText = dragEnd;
  6349. dragEnd.copy = mac ? e.altKey : e.ctrlKey;
  6350. // IE's approach to draggable
  6351. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6352. on(document, "mouseup", dragEnd);
  6353. on(document, "mousemove", mouseMove);
  6354. on(display.scroller, "dragstart", dragStart);
  6355. on(display.scroller, "drop", dragEnd);
  6356. delayBlurEvent(cm);
  6357. setTimeout(function () { return display.input.focus(); }, 20);
  6358. }
  6359. // Normal selection, as opposed to text dragging.
  6360. function leftButtonSelect(cm, e, start, type, addNew) {
  6361. var display = cm.display, doc = cm.doc;
  6362. e_preventDefault(e);
  6363. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6364. if (addNew && !e.shiftKey) {
  6365. ourIndex = doc.sel.contains(start);
  6366. if (ourIndex > -1)
  6367. { ourRange = ranges[ourIndex]; }
  6368. else
  6369. { ourRange = new Range(start, start); }
  6370. } else {
  6371. ourRange = doc.sel.primary();
  6372. ourIndex = doc.sel.primIndex;
  6373. }
  6374. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  6375. type = "rect";
  6376. if (!addNew) { ourRange = new Range(start, start); }
  6377. start = posFromMouse(cm, e, true, true);
  6378. ourIndex = -1;
  6379. } else if (type == "double") {
  6380. var word = cm.findWordAt(start);
  6381. if (cm.display.shift || doc.extend)
  6382. { ourRange = extendRange(doc, ourRange, word.anchor, word.head); }
  6383. else
  6384. { ourRange = word; }
  6385. } else if (type == "triple") {
  6386. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  6387. if (cm.display.shift || doc.extend)
  6388. { ourRange = extendRange(doc, ourRange, line.anchor, line.head); }
  6389. else
  6390. { ourRange = line; }
  6391. } else {
  6392. ourRange = extendRange(doc, ourRange, start);
  6393. }
  6394. if (!addNew) {
  6395. ourIndex = 0;
  6396. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6397. startSel = doc.sel;
  6398. } else if (ourIndex == -1) {
  6399. ourIndex = ranges.length;
  6400. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6401. {scroll: false, origin: "*mouse"});
  6402. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  6403. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6404. {scroll: false, origin: "*mouse"});
  6405. startSel = doc.sel;
  6406. } else {
  6407. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6408. }
  6409. var lastPos = start;
  6410. function extendTo(pos) {
  6411. if (cmp(lastPos, pos) == 0) { return }
  6412. lastPos = pos;
  6413. if (type == "rect") {
  6414. var ranges = [], tabSize = cm.options.tabSize;
  6415. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6416. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6417. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6418. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6419. line <= end; line++) {
  6420. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6421. if (left == right)
  6422. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6423. else if (text.length > leftPos)
  6424. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6425. }
  6426. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6427. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6428. {origin: "*mouse", scroll: false});
  6429. cm.scrollIntoView(pos);
  6430. } else {
  6431. var oldRange = ourRange;
  6432. var anchor = oldRange.anchor, head = pos;
  6433. if (type != "single") {
  6434. var range$$1;
  6435. if (type == "double")
  6436. { range$$1 = cm.findWordAt(pos); }
  6437. else
  6438. { range$$1 = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); }
  6439. if (cmp(range$$1.anchor, anchor) > 0) {
  6440. head = range$$1.head;
  6441. anchor = minPos(oldRange.from(), range$$1.anchor);
  6442. } else {
  6443. head = range$$1.anchor;
  6444. anchor = maxPos(oldRange.to(), range$$1.head);
  6445. }
  6446. }
  6447. var ranges$1 = startSel.ranges.slice(0);
  6448. ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head);
  6449. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
  6450. }
  6451. }
  6452. var editorSize = display.wrapper.getBoundingClientRect();
  6453. // Used to ensure timeout re-tries don't fire when another extend
  6454. // happened in the meantime (clearTimeout isn't reliable -- at
  6455. // least on Chrome, the timeouts still happen even when cleared,
  6456. // if the clear happens after their scheduled firing time).
  6457. var counter = 0;
  6458. function extend(e) {
  6459. var curCount = ++counter;
  6460. var cur = posFromMouse(cm, e, true, type == "rect");
  6461. if (!cur) { return }
  6462. if (cmp(cur, lastPos) != 0) {
  6463. cm.curOp.focus = activeElt();
  6464. extendTo(cur);
  6465. var visible = visibleLines(display, doc);
  6466. if (cur.line >= visible.to || cur.line < visible.from)
  6467. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6468. } else {
  6469. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6470. if (outside) { setTimeout(operation(cm, function () {
  6471. if (counter != curCount) { return }
  6472. display.scroller.scrollTop += outside;
  6473. extend(e);
  6474. }), 50); }
  6475. }
  6476. }
  6477. function done(e) {
  6478. cm.state.selectingText = false;
  6479. counter = Infinity;
  6480. e_preventDefault(e);
  6481. display.input.focus();
  6482. off(document, "mousemove", move);
  6483. off(document, "mouseup", up);
  6484. doc.history.lastSelOrigin = null;
  6485. }
  6486. var move = operation(cm, function (e) {
  6487. if (!e_button(e)) { done(e); }
  6488. else { extend(e); }
  6489. });
  6490. var up = operation(cm, done);
  6491. cm.state.selectingText = up;
  6492. on(document, "mousemove", move);
  6493. on(document, "mouseup", up);
  6494. }
  6495. // Determines whether an event happened in the gutter, and fires the
  6496. // handlers for the corresponding event.
  6497. function gutterEvent(cm, e, type, prevent) {
  6498. var mX, mY;
  6499. try { mX = e.clientX; mY = e.clientY; }
  6500. catch(e) { return false }
  6501. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6502. if (prevent) { e_preventDefault(e); }
  6503. var display = cm.display;
  6504. var lineBox = display.lineDiv.getBoundingClientRect();
  6505. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6506. mY -= lineBox.top - display.viewOffset;
  6507. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6508. var g = display.gutters.childNodes[i];
  6509. if (g && g.getBoundingClientRect().right >= mX) {
  6510. var line = lineAtHeight(cm.doc, mY);
  6511. var gutter = cm.options.gutters[i];
  6512. signal(cm, type, cm, line, gutter, e);
  6513. return e_defaultPrevented(e)
  6514. }
  6515. }
  6516. }
  6517. function clickInGutter(cm, e) {
  6518. return gutterEvent(cm, e, "gutterClick", true)
  6519. }
  6520. // CONTEXT MENU HANDLING
  6521. // To make the context menu work, we need to briefly unhide the
  6522. // textarea (making it as unobtrusive as possible) to let the
  6523. // right-click take effect on it.
  6524. function onContextMenu(cm, e) {
  6525. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6526. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6527. cm.display.input.onContextMenu(e);
  6528. }
  6529. function contextMenuInGutter(cm, e) {
  6530. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6531. return gutterEvent(cm, e, "gutterContextMenu", false)
  6532. }
  6533. function themeChanged(cm) {
  6534. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6535. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6536. clearCaches(cm);
  6537. }
  6538. var Init = {toString: function(){return "CodeMirror.Init"}};
  6539. var defaults = {};
  6540. var optionHandlers = {};
  6541. function defineOptions(CodeMirror) {
  6542. var optionHandlers = CodeMirror.optionHandlers;
  6543. function option(name, deflt, handle, notOnInit) {
  6544. CodeMirror.defaults[name] = deflt;
  6545. if (handle) { optionHandlers[name] =
  6546. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6547. }
  6548. CodeMirror.defineOption = option;
  6549. // Passed to option handlers when there is no old value.
  6550. CodeMirror.Init = Init;
  6551. // These two are, on init, called from the constructor because they
  6552. // have to be initialized before the editor can start at all.
  6553. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6554. option("mode", null, function (cm, val) {
  6555. cm.doc.modeOption = val;
  6556. loadMode(cm);
  6557. }, true);
  6558. option("indentUnit", 2, loadMode, true);
  6559. option("indentWithTabs", false);
  6560. option("smartIndent", true);
  6561. option("tabSize", 4, function (cm) {
  6562. resetModeState(cm);
  6563. clearCaches(cm);
  6564. regChange(cm);
  6565. }, true);
  6566. option("lineSeparator", null, function (cm, val) {
  6567. cm.doc.lineSep = val;
  6568. if (!val) { return }
  6569. var newBreaks = [], lineNo = cm.doc.first;
  6570. cm.doc.iter(function (line) {
  6571. for (var pos = 0;;) {
  6572. var found = line.text.indexOf(val, pos);
  6573. if (found == -1) { break }
  6574. pos = found + val.length;
  6575. newBreaks.push(Pos(lineNo, found));
  6576. }
  6577. lineNo++;
  6578. });
  6579. for (var i = newBreaks.length - 1; i >= 0; i--)
  6580. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6581. });
  6582. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6583. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6584. if (old != Init) { cm.refresh(); }
  6585. });
  6586. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6587. option("electricChars", true);
  6588. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6589. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6590. }, true);
  6591. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  6592. option("rtlMoveVisually", !windows);
  6593. option("wholeLineUpdateBefore", true);
  6594. option("theme", "default", function (cm) {
  6595. themeChanged(cm);
  6596. guttersChanged(cm);
  6597. }, true);
  6598. option("keyMap", "default", function (cm, val, old) {
  6599. var next = getKeyMap(val);
  6600. var prev = old != Init && getKeyMap(old);
  6601. if (prev && prev.detach) { prev.detach(cm, next); }
  6602. if (next.attach) { next.attach(cm, prev || null); }
  6603. });
  6604. option("extraKeys", null);
  6605. option("lineWrapping", false, wrappingChanged, true);
  6606. option("gutters", [], function (cm) {
  6607. setGuttersForLineNumbers(cm.options);
  6608. guttersChanged(cm);
  6609. }, true);
  6610. option("fixedGutter", true, function (cm, val) {
  6611. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6612. cm.refresh();
  6613. }, true);
  6614. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  6615. option("scrollbarStyle", "native", function (cm) {
  6616. initScrollbars(cm);
  6617. updateScrollbars(cm);
  6618. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6619. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6620. }, true);
  6621. option("lineNumbers", false, function (cm) {
  6622. setGuttersForLineNumbers(cm.options);
  6623. guttersChanged(cm);
  6624. }, true);
  6625. option("firstLineNumber", 1, guttersChanged, true);
  6626. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  6627. option("showCursorWhenSelecting", false, updateSelection, true);
  6628. option("resetSelectionOnContextMenu", true);
  6629. option("lineWiseCopyCut", true);
  6630. option("readOnly", false, function (cm, val) {
  6631. if (val == "nocursor") {
  6632. onBlur(cm);
  6633. cm.display.input.blur();
  6634. cm.display.disabled = true;
  6635. } else {
  6636. cm.display.disabled = false;
  6637. }
  6638. cm.display.input.readOnlyChanged(val);
  6639. });
  6640. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  6641. option("dragDrop", true, dragDropChanged);
  6642. option("allowDropFileTypes", null);
  6643. option("cursorBlinkRate", 530);
  6644. option("cursorScrollMargin", 0);
  6645. option("cursorHeight", 1, updateSelection, true);
  6646. option("singleCursorHeightPerLine", true, updateSelection, true);
  6647. option("workTime", 100);
  6648. option("workDelay", 100);
  6649. option("flattenSpans", true, resetModeState, true);
  6650. option("addModeClass", false, resetModeState, true);
  6651. option("pollInterval", 100);
  6652. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  6653. option("historyEventDelay", 1250);
  6654. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  6655. option("maxHighlightLength", 10000, resetModeState, true);
  6656. option("moveInputWithCursor", true, function (cm, val) {
  6657. if (!val) { cm.display.input.resetPosition(); }
  6658. });
  6659. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  6660. option("autofocus", null);
  6661. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  6662. }
  6663. function guttersChanged(cm) {
  6664. updateGutters(cm);
  6665. regChange(cm);
  6666. alignHorizontally(cm);
  6667. }
  6668. function dragDropChanged(cm, value, old) {
  6669. var wasOn = old && old != Init;
  6670. if (!value != !wasOn) {
  6671. var funcs = cm.display.dragFunctions;
  6672. var toggle = value ? on : off;
  6673. toggle(cm.display.scroller, "dragstart", funcs.start);
  6674. toggle(cm.display.scroller, "dragenter", funcs.enter);
  6675. toggle(cm.display.scroller, "dragover", funcs.over);
  6676. toggle(cm.display.scroller, "dragleave", funcs.leave);
  6677. toggle(cm.display.scroller, "drop", funcs.drop);
  6678. }
  6679. }
  6680. function wrappingChanged(cm) {
  6681. if (cm.options.lineWrapping) {
  6682. addClass(cm.display.wrapper, "CodeMirror-wrap");
  6683. cm.display.sizer.style.minWidth = "";
  6684. cm.display.sizerWidth = null;
  6685. } else {
  6686. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  6687. findMaxLine(cm);
  6688. }
  6689. estimateLineHeights(cm);
  6690. regChange(cm);
  6691. clearCaches(cm);
  6692. setTimeout(function () { return updateScrollbars(cm); }, 100);
  6693. }
  6694. // A CodeMirror instance represents an editor. This is the object
  6695. // that user code is usually dealing with.
  6696. function CodeMirror$1(place, options) {
  6697. var this$1 = this;
  6698. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  6699. this.options = options = options ? copyObj(options) : {};
  6700. // Determine effective options based on given values and defaults.
  6701. copyObj(defaults, options, false);
  6702. setGuttersForLineNumbers(options);
  6703. var doc = options.value;
  6704. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  6705. this.doc = doc;
  6706. var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  6707. var display = this.display = new Display(place, doc, input);
  6708. display.wrapper.CodeMirror = this;
  6709. updateGutters(this);
  6710. themeChanged(this);
  6711. if (options.lineWrapping)
  6712. { this.display.wrapper.className += " CodeMirror-wrap"; }
  6713. initScrollbars(this);
  6714. this.state = {
  6715. keyMaps: [], // stores maps added by addKeyMap
  6716. overlays: [], // highlighting overlays, as added by addOverlay
  6717. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  6718. overwrite: false,
  6719. delayingBlurEvent: false,
  6720. focused: false,
  6721. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  6722. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  6723. selectingText: false,
  6724. draggingText: false,
  6725. highlight: new Delayed(), // stores highlight worker timeout
  6726. keySeq: null, // Unfinished key sequence
  6727. specialChars: null
  6728. };
  6729. if (options.autofocus && !mobile) { display.input.focus(); }
  6730. // Override magic textarea content restore that IE sometimes does
  6731. // on our hidden textarea on reload
  6732. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  6733. registerEventHandlers(this);
  6734. ensureGlobalHandlers();
  6735. startOperation(this);
  6736. this.curOp.forceUpdate = true;
  6737. attachDoc(this, doc);
  6738. if ((options.autofocus && !mobile) || this.hasFocus())
  6739. { setTimeout(bind(onFocus, this), 20); }
  6740. else
  6741. { onBlur(this); }
  6742. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  6743. { optionHandlers[opt](this$1, options[opt], Init); } }
  6744. maybeUpdateLineNumberWidth(this);
  6745. if (options.finishInit) { options.finishInit(this); }
  6746. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  6747. endOperation(this);
  6748. // Suppress optimizelegibility in Webkit, since it breaks text
  6749. // measuring on line wrapping boundaries.
  6750. if (webkit && options.lineWrapping &&
  6751. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  6752. { display.lineDiv.style.textRendering = "auto"; }
  6753. }
  6754. // The default configuration options.
  6755. CodeMirror$1.defaults = defaults;
  6756. // Functions to run when options are changed.
  6757. CodeMirror$1.optionHandlers = optionHandlers;
  6758. // Attach the necessary event handlers when initializing the editor
  6759. function registerEventHandlers(cm) {
  6760. var d = cm.display;
  6761. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  6762. // Older IE's will not fire a second mousedown for a double click
  6763. if (ie && ie_version < 11)
  6764. { on(d.scroller, "dblclick", operation(cm, function (e) {
  6765. if (signalDOMEvent(cm, e)) { return }
  6766. var pos = posFromMouse(cm, e);
  6767. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  6768. e_preventDefault(e);
  6769. var word = cm.findWordAt(pos);
  6770. extendSelection(cm.doc, word.anchor, word.head);
  6771. })); }
  6772. else
  6773. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  6774. // Some browsers fire contextmenu *after* opening the menu, at
  6775. // which point we can't mess with it anymore. Context menu is
  6776. // handled in onMouseDown for these browsers.
  6777. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
  6778. // Used to suppress mouse event handling when a touch happens
  6779. var touchFinished, prevTouch = {end: 0};
  6780. function finishTouch() {
  6781. if (d.activeTouch) {
  6782. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  6783. prevTouch = d.activeTouch;
  6784. prevTouch.end = +new Date;
  6785. }
  6786. }
  6787. function isMouseLikeTouchEvent(e) {
  6788. if (e.touches.length != 1) { return false }
  6789. var touch = e.touches[0];
  6790. return touch.radiusX <= 1 && touch.radiusY <= 1
  6791. }
  6792. function farAway(touch, other) {
  6793. if (other.left == null) { return true }
  6794. var dx = other.left - touch.left, dy = other.top - touch.top;
  6795. return dx * dx + dy * dy > 20 * 20
  6796. }
  6797. on(d.scroller, "touchstart", function (e) {
  6798. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  6799. d.input.ensurePolled();
  6800. clearTimeout(touchFinished);
  6801. var now = +new Date;
  6802. d.activeTouch = {start: now, moved: false,
  6803. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  6804. if (e.touches.length == 1) {
  6805. d.activeTouch.left = e.touches[0].pageX;
  6806. d.activeTouch.top = e.touches[0].pageY;
  6807. }
  6808. }
  6809. });
  6810. on(d.scroller, "touchmove", function () {
  6811. if (d.activeTouch) { d.activeTouch.moved = true; }
  6812. });
  6813. on(d.scroller, "touchend", function (e) {
  6814. var touch = d.activeTouch;
  6815. if (touch && !eventInWidget(d, e) && touch.left != null &&
  6816. !touch.moved && new Date - touch.start < 300) {
  6817. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  6818. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  6819. { range = new Range(pos, pos); }
  6820. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  6821. { range = cm.findWordAt(pos); }
  6822. else // Triple tap
  6823. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  6824. cm.setSelection(range.anchor, range.head);
  6825. cm.focus();
  6826. e_preventDefault(e);
  6827. }
  6828. finishTouch();
  6829. });
  6830. on(d.scroller, "touchcancel", finishTouch);
  6831. // Sync scrolling between fake scrollbars and real scrollable
  6832. // area, ensure viewport is updated when scrolling.
  6833. on(d.scroller, "scroll", function () {
  6834. if (d.scroller.clientHeight) {
  6835. setScrollTop(cm, d.scroller.scrollTop);
  6836. setScrollLeft(cm, d.scroller.scrollLeft, true);
  6837. signal(cm, "scroll", cm);
  6838. }
  6839. });
  6840. // Listen to wheel events in order to try and update the viewport on time.
  6841. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  6842. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  6843. // Prevent wrapper from ever scrolling
  6844. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  6845. d.dragFunctions = {
  6846. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  6847. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  6848. start: function (e) { return onDragStart(cm, e); },
  6849. drop: operation(cm, onDrop),
  6850. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  6851. };
  6852. var inp = d.input.getField();
  6853. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  6854. on(inp, "keydown", operation(cm, onKeyDown));
  6855. on(inp, "keypress", operation(cm, onKeyPress));
  6856. on(inp, "focus", function (e) { return onFocus(cm, e); });
  6857. on(inp, "blur", function (e) { return onBlur(cm, e); });
  6858. }
  6859. var initHooks = [];
  6860. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
  6861. // Indent the given line. The how parameter can be "smart",
  6862. // "add"/null, "subtract", or "prev". When aggressive is false
  6863. // (typically set to true for forced single-line indents), empty
  6864. // lines are not indented, and places where the mode returns Pass
  6865. // are left alone.
  6866. function indentLine(cm, n, how, aggressive) {
  6867. var doc = cm.doc, state;
  6868. if (how == null) { how = "add"; }
  6869. if (how == "smart") {
  6870. // Fall back to "prev" when the mode doesn't have an indentation
  6871. // method.
  6872. if (!doc.mode.indent) { how = "prev"; }
  6873. else { state = getStateBefore(cm, n); }
  6874. }
  6875. var tabSize = cm.options.tabSize;
  6876. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  6877. if (line.stateAfter) { line.stateAfter = null; }
  6878. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  6879. if (!aggressive && !/\S/.test(line.text)) {
  6880. indentation = 0;
  6881. how = "not";
  6882. } else if (how == "smart") {
  6883. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  6884. if (indentation == Pass || indentation > 150) {
  6885. if (!aggressive) { return }
  6886. how = "prev";
  6887. }
  6888. }
  6889. if (how == "prev") {
  6890. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  6891. else { indentation = 0; }
  6892. } else if (how == "add") {
  6893. indentation = curSpace + cm.options.indentUnit;
  6894. } else if (how == "subtract") {
  6895. indentation = curSpace - cm.options.indentUnit;
  6896. } else if (typeof how == "number") {
  6897. indentation = curSpace + how;
  6898. }
  6899. indentation = Math.max(0, indentation);
  6900. var indentString = "", pos = 0;
  6901. if (cm.options.indentWithTabs)
  6902. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  6903. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  6904. if (indentString != curSpaceString) {
  6905. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  6906. line.stateAfter = null;
  6907. return true
  6908. } else {
  6909. // Ensure that, if the cursor was in the whitespace at the start
  6910. // of the line, it is moved to the end of that space.
  6911. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  6912. var range = doc.sel.ranges[i$1];
  6913. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6914. var pos$1 = Pos(n, curSpaceString.length);
  6915. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  6916. break
  6917. }
  6918. }
  6919. }
  6920. }
  6921. // This will be set to a {lineWise: bool, text: [string]} object, so
  6922. // that, when pasting, we know what kind of selections the copied
  6923. // text was made out of.
  6924. var lastCopied = null;
  6925. function setLastCopied(newLastCopied) {
  6926. lastCopied = newLastCopied;
  6927. }
  6928. function applyTextInput(cm, inserted, deleted, sel, origin) {
  6929. var doc = cm.doc;
  6930. cm.display.shift = false;
  6931. if (!sel) { sel = doc.sel; }
  6932. var paste = cm.state.pasteIncoming || origin == "paste";
  6933. var textLines = splitLinesAuto(inserted), multiPaste = null;
  6934. // When pasing N lines into N selections, insert one line per selection
  6935. if (paste && sel.ranges.length > 1) {
  6936. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  6937. if (sel.ranges.length % lastCopied.text.length == 0) {
  6938. multiPaste = [];
  6939. for (var i = 0; i < lastCopied.text.length; i++)
  6940. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  6941. }
  6942. } else if (textLines.length == sel.ranges.length) {
  6943. multiPaste = map(textLines, function (l) { return [l]; });
  6944. }
  6945. }
  6946. var updateInput;
  6947. // Normal behavior is to insert the new text into every selection
  6948. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  6949. var range$$1 = sel.ranges[i$1];
  6950. var from = range$$1.from(), to = range$$1.to();
  6951. if (range$$1.empty()) {
  6952. if (deleted && deleted > 0) // Handle deletion
  6953. { from = Pos(from.line, from.ch - deleted); }
  6954. else if (cm.state.overwrite && !paste) // Handle overwrite
  6955. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  6956. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  6957. { from = to = Pos(from.line, 0); }
  6958. }
  6959. updateInput = cm.curOp.updateInput;
  6960. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  6961. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  6962. makeChange(cm.doc, changeEvent);
  6963. signalLater(cm, "inputRead", cm, changeEvent);
  6964. }
  6965. if (inserted && !paste)
  6966. { triggerElectric(cm, inserted); }
  6967. ensureCursorVisible(cm);
  6968. cm.curOp.updateInput = updateInput;
  6969. cm.curOp.typing = true;
  6970. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  6971. }
  6972. function handlePaste(e, cm) {
  6973. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  6974. if (pasted) {
  6975. e.preventDefault();
  6976. if (!cm.isReadOnly() && !cm.options.disableInput)
  6977. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  6978. return true
  6979. }
  6980. }
  6981. function triggerElectric(cm, inserted) {
  6982. // When an 'electric' character is inserted, immediately trigger a reindent
  6983. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  6984. var sel = cm.doc.sel;
  6985. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  6986. var range$$1 = sel.ranges[i];
  6987. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  6988. var mode = cm.getModeAt(range$$1.head);
  6989. var indented = false;
  6990. if (mode.electricChars) {
  6991. for (var j = 0; j < mode.electricChars.length; j++)
  6992. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  6993. indented = indentLine(cm, range$$1.head.line, "smart");
  6994. break
  6995. } }
  6996. } else if (mode.electricInput) {
  6997. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  6998. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  6999. }
  7000. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  7001. }
  7002. }
  7003. function copyableRanges(cm) {
  7004. var text = [], ranges = [];
  7005. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7006. var line = cm.doc.sel.ranges[i].head.line;
  7007. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7008. ranges.push(lineRange);
  7009. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7010. }
  7011. return {text: text, ranges: ranges}
  7012. }
  7013. function disableBrowserMagic(field, spellcheck) {
  7014. field.setAttribute("autocorrect", "off");
  7015. field.setAttribute("autocapitalize", "off");
  7016. field.setAttribute("spellcheck", !!spellcheck);
  7017. }
  7018. function hiddenTextarea() {
  7019. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7020. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7021. // The textarea is kept positioned near the cursor to prevent the
  7022. // fact that it'll be scrolled into view on input from scrolling
  7023. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7024. // very slow. So make the area wide instead.
  7025. if (webkit) { te.style.width = "1000px"; }
  7026. else { te.setAttribute("wrap", "off"); }
  7027. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7028. if (ios) { te.style.border = "1px solid black"; }
  7029. disableBrowserMagic(te);
  7030. return div
  7031. }
  7032. // The publicly visible API. Note that methodOp(f) means
  7033. // 'wrap f in an operation, performed on its `this` parameter'.
  7034. // This is not the complete set of editor methods. Most of the
  7035. // methods defined on the Doc type are also injected into
  7036. // CodeMirror.prototype, for backwards compatibility and
  7037. // convenience.
  7038. var addEditorMethods = function(CodeMirror) {
  7039. var optionHandlers = CodeMirror.optionHandlers;
  7040. var helpers = CodeMirror.helpers = {};
  7041. CodeMirror.prototype = {
  7042. constructor: CodeMirror,
  7043. focus: function(){window.focus(); this.display.input.focus();},
  7044. setOption: function(option, value) {
  7045. var options = this.options, old = options[option];
  7046. if (options[option] == value && option != "mode") { return }
  7047. options[option] = value;
  7048. if (optionHandlers.hasOwnProperty(option))
  7049. { operation(this, optionHandlers[option])(this, value, old); }
  7050. signal(this, "optionChange", this, option);
  7051. },
  7052. getOption: function(option) {return this.options[option]},
  7053. getDoc: function() {return this.doc},
  7054. addKeyMap: function(map$$1, bottom) {
  7055. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  7056. },
  7057. removeKeyMap: function(map$$1) {
  7058. var maps = this.state.keyMaps;
  7059. for (var i = 0; i < maps.length; ++i)
  7060. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  7061. maps.splice(i, 1);
  7062. return true
  7063. } }
  7064. },
  7065. addOverlay: methodOp(function(spec, options) {
  7066. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7067. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7068. insertSorted(this.state.overlays,
  7069. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7070. priority: (options && options.priority) || 0},
  7071. function (overlay) { return overlay.priority; });
  7072. this.state.modeGen++;
  7073. regChange(this);
  7074. }),
  7075. removeOverlay: methodOp(function(spec) {
  7076. var this$1 = this;
  7077. var overlays = this.state.overlays;
  7078. for (var i = 0; i < overlays.length; ++i) {
  7079. var cur = overlays[i].modeSpec;
  7080. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7081. overlays.splice(i, 1);
  7082. this$1.state.modeGen++;
  7083. regChange(this$1);
  7084. return
  7085. }
  7086. }
  7087. }),
  7088. indentLine: methodOp(function(n, dir, aggressive) {
  7089. if (typeof dir != "string" && typeof dir != "number") {
  7090. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7091. else { dir = dir ? "add" : "subtract"; }
  7092. }
  7093. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7094. }),
  7095. indentSelection: methodOp(function(how) {
  7096. var this$1 = this;
  7097. var ranges = this.doc.sel.ranges, end = -1;
  7098. for (var i = 0; i < ranges.length; i++) {
  7099. var range$$1 = ranges[i];
  7100. if (!range$$1.empty()) {
  7101. var from = range$$1.from(), to = range$$1.to();
  7102. var start = Math.max(end, from.line);
  7103. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7104. for (var j = start; j < end; ++j)
  7105. { indentLine(this$1, j, how); }
  7106. var newRanges = this$1.doc.sel.ranges;
  7107. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7108. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7109. } else if (range$$1.head.line > end) {
  7110. indentLine(this$1, range$$1.head.line, how, true);
  7111. end = range$$1.head.line;
  7112. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  7113. }
  7114. }
  7115. }),
  7116. // Fetch the parser token for a given character. Useful for hacks
  7117. // that want to inspect the mode state (say, for completion).
  7118. getTokenAt: function(pos, precise) {
  7119. return takeToken(this, pos, precise)
  7120. },
  7121. getLineTokens: function(line, precise) {
  7122. return takeToken(this, Pos(line), precise, true)
  7123. },
  7124. getTokenTypeAt: function(pos) {
  7125. pos = clipPos(this.doc, pos);
  7126. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7127. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7128. var type;
  7129. if (ch == 0) { type = styles[2]; }
  7130. else { for (;;) {
  7131. var mid = (before + after) >> 1;
  7132. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7133. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7134. else { type = styles[mid * 2 + 2]; break }
  7135. } }
  7136. var cut = type ? type.indexOf("overlay ") : -1;
  7137. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7138. },
  7139. getModeAt: function(pos) {
  7140. var mode = this.doc.mode;
  7141. if (!mode.innerMode) { return mode }
  7142. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7143. },
  7144. getHelper: function(pos, type) {
  7145. return this.getHelpers(pos, type)[0]
  7146. },
  7147. getHelpers: function(pos, type) {
  7148. var this$1 = this;
  7149. var found = [];
  7150. if (!helpers.hasOwnProperty(type)) { return found }
  7151. var help = helpers[type], mode = this.getModeAt(pos);
  7152. if (typeof mode[type] == "string") {
  7153. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7154. } else if (mode[type]) {
  7155. for (var i = 0; i < mode[type].length; i++) {
  7156. var val = help[mode[type][i]];
  7157. if (val) { found.push(val); }
  7158. }
  7159. } else if (mode.helperType && help[mode.helperType]) {
  7160. found.push(help[mode.helperType]);
  7161. } else if (help[mode.name]) {
  7162. found.push(help[mode.name]);
  7163. }
  7164. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7165. var cur = help._global[i$1];
  7166. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7167. { found.push(cur.val); }
  7168. }
  7169. return found
  7170. },
  7171. getStateAfter: function(line, precise) {
  7172. var doc = this.doc;
  7173. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7174. return getStateBefore(this, line + 1, precise)
  7175. },
  7176. cursorCoords: function(start, mode) {
  7177. var pos, range$$1 = this.doc.sel.primary();
  7178. if (start == null) { pos = range$$1.head; }
  7179. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7180. else { pos = start ? range$$1.from() : range$$1.to(); }
  7181. return cursorCoords(this, pos, mode || "page")
  7182. },
  7183. charCoords: function(pos, mode) {
  7184. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7185. },
  7186. coordsChar: function(coords, mode) {
  7187. coords = fromCoordSystem(this, coords, mode || "page");
  7188. return coordsChar(this, coords.left, coords.top)
  7189. },
  7190. lineAtHeight: function(height, mode) {
  7191. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7192. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7193. },
  7194. heightAtLine: function(line, mode, includeWidgets) {
  7195. var end = false, lineObj;
  7196. if (typeof line == "number") {
  7197. var last = this.doc.first + this.doc.size - 1;
  7198. if (line < this.doc.first) { line = this.doc.first; }
  7199. else if (line > last) { line = last; end = true; }
  7200. lineObj = getLine(this.doc, line);
  7201. } else {
  7202. lineObj = line;
  7203. }
  7204. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7205. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7206. },
  7207. defaultTextHeight: function() { return textHeight(this.display) },
  7208. defaultCharWidth: function() { return charWidth(this.display) },
  7209. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7210. addWidget: function(pos, node, scroll, vert, horiz) {
  7211. var display = this.display;
  7212. pos = cursorCoords(this, clipPos(this.doc, pos));
  7213. var top = pos.bottom, left = pos.left;
  7214. node.style.position = "absolute";
  7215. node.setAttribute("cm-ignore-events", "true");
  7216. this.display.input.setUneditable(node);
  7217. display.sizer.appendChild(node);
  7218. if (vert == "over") {
  7219. top = pos.top;
  7220. } else if (vert == "above" || vert == "near") {
  7221. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7222. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7223. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7224. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7225. { top = pos.top - node.offsetHeight; }
  7226. else if (pos.bottom + node.offsetHeight <= vspace)
  7227. { top = pos.bottom; }
  7228. if (left + node.offsetWidth > hspace)
  7229. { left = hspace - node.offsetWidth; }
  7230. }
  7231. node.style.top = top + "px";
  7232. node.style.left = node.style.right = "";
  7233. if (horiz == "right") {
  7234. left = display.sizer.clientWidth - node.offsetWidth;
  7235. node.style.right = "0px";
  7236. } else {
  7237. if (horiz == "left") { left = 0; }
  7238. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7239. node.style.left = left + "px";
  7240. }
  7241. if (scroll)
  7242. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7243. },
  7244. triggerOnKeyDown: methodOp(onKeyDown),
  7245. triggerOnKeyPress: methodOp(onKeyPress),
  7246. triggerOnKeyUp: onKeyUp,
  7247. execCommand: function(cmd) {
  7248. if (commands.hasOwnProperty(cmd))
  7249. { return commands[cmd].call(null, this) }
  7250. },
  7251. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7252. findPosH: function(from, amount, unit, visually) {
  7253. var this$1 = this;
  7254. var dir = 1;
  7255. if (amount < 0) { dir = -1; amount = -amount; }
  7256. var cur = clipPos(this.doc, from);
  7257. for (var i = 0; i < amount; ++i) {
  7258. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  7259. if (cur.hitSide) { break }
  7260. }
  7261. return cur
  7262. },
  7263. moveH: methodOp(function(dir, unit) {
  7264. var this$1 = this;
  7265. this.extendSelectionsBy(function (range$$1) {
  7266. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  7267. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  7268. else
  7269. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7270. }, sel_move);
  7271. }),
  7272. deleteH: methodOp(function(dir, unit) {
  7273. var sel = this.doc.sel, doc = this.doc;
  7274. if (sel.somethingSelected())
  7275. { doc.replaceSelection("", null, "+delete"); }
  7276. else
  7277. { deleteNearSelection(this, function (range$$1) {
  7278. var other = findPosH(doc, range$$1.head, dir, unit, false);
  7279. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  7280. }); }
  7281. }),
  7282. findPosV: function(from, amount, unit, goalColumn) {
  7283. var this$1 = this;
  7284. var dir = 1, x = goalColumn;
  7285. if (amount < 0) { dir = -1; amount = -amount; }
  7286. var cur = clipPos(this.doc, from);
  7287. for (var i = 0; i < amount; ++i) {
  7288. var coords = cursorCoords(this$1, cur, "div");
  7289. if (x == null) { x = coords.left; }
  7290. else { coords.left = x; }
  7291. cur = findPosV(this$1, coords, dir, unit);
  7292. if (cur.hitSide) { break }
  7293. }
  7294. return cur
  7295. },
  7296. moveV: methodOp(function(dir, unit) {
  7297. var this$1 = this;
  7298. var doc = this.doc, goals = [];
  7299. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7300. doc.extendSelectionsBy(function (range$$1) {
  7301. if (collapse)
  7302. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7303. var headPos = cursorCoords(this$1, range$$1.head, "div");
  7304. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  7305. goals.push(headPos.left);
  7306. var pos = findPosV(this$1, headPos, dir, unit);
  7307. if (unit == "page" && range$$1 == doc.sel.primary())
  7308. { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top); }
  7309. return pos
  7310. }, sel_move);
  7311. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7312. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7313. }),
  7314. // Find the word at the given position (as returned by coordsChar).
  7315. findWordAt: function(pos) {
  7316. var doc = this.doc, line = getLine(doc, pos.line).text;
  7317. var start = pos.ch, end = pos.ch;
  7318. if (line) {
  7319. var helper = this.getHelper(pos, "wordChars");
  7320. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7321. var startChar = line.charAt(start);
  7322. var check = isWordChar(startChar, helper)
  7323. ? function (ch) { return isWordChar(ch, helper); }
  7324. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7325. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7326. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7327. while (end < line.length && check(line.charAt(end))) { ++end; }
  7328. }
  7329. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7330. },
  7331. toggleOverwrite: function(value) {
  7332. if (value != null && value == this.state.overwrite) { return }
  7333. if (this.state.overwrite = !this.state.overwrite)
  7334. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7335. else
  7336. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7337. signal(this, "overwriteToggle", this, this.state.overwrite);
  7338. },
  7339. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7340. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7341. scrollTo: methodOp(function(x, y) {
  7342. if (x != null || y != null) { resolveScrollToPos(this); }
  7343. if (x != null) { this.curOp.scrollLeft = x; }
  7344. if (y != null) { this.curOp.scrollTop = y; }
  7345. }),
  7346. getScrollInfo: function() {
  7347. var scroller = this.display.scroller;
  7348. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7349. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7350. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7351. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7352. },
  7353. scrollIntoView: methodOp(function(range$$1, margin) {
  7354. if (range$$1 == null) {
  7355. range$$1 = {from: this.doc.sel.primary().head, to: null};
  7356. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7357. } else if (typeof range$$1 == "number") {
  7358. range$$1 = {from: Pos(range$$1, 0), to: null};
  7359. } else if (range$$1.from == null) {
  7360. range$$1 = {from: range$$1, to: null};
  7361. }
  7362. if (!range$$1.to) { range$$1.to = range$$1.from; }
  7363. range$$1.margin = margin || 0;
  7364. if (range$$1.from.line != null) {
  7365. resolveScrollToPos(this);
  7366. this.curOp.scrollToPos = range$$1;
  7367. } else {
  7368. var sPos = calculateScrollPos(this, {
  7369. left: Math.min(range$$1.from.left, range$$1.to.left),
  7370. top: Math.min(range$$1.from.top, range$$1.to.top) - range$$1.margin,
  7371. right: Math.max(range$$1.from.right, range$$1.to.right),
  7372. bottom: Math.max(range$$1.from.bottom, range$$1.to.bottom) + range$$1.margin
  7373. });
  7374. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  7375. }
  7376. }),
  7377. setSize: methodOp(function(width, height) {
  7378. var this$1 = this;
  7379. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7380. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7381. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7382. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7383. var lineNo$$1 = this.display.viewFrom;
  7384. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  7385. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7386. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  7387. ++lineNo$$1;
  7388. });
  7389. this.curOp.forceUpdate = true;
  7390. signal(this, "refresh", this);
  7391. }),
  7392. operation: function(f){return runInOp(this, f)},
  7393. refresh: methodOp(function() {
  7394. var oldHeight = this.display.cachedTextHeight;
  7395. regChange(this);
  7396. this.curOp.forceUpdate = true;
  7397. clearCaches(this);
  7398. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  7399. updateGutterSpace(this);
  7400. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7401. { estimateLineHeights(this); }
  7402. signal(this, "refresh", this);
  7403. }),
  7404. swapDoc: methodOp(function(doc) {
  7405. var old = this.doc;
  7406. old.cm = null;
  7407. attachDoc(this, doc);
  7408. clearCaches(this);
  7409. this.display.input.reset();
  7410. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  7411. this.curOp.forceScroll = true;
  7412. signalLater(this, "swapDoc", this, old);
  7413. return old
  7414. }),
  7415. getInputField: function(){return this.display.input.getField()},
  7416. getWrapperElement: function(){return this.display.wrapper},
  7417. getScrollerElement: function(){return this.display.scroller},
  7418. getGutterElement: function(){return this.display.gutters}
  7419. };
  7420. eventMixin(CodeMirror);
  7421. CodeMirror.registerHelper = function(type, name, value) {
  7422. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7423. helpers[type][name] = value;
  7424. };
  7425. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7426. CodeMirror.registerHelper(type, name, value);
  7427. helpers[type]._global.push({pred: predicate, val: value});
  7428. };
  7429. };
  7430. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7431. // right), unit can be "char", "column" (like char, but doesn't
  7432. // cross line boundaries), "word" (across next word), or "group" (to
  7433. // the start of next group of word or non-word-non-whitespace
  7434. // chars). The visually param controls whether, in right-to-left
  7435. // text, direction 1 means to move towards the next index in the
  7436. // string, or towards the character to the right of the current
  7437. // position. The resulting position will have a hitSide=true
  7438. // property if it reached the end of the document.
  7439. function findPosH(doc, pos, dir, unit, visually) {
  7440. var oldPos = pos;
  7441. var origDir = dir;
  7442. var lineObj = getLine(doc, pos.line);
  7443. function findNextLine() {
  7444. var l = pos.line + dir;
  7445. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7446. pos = new Pos(l, pos.ch, pos.sticky);
  7447. return lineObj = getLine(doc, l)
  7448. }
  7449. function moveOnce(boundToLine) {
  7450. var next;
  7451. if (visually) {
  7452. next = moveVisually(doc.cm, lineObj, pos, dir);
  7453. } else {
  7454. next = moveLogically(lineObj, pos, dir);
  7455. }
  7456. if (next == null) {
  7457. if (!boundToLine && findNextLine())
  7458. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  7459. else
  7460. { return false }
  7461. } else {
  7462. pos = next;
  7463. }
  7464. return true
  7465. }
  7466. if (unit == "char") {
  7467. moveOnce();
  7468. } else if (unit == "column") {
  7469. moveOnce(true);
  7470. } else if (unit == "word" || unit == "group") {
  7471. var sawType = null, group = unit == "group";
  7472. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7473. for (var first = true;; first = false) {
  7474. if (dir < 0 && !moveOnce(!first)) { break }
  7475. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7476. var type = isWordChar(cur, helper) ? "w"
  7477. : group && cur == "\n" ? "n"
  7478. : !group || /\s/.test(cur) ? null
  7479. : "p";
  7480. if (group && !first && !type) { type = "s"; }
  7481. if (sawType && sawType != type) {
  7482. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7483. break
  7484. }
  7485. if (type) { sawType = type; }
  7486. if (dir > 0 && !moveOnce(!first)) { break }
  7487. }
  7488. }
  7489. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7490. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7491. return result
  7492. }
  7493. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7494. // "page" or "line". The resulting position will have a hitSide=true
  7495. // property if it reached the end of the document.
  7496. function findPosV(cm, pos, dir, unit) {
  7497. var doc = cm.doc, x = pos.left, y;
  7498. if (unit == "page") {
  7499. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7500. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7501. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7502. } else if (unit == "line") {
  7503. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7504. }
  7505. var target;
  7506. for (;;) {
  7507. target = coordsChar(cm, x, y);
  7508. if (!target.outside) { break }
  7509. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7510. y += dir * 5;
  7511. }
  7512. return target
  7513. }
  7514. // CONTENTEDITABLE INPUT STYLE
  7515. var ContentEditableInput = function(cm) {
  7516. this.cm = cm;
  7517. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7518. this.polling = new Delayed();
  7519. this.composing = null;
  7520. this.gracePeriod = false;
  7521. this.readDOMTimeout = null;
  7522. };
  7523. ContentEditableInput.prototype.init = function (display) {
  7524. var this$1 = this;
  7525. var input = this, cm = input.cm;
  7526. var div = input.div = display.lineDiv;
  7527. disableBrowserMagic(div, cm.options.spellcheck);
  7528. on(div, "paste", function (e) {
  7529. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7530. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7531. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7532. });
  7533. on(div, "compositionstart", function (e) {
  7534. this$1.composing = {data: e.data, done: false};
  7535. });
  7536. on(div, "compositionupdate", function (e) {
  7537. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7538. });
  7539. on(div, "compositionend", function (e) {
  7540. if (this$1.composing) {
  7541. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7542. this$1.composing.done = true;
  7543. }
  7544. });
  7545. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7546. on(div, "input", function () {
  7547. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7548. });
  7549. function onCopyCut(e) {
  7550. if (signalDOMEvent(cm, e)) { return }
  7551. if (cm.somethingSelected()) {
  7552. setLastCopied({lineWise: false, text: cm.getSelections()});
  7553. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7554. } else if (!cm.options.lineWiseCopyCut) {
  7555. return
  7556. } else {
  7557. var ranges = copyableRanges(cm);
  7558. setLastCopied({lineWise: true, text: ranges.text});
  7559. if (e.type == "cut") {
  7560. cm.operation(function () {
  7561. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7562. cm.replaceSelection("", null, "cut");
  7563. });
  7564. }
  7565. }
  7566. if (e.clipboardData) {
  7567. e.clipboardData.clearData();
  7568. var content = lastCopied.text.join("\n");
  7569. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7570. e.clipboardData.setData("Text", content);
  7571. if (e.clipboardData.getData("Text") == content) {
  7572. e.preventDefault();
  7573. return
  7574. }
  7575. }
  7576. // Old-fashioned briefly-focus-a-textarea hack
  7577. var kludge = hiddenTextarea(), te = kludge.firstChild;
  7578. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  7579. te.value = lastCopied.text.join("\n");
  7580. var hadFocus = document.activeElement;
  7581. selectInput(te);
  7582. setTimeout(function () {
  7583. cm.display.lineSpace.removeChild(kludge);
  7584. hadFocus.focus();
  7585. if (hadFocus == div) { input.showPrimarySelection(); }
  7586. }, 50);
  7587. }
  7588. on(div, "copy", onCopyCut);
  7589. on(div, "cut", onCopyCut);
  7590. };
  7591. ContentEditableInput.prototype.prepareSelection = function () {
  7592. var result = prepareSelection(this.cm, false);
  7593. result.focus = this.cm.state.focused;
  7594. return result
  7595. };
  7596. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7597. if (!info || !this.cm.display.view.length) { return }
  7598. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  7599. this.showMultipleSelections(info);
  7600. };
  7601. ContentEditableInput.prototype.showPrimarySelection = function () {
  7602. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  7603. var from = prim.from(), to = prim.to();
  7604. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7605. sel.removeAllRanges();
  7606. return
  7607. }
  7608. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  7609. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  7610. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7611. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7612. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7613. { return }
  7614. var view = cm.display.view;
  7615. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7616. {node: view[0].measure.map[2], offset: 0};
  7617. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  7618. if (!end) {
  7619. var measure = view[view.length - 1].measure;
  7620. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  7621. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  7622. }
  7623. if (!start || !end) {
  7624. sel.removeAllRanges();
  7625. return
  7626. }
  7627. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  7628. try { rng = range(start.node, start.offset, end.offset, end.node); }
  7629. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7630. if (rng) {
  7631. if (!gecko && cm.state.focused) {
  7632. sel.collapse(start.node, start.offset);
  7633. if (!rng.collapsed) {
  7634. sel.removeAllRanges();
  7635. sel.addRange(rng);
  7636. }
  7637. } else {
  7638. sel.removeAllRanges();
  7639. sel.addRange(rng);
  7640. }
  7641. if (old && sel.anchorNode == null) { sel.addRange(old); }
  7642. else if (gecko) { this.startGracePeriod(); }
  7643. }
  7644. this.rememberSelection();
  7645. };
  7646. ContentEditableInput.prototype.startGracePeriod = function () {
  7647. var this$1 = this;
  7648. clearTimeout(this.gracePeriod);
  7649. this.gracePeriod = setTimeout(function () {
  7650. this$1.gracePeriod = false;
  7651. if (this$1.selectionChanged())
  7652. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  7653. }, 20);
  7654. };
  7655. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7656. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  7657. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  7658. };
  7659. ContentEditableInput.prototype.rememberSelection = function () {
  7660. var sel = window.getSelection();
  7661. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  7662. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  7663. };
  7664. ContentEditableInput.prototype.selectionInEditor = function () {
  7665. var sel = window.getSelection();
  7666. if (!sel.rangeCount) { return false }
  7667. var node = sel.getRangeAt(0).commonAncestorContainer;
  7668. return contains(this.div, node)
  7669. };
  7670. ContentEditableInput.prototype.focus = function () {
  7671. if (this.cm.options.readOnly != "nocursor") {
  7672. if (!this.selectionInEditor())
  7673. { this.showSelection(this.prepareSelection(), true); }
  7674. this.div.focus();
  7675. }
  7676. };
  7677. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  7678. ContentEditableInput.prototype.getField = function () { return this.div };
  7679. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7680. ContentEditableInput.prototype.receivedFocus = function () {
  7681. var input = this;
  7682. if (this.selectionInEditor())
  7683. { this.pollSelection(); }
  7684. else
  7685. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  7686. function poll() {
  7687. if (input.cm.state.focused) {
  7688. input.pollSelection();
  7689. input.polling.set(input.cm.options.pollInterval, poll);
  7690. }
  7691. }
  7692. this.polling.set(this.cm.options.pollInterval, poll);
  7693. };
  7694. ContentEditableInput.prototype.selectionChanged = function () {
  7695. var sel = window.getSelection();
  7696. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7697. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7698. };
  7699. ContentEditableInput.prototype.pollSelection = function () {
  7700. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  7701. var sel = window.getSelection(), cm = this.cm;
  7702. // On Android Chrome (version 56, at least), backspacing into an
  7703. // uneditable block element will put the cursor in that element,
  7704. // and then, because it's not editable, hide the virtual keyboard.
  7705. // Because Android doesn't allow us to actually detect backspace
  7706. // presses in a sane way, this code checks for when that happens
  7707. // and simulates a backspace press in this case.
  7708. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  7709. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  7710. this.blur();
  7711. this.focus();
  7712. return
  7713. }
  7714. if (this.composing) { return }
  7715. this.rememberSelection();
  7716. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  7717. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  7718. if (anchor && head) { runInOp(cm, function () {
  7719. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  7720. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  7721. }); }
  7722. };
  7723. ContentEditableInput.prototype.pollContent = function () {
  7724. if (this.readDOMTimeout != null) {
  7725. clearTimeout(this.readDOMTimeout);
  7726. this.readDOMTimeout = null;
  7727. }
  7728. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  7729. var from = sel.from(), to = sel.to();
  7730. if (from.ch == 0 && from.line > cm.firstLine())
  7731. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  7732. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  7733. { to = Pos(to.line + 1, 0); }
  7734. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  7735. var fromIndex, fromLine, fromNode;
  7736. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  7737. fromLine = lineNo(display.view[0].line);
  7738. fromNode = display.view[0].node;
  7739. } else {
  7740. fromLine = lineNo(display.view[fromIndex].line);
  7741. fromNode = display.view[fromIndex - 1].node.nextSibling;
  7742. }
  7743. var toIndex = findViewIndex(cm, to.line);
  7744. var toLine, toNode;
  7745. if (toIndex == display.view.length - 1) {
  7746. toLine = display.viewTo - 1;
  7747. toNode = display.lineDiv.lastChild;
  7748. } else {
  7749. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  7750. toNode = display.view[toIndex + 1].node.previousSibling;
  7751. }
  7752. if (!fromNode) { return false }
  7753. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  7754. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  7755. while (newText.length > 1 && oldText.length > 1) {
  7756. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  7757. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  7758. else { break }
  7759. }
  7760. var cutFront = 0, cutEnd = 0;
  7761. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  7762. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  7763. { ++cutFront; }
  7764. var newBot = lst(newText), oldBot = lst(oldText);
  7765. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  7766. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  7767. while (cutEnd < maxCutEnd &&
  7768. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  7769. { ++cutEnd; }
  7770. // Try to move start of change to start of selection if ambiguous
  7771. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  7772. while (cutFront && cutFront > from.ch &&
  7773. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  7774. cutFront--;
  7775. cutEnd++;
  7776. }
  7777. }
  7778. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  7779. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  7780. var chFrom = Pos(fromLine, cutFront);
  7781. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  7782. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  7783. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  7784. return true
  7785. }
  7786. };
  7787. ContentEditableInput.prototype.ensurePolled = function () {
  7788. this.forceCompositionEnd();
  7789. };
  7790. ContentEditableInput.prototype.reset = function () {
  7791. this.forceCompositionEnd();
  7792. };
  7793. ContentEditableInput.prototype.forceCompositionEnd = function () {
  7794. if (!this.composing) { return }
  7795. clearTimeout(this.readDOMTimeout);
  7796. this.composing = null;
  7797. this.updateFromDOM();
  7798. this.div.blur();
  7799. this.div.focus();
  7800. };
  7801. ContentEditableInput.prototype.readFromDOMSoon = function () {
  7802. var this$1 = this;
  7803. if (this.readDOMTimeout != null) { return }
  7804. this.readDOMTimeout = setTimeout(function () {
  7805. this$1.readDOMTimeout = null;
  7806. if (this$1.composing) {
  7807. if (this$1.composing.done) { this$1.composing = null; }
  7808. else { return }
  7809. }
  7810. this$1.updateFromDOM();
  7811. }, 80);
  7812. };
  7813. ContentEditableInput.prototype.updateFromDOM = function () {
  7814. var this$1 = this;
  7815. if (this.cm.isReadOnly() || !this.pollContent())
  7816. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  7817. };
  7818. ContentEditableInput.prototype.setUneditable = function (node) {
  7819. node.contentEditable = "false";
  7820. };
  7821. ContentEditableInput.prototype.onKeyPress = function (e) {
  7822. if (e.charCode == 0) { return }
  7823. e.preventDefault();
  7824. if (!this.cm.isReadOnly())
  7825. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  7826. };
  7827. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  7828. this.div.contentEditable = String(val != "nocursor");
  7829. };
  7830. ContentEditableInput.prototype.onContextMenu = function () {};
  7831. ContentEditableInput.prototype.resetPosition = function () {};
  7832. ContentEditableInput.prototype.needsContentAttribute = true;
  7833. function posToDOM(cm, pos) {
  7834. var view = findViewForLine(cm, pos.line);
  7835. if (!view || view.hidden) { return null }
  7836. var line = getLine(cm.doc, pos.line);
  7837. var info = mapFromLineView(view, line, pos.line);
  7838. var order = getOrder(line, cm.doc.direction), side = "left";
  7839. if (order) {
  7840. var partPos = getBidiPartAt(order, pos.ch);
  7841. side = partPos % 2 ? "right" : "left";
  7842. }
  7843. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  7844. result.offset = result.collapse == "right" ? result.end : result.start;
  7845. return result
  7846. }
  7847. function isInGutter(node) {
  7848. for (var scan = node; scan; scan = scan.parentNode)
  7849. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  7850. return false
  7851. }
  7852. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  7853. function domTextBetween(cm, from, to, fromLine, toLine) {
  7854. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  7855. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  7856. function close() {
  7857. if (closing) {
  7858. text += lineSep;
  7859. closing = false;
  7860. }
  7861. }
  7862. function addText(str) {
  7863. if (str) {
  7864. close();
  7865. text += str;
  7866. }
  7867. }
  7868. function walk(node) {
  7869. if (node.nodeType == 1) {
  7870. var cmText = node.getAttribute("cm-text");
  7871. if (cmText != null) {
  7872. addText(cmText || node.textContent.replace(/\u200b/g, ""));
  7873. return
  7874. }
  7875. var markerID = node.getAttribute("cm-marker"), range$$1;
  7876. if (markerID) {
  7877. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  7878. if (found.length && (range$$1 = found[0].find()))
  7879. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  7880. return
  7881. }
  7882. if (node.getAttribute("contenteditable") == "false") { return }
  7883. var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
  7884. if (isBlock) { close(); }
  7885. for (var i = 0; i < node.childNodes.length; i++)
  7886. { walk(node.childNodes[i]); }
  7887. if (isBlock) { closing = true; }
  7888. } else if (node.nodeType == 3) {
  7889. addText(node.nodeValue);
  7890. }
  7891. }
  7892. for (;;) {
  7893. walk(from);
  7894. if (from == to) { break }
  7895. from = from.nextSibling;
  7896. }
  7897. return text
  7898. }
  7899. function domToPos(cm, node, offset) {
  7900. var lineNode;
  7901. if (node == cm.display.lineDiv) {
  7902. lineNode = cm.display.lineDiv.childNodes[offset];
  7903. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  7904. node = null; offset = 0;
  7905. } else {
  7906. for (lineNode = node;; lineNode = lineNode.parentNode) {
  7907. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  7908. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  7909. }
  7910. }
  7911. for (var i = 0; i < cm.display.view.length; i++) {
  7912. var lineView = cm.display.view[i];
  7913. if (lineView.node == lineNode)
  7914. { return locateNodeInLineView(lineView, node, offset) }
  7915. }
  7916. }
  7917. function locateNodeInLineView(lineView, node, offset) {
  7918. var wrapper = lineView.text.firstChild, bad = false;
  7919. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  7920. if (node == wrapper) {
  7921. bad = true;
  7922. node = wrapper.childNodes[offset];
  7923. offset = 0;
  7924. if (!node) {
  7925. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  7926. return badPos(Pos(lineNo(line), line.text.length), bad)
  7927. }
  7928. }
  7929. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  7930. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  7931. textNode = node.firstChild;
  7932. if (offset) { offset = textNode.nodeValue.length; }
  7933. }
  7934. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  7935. var measure = lineView.measure, maps = measure.maps;
  7936. function find(textNode, topNode, offset) {
  7937. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  7938. var map$$1 = i < 0 ? measure.map : maps[i];
  7939. for (var j = 0; j < map$$1.length; j += 3) {
  7940. var curNode = map$$1[j + 2];
  7941. if (curNode == textNode || curNode == topNode) {
  7942. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  7943. var ch = map$$1[j] + offset;
  7944. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  7945. return Pos(line, ch)
  7946. }
  7947. }
  7948. }
  7949. }
  7950. var found = find(textNode, topNode, offset);
  7951. if (found) { return badPos(found, bad) }
  7952. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  7953. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  7954. found = find(after, after.firstChild, 0);
  7955. if (found)
  7956. { return badPos(Pos(found.line, found.ch - dist), bad) }
  7957. else
  7958. { dist += after.textContent.length; }
  7959. }
  7960. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  7961. found = find(before, before.firstChild, -1);
  7962. if (found)
  7963. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  7964. else
  7965. { dist$1 += before.textContent.length; }
  7966. }
  7967. }
  7968. // TEXTAREA INPUT STYLE
  7969. var TextareaInput = function(cm) {
  7970. this.cm = cm;
  7971. // See input.poll and input.reset
  7972. this.prevInput = "";
  7973. // Flag that indicates whether we expect input to appear real soon
  7974. // now (after some event like 'keypress' or 'input') and are
  7975. // polling intensively.
  7976. this.pollingFast = false;
  7977. // Self-resetting timeout for the poller
  7978. this.polling = new Delayed();
  7979. // Tracks when input.reset has punted to just putting a short
  7980. // string into the textarea instead of the full selection.
  7981. this.inaccurateSelection = false;
  7982. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  7983. this.hasSelection = false;
  7984. this.composing = null;
  7985. };
  7986. TextareaInput.prototype.init = function (display) {
  7987. var this$1 = this;
  7988. var input = this, cm = this.cm;
  7989. // Wraps and hides input textarea
  7990. var div = this.wrapper = hiddenTextarea();
  7991. // The semihidden textarea that is focused when the editor is
  7992. // focused, and receives input.
  7993. var te = this.textarea = div.firstChild;
  7994. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  7995. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  7996. if (ios) { te.style.width = "0px"; }
  7997. on(te, "input", function () {
  7998. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  7999. input.poll();
  8000. });
  8001. on(te, "paste", function (e) {
  8002. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8003. cm.state.pasteIncoming = true;
  8004. input.fastPoll();
  8005. });
  8006. function prepareCopyCut(e) {
  8007. if (signalDOMEvent(cm, e)) { return }
  8008. if (cm.somethingSelected()) {
  8009. setLastCopied({lineWise: false, text: cm.getSelections()});
  8010. if (input.inaccurateSelection) {
  8011. input.prevInput = "";
  8012. input.inaccurateSelection = false;
  8013. te.value = lastCopied.text.join("\n");
  8014. selectInput(te);
  8015. }
  8016. } else if (!cm.options.lineWiseCopyCut) {
  8017. return
  8018. } else {
  8019. var ranges = copyableRanges(cm);
  8020. setLastCopied({lineWise: true, text: ranges.text});
  8021. if (e.type == "cut") {
  8022. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8023. } else {
  8024. input.prevInput = "";
  8025. te.value = ranges.text.join("\n");
  8026. selectInput(te);
  8027. }
  8028. }
  8029. if (e.type == "cut") { cm.state.cutIncoming = true; }
  8030. }
  8031. on(te, "cut", prepareCopyCut);
  8032. on(te, "copy", prepareCopyCut);
  8033. on(display.scroller, "paste", function (e) {
  8034. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8035. cm.state.pasteIncoming = true;
  8036. input.focus();
  8037. });
  8038. // Prevent normal selection in the editor (we handle our own)
  8039. on(display.lineSpace, "selectstart", function (e) {
  8040. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8041. });
  8042. on(te, "compositionstart", function () {
  8043. var start = cm.getCursor("from");
  8044. if (input.composing) { input.composing.range.clear(); }
  8045. input.composing = {
  8046. start: start,
  8047. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8048. };
  8049. });
  8050. on(te, "compositionend", function () {
  8051. if (input.composing) {
  8052. input.poll();
  8053. input.composing.range.clear();
  8054. input.composing = null;
  8055. }
  8056. });
  8057. };
  8058. TextareaInput.prototype.prepareSelection = function () {
  8059. // Redraw the selection and/or cursor
  8060. var cm = this.cm, display = cm.display, doc = cm.doc;
  8061. var result = prepareSelection(cm);
  8062. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8063. if (cm.options.moveInputWithCursor) {
  8064. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8065. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8066. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8067. headPos.top + lineOff.top - wrapOff.top));
  8068. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8069. headPos.left + lineOff.left - wrapOff.left));
  8070. }
  8071. return result
  8072. };
  8073. TextareaInput.prototype.showSelection = function (drawn) {
  8074. var cm = this.cm, display = cm.display;
  8075. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8076. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8077. if (drawn.teTop != null) {
  8078. this.wrapper.style.top = drawn.teTop + "px";
  8079. this.wrapper.style.left = drawn.teLeft + "px";
  8080. }
  8081. };
  8082. // Reset the input to correspond to the selection (or to be empty,
  8083. // when not typing and nothing is selected)
  8084. TextareaInput.prototype.reset = function (typing) {
  8085. if (this.contextMenuPending) { return }
  8086. var minimal, selected, cm = this.cm, doc = cm.doc;
  8087. if (cm.somethingSelected()) {
  8088. this.prevInput = "";
  8089. var range$$1 = doc.sel.primary();
  8090. minimal = hasCopyEvent &&
  8091. (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  8092. var content = minimal ? "-" : selected || cm.getSelection();
  8093. this.textarea.value = content;
  8094. if (cm.state.focused) { selectInput(this.textarea); }
  8095. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8096. } else if (!typing) {
  8097. this.prevInput = this.textarea.value = "";
  8098. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8099. }
  8100. this.inaccurateSelection = minimal;
  8101. };
  8102. TextareaInput.prototype.getField = function () { return this.textarea };
  8103. TextareaInput.prototype.supportsTouch = function () { return false };
  8104. TextareaInput.prototype.focus = function () {
  8105. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8106. try { this.textarea.focus(); }
  8107. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8108. }
  8109. };
  8110. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8111. TextareaInput.prototype.resetPosition = function () {
  8112. this.wrapper.style.top = this.wrapper.style.left = 0;
  8113. };
  8114. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8115. // Poll for input changes, using the normal rate of polling. This
  8116. // runs as long as the editor is focused.
  8117. TextareaInput.prototype.slowPoll = function () {
  8118. var this$1 = this;
  8119. if (this.pollingFast) { return }
  8120. this.polling.set(this.cm.options.pollInterval, function () {
  8121. this$1.poll();
  8122. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8123. });
  8124. };
  8125. // When an event has just come in that is likely to add or change
  8126. // something in the input textarea, we poll faster, to ensure that
  8127. // the change appears on the screen quickly.
  8128. TextareaInput.prototype.fastPoll = function () {
  8129. var missed = false, input = this;
  8130. input.pollingFast = true;
  8131. function p() {
  8132. var changed = input.poll();
  8133. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8134. else {input.pollingFast = false; input.slowPoll();}
  8135. }
  8136. input.polling.set(20, p);
  8137. };
  8138. // Read input from the textarea, and update the document to match.
  8139. // When something is selected, it is present in the textarea, and
  8140. // selected (unless it is huge, in which case a placeholder is
  8141. // used). When nothing is selected, the cursor sits after previously
  8142. // seen text (can be empty), which is stored in prevInput (we must
  8143. // not reset the textarea when typing, because that breaks IME).
  8144. TextareaInput.prototype.poll = function () {
  8145. var this$1 = this;
  8146. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8147. // Since this is called a *lot*, try to bail out as cheaply as
  8148. // possible when it is clear that nothing happened. hasSelection
  8149. // will be the case when there is a lot of text in the textarea,
  8150. // in which case reading its value would be expensive.
  8151. if (this.contextMenuPending || !cm.state.focused ||
  8152. (hasSelection(input) && !prevInput && !this.composing) ||
  8153. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8154. { return false }
  8155. var text = input.value;
  8156. // If nothing changed, bail.
  8157. if (text == prevInput && !cm.somethingSelected()) { return false }
  8158. // Work around nonsensical selection resetting in IE9/10, and
  8159. // inexplicable appearance of private area unicode characters on
  8160. // some key combos in Mac (#2689).
  8161. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8162. mac && /[\uf700-\uf7ff]/.test(text)) {
  8163. cm.display.input.reset();
  8164. return false
  8165. }
  8166. if (cm.doc.sel == cm.display.selForContextMenu) {
  8167. var first = text.charCodeAt(0);
  8168. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8169. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8170. }
  8171. // Find the part of the input that is actually new
  8172. var same = 0, l = Math.min(prevInput.length, text.length);
  8173. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8174. runInOp(cm, function () {
  8175. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8176. null, this$1.composing ? "*compose" : null);
  8177. // Don't leave long text in the textarea, since it makes further polling slow
  8178. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8179. else { this$1.prevInput = text; }
  8180. if (this$1.composing) {
  8181. this$1.composing.range.clear();
  8182. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8183. {className: "CodeMirror-composing"});
  8184. }
  8185. });
  8186. return true
  8187. };
  8188. TextareaInput.prototype.ensurePolled = function () {
  8189. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8190. };
  8191. TextareaInput.prototype.onKeyPress = function () {
  8192. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8193. this.fastPoll();
  8194. };
  8195. TextareaInput.prototype.onContextMenu = function (e) {
  8196. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8197. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8198. if (!pos || presto) { return } // Opera is difficult.
  8199. // Reset the current text selection only if the click is done outside of the selection
  8200. // and 'resetSelectionOnContextMenu' option is true.
  8201. var reset = cm.options.resetSelectionOnContextMenu;
  8202. if (reset && cm.doc.sel.contains(pos) == -1)
  8203. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8204. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8205. input.wrapper.style.cssText = "position: absolute";
  8206. var wrapperBox = input.wrapper.getBoundingClientRect();
  8207. 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);";
  8208. var oldScrollY;
  8209. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8210. display.input.focus();
  8211. if (webkit) { window.scrollTo(null, oldScrollY); }
  8212. display.input.reset();
  8213. // Adds "Select all" to context menu in FF
  8214. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8215. input.contextMenuPending = true;
  8216. display.selForContextMenu = cm.doc.sel;
  8217. clearTimeout(display.detectingSelectAll);
  8218. // Select-all will be greyed out if there's nothing to select, so
  8219. // this adds a zero-width space so that we can later check whether
  8220. // it got selected.
  8221. function prepareSelectAllHack() {
  8222. if (te.selectionStart != null) {
  8223. var selected = cm.somethingSelected();
  8224. var extval = "\u200b" + (selected ? te.value : "");
  8225. te.value = "\u21da"; // Used to catch context-menu undo
  8226. te.value = extval;
  8227. input.prevInput = selected ? "" : "\u200b";
  8228. te.selectionStart = 1; te.selectionEnd = extval.length;
  8229. // Re-set this, in case some other handler touched the
  8230. // selection in the meantime.
  8231. display.selForContextMenu = cm.doc.sel;
  8232. }
  8233. }
  8234. function rehide() {
  8235. input.contextMenuPending = false;
  8236. input.wrapper.style.cssText = oldWrapperCSS;
  8237. te.style.cssText = oldCSS;
  8238. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8239. // Try to detect the user choosing select-all
  8240. if (te.selectionStart != null) {
  8241. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8242. var i = 0, poll = function () {
  8243. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8244. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8245. operation(cm, selectAll)(cm);
  8246. } else if (i++ < 10) {
  8247. display.detectingSelectAll = setTimeout(poll, 500);
  8248. } else {
  8249. display.selForContextMenu = null;
  8250. display.input.reset();
  8251. }
  8252. };
  8253. display.detectingSelectAll = setTimeout(poll, 200);
  8254. }
  8255. }
  8256. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8257. if (captureRightClick) {
  8258. e_stop(e);
  8259. var mouseup = function () {
  8260. off(window, "mouseup", mouseup);
  8261. setTimeout(rehide, 20);
  8262. };
  8263. on(window, "mouseup", mouseup);
  8264. } else {
  8265. setTimeout(rehide, 50);
  8266. }
  8267. };
  8268. TextareaInput.prototype.readOnlyChanged = function (val) {
  8269. if (!val) { this.reset(); }
  8270. };
  8271. TextareaInput.prototype.setUneditable = function () {};
  8272. TextareaInput.prototype.needsContentAttribute = false;
  8273. function fromTextArea(textarea, options) {
  8274. options = options ? copyObj(options) : {};
  8275. options.value = textarea.value;
  8276. if (!options.tabindex && textarea.tabIndex)
  8277. { options.tabindex = textarea.tabIndex; }
  8278. if (!options.placeholder && textarea.placeholder)
  8279. { options.placeholder = textarea.placeholder; }
  8280. // Set autofocus to true if this textarea is focused, or if it has
  8281. // autofocus and no other element is focused.
  8282. if (options.autofocus == null) {
  8283. var hasFocus = activeElt();
  8284. options.autofocus = hasFocus == textarea ||
  8285. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8286. }
  8287. function save() {textarea.value = cm.getValue();}
  8288. var realSubmit;
  8289. if (textarea.form) {
  8290. on(textarea.form, "submit", save);
  8291. // Deplorable hack to make the submit method do the right thing.
  8292. if (!options.leaveSubmitMethodAlone) {
  8293. var form = textarea.form;
  8294. realSubmit = form.submit;
  8295. try {
  8296. var wrappedSubmit = form.submit = function () {
  8297. save();
  8298. form.submit = realSubmit;
  8299. form.submit();
  8300. form.submit = wrappedSubmit;
  8301. };
  8302. } catch(e) {}
  8303. }
  8304. }
  8305. options.finishInit = function (cm) {
  8306. cm.save = save;
  8307. cm.getTextArea = function () { return textarea; };
  8308. cm.toTextArea = function () {
  8309. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8310. save();
  8311. textarea.parentNode.removeChild(cm.getWrapperElement());
  8312. textarea.style.display = "";
  8313. if (textarea.form) {
  8314. off(textarea.form, "submit", save);
  8315. if (typeof textarea.form.submit == "function")
  8316. { textarea.form.submit = realSubmit; }
  8317. }
  8318. };
  8319. };
  8320. textarea.style.display = "none";
  8321. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8322. options);
  8323. return cm
  8324. }
  8325. function addLegacyProps(CodeMirror) {
  8326. CodeMirror.off = off;
  8327. CodeMirror.on = on;
  8328. CodeMirror.wheelEventPixels = wheelEventPixels;
  8329. CodeMirror.Doc = Doc;
  8330. CodeMirror.splitLines = splitLinesAuto;
  8331. CodeMirror.countColumn = countColumn;
  8332. CodeMirror.findColumn = findColumn;
  8333. CodeMirror.isWordChar = isWordCharBasic;
  8334. CodeMirror.Pass = Pass;
  8335. CodeMirror.signal = signal;
  8336. CodeMirror.Line = Line;
  8337. CodeMirror.changeEnd = changeEnd;
  8338. CodeMirror.scrollbarModel = scrollbarModel;
  8339. CodeMirror.Pos = Pos;
  8340. CodeMirror.cmpPos = cmp;
  8341. CodeMirror.modes = modes;
  8342. CodeMirror.mimeModes = mimeModes;
  8343. CodeMirror.resolveMode = resolveMode;
  8344. CodeMirror.getMode = getMode;
  8345. CodeMirror.modeExtensions = modeExtensions;
  8346. CodeMirror.extendMode = extendMode;
  8347. CodeMirror.copyState = copyState;
  8348. CodeMirror.startState = startState;
  8349. CodeMirror.innerMode = innerMode;
  8350. CodeMirror.commands = commands;
  8351. CodeMirror.keyMap = keyMap;
  8352. CodeMirror.keyName = keyName;
  8353. CodeMirror.isModifierKey = isModifierKey;
  8354. CodeMirror.lookupKey = lookupKey;
  8355. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8356. CodeMirror.StringStream = StringStream;
  8357. CodeMirror.SharedTextMarker = SharedTextMarker;
  8358. CodeMirror.TextMarker = TextMarker;
  8359. CodeMirror.LineWidget = LineWidget;
  8360. CodeMirror.e_preventDefault = e_preventDefault;
  8361. CodeMirror.e_stopPropagation = e_stopPropagation;
  8362. CodeMirror.e_stop = e_stop;
  8363. CodeMirror.addClass = addClass;
  8364. CodeMirror.contains = contains;
  8365. CodeMirror.rmClass = rmClass;
  8366. CodeMirror.keyNames = keyNames;
  8367. }
  8368. // EDITOR CONSTRUCTOR
  8369. defineOptions(CodeMirror$1);
  8370. addEditorMethods(CodeMirror$1);
  8371. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8372. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8373. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8374. { CodeMirror$1.prototype[prop] = (function(method) {
  8375. return function() {return method.apply(this.doc, arguments)}
  8376. })(Doc.prototype[prop]); } }
  8377. eventMixin(Doc);
  8378. // INPUT HANDLING
  8379. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8380. // MODE DEFINITION AND QUERYING
  8381. // Extra arguments are stored as the mode's dependencies, which is
  8382. // used by (legacy) mechanisms like loadmode.js to automatically
  8383. // load a mode. (Preferred mechanism is the require/define calls.)
  8384. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  8385. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  8386. defineMode.apply(this, arguments);
  8387. };
  8388. CodeMirror$1.defineMIME = defineMIME;
  8389. // Minimal default mode.
  8390. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8391. CodeMirror$1.defineMIME("text/plain", "null");
  8392. // EXTENSIONS
  8393. CodeMirror$1.defineExtension = function (name, func) {
  8394. CodeMirror$1.prototype[name] = func;
  8395. };
  8396. CodeMirror$1.defineDocExtension = function (name, func) {
  8397. Doc.prototype[name] = func;
  8398. };
  8399. CodeMirror$1.fromTextArea = fromTextArea;
  8400. addLegacyProps(CodeMirror$1);
  8401. CodeMirror$1.version = "5.25.2";
  8402. return CodeMirror$1;
  8403. })));