国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9231 lines
344KB

  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. // This is woefully incomplete. Suggestions for alternative methods welcome.
  32. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  33. var mac = ios || /Mac/.test(platform)
  34. var chromeOS = /\bCrOS\b/.test(userAgent)
  35. var windows = /win/i.test(platform)
  36. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  37. if (presto_version) { presto_version = Number(presto_version[1]) }
  38. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  39. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  40. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  41. var captureRightClick = gecko || (ie && ie_version >= 9)
  42. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  43. var rmClass = function(node, cls) {
  44. var current = node.className
  45. var match = classTest(cls).exec(current)
  46. if (match) {
  47. var after = current.slice(match.index + match[0].length)
  48. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  49. }
  50. }
  51. function removeChildren(e) {
  52. for (var count = e.childNodes.length; count > 0; --count)
  53. { e.removeChild(e.firstChild) }
  54. return e
  55. }
  56. function removeChildrenAndAdd(parent, e) {
  57. return removeChildren(parent).appendChild(e)
  58. }
  59. function elt(tag, content, className, style) {
  60. var e = document.createElement(tag)
  61. if (className) { e.className = className }
  62. if (style) { e.style.cssText = style }
  63. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  64. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  65. return e
  66. }
  67. var range
  68. if (document.createRange) { range = function(node, start, end, endNode) {
  69. var r = document.createRange()
  70. r.setEnd(endNode || node, end)
  71. r.setStart(node, start)
  72. return r
  73. } }
  74. else { range = function(node, start, end) {
  75. var r = document.body.createTextRange()
  76. try { r.moveToElementText(node.parentNode) }
  77. catch(e) { return r }
  78. r.collapse(true)
  79. r.moveEnd("character", end)
  80. r.moveStart("character", start)
  81. return r
  82. } }
  83. function contains(parent, child) {
  84. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  85. { child = child.parentNode }
  86. if (parent.contains)
  87. { return parent.contains(child) }
  88. do {
  89. if (child.nodeType == 11) { child = child.host }
  90. if (child == parent) { return true }
  91. } while (child = child.parentNode)
  92. }
  93. function activeElt() {
  94. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  95. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  96. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  97. var activeElement
  98. try {
  99. activeElement = document.activeElement
  100. } catch(e) {
  101. activeElement = document.body || null
  102. }
  103. while (activeElement && activeElement.root && activeElement.root.activeElement)
  104. { activeElement = activeElement.root.activeElement }
  105. return activeElement
  106. }
  107. function addClass(node, cls) {
  108. var current = node.className
  109. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  110. }
  111. function joinClasses(a, b) {
  112. var as = a.split(" ")
  113. for (var i = 0; i < as.length; i++)
  114. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  115. return b
  116. }
  117. var selectInput = function(node) { node.select() }
  118. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  119. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  120. else if (ie) // Suppress mysterious IE10 errors
  121. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  122. function bind(f) {
  123. var args = Array.prototype.slice.call(arguments, 1)
  124. return function(){return f.apply(null, args)}
  125. }
  126. function copyObj(obj, target, overwrite) {
  127. if (!target) { target = {} }
  128. for (var prop in obj)
  129. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  130. { target[prop] = obj[prop] } }
  131. return target
  132. }
  133. // Counts the column offset in a string, taking tabs into account.
  134. // Used mostly to find indentation.
  135. function countColumn(string, end, tabSize, startIndex, startValue) {
  136. if (end == null) {
  137. end = string.search(/[^\s\u00a0]/)
  138. if (end == -1) { end = string.length }
  139. }
  140. for (var i = startIndex || 0, n = startValue || 0;;) {
  141. var nextTab = string.indexOf("\t", i)
  142. if (nextTab < 0 || nextTab >= end)
  143. { return n + (end - i) }
  144. n += nextTab - i
  145. n += tabSize - (n % tabSize)
  146. i = nextTab + 1
  147. }
  148. }
  149. var Delayed = function() {this.id = null};
  150. Delayed.prototype.set = function (ms, f) {
  151. clearTimeout(this.id)
  152. this.id = setTimeout(f, ms)
  153. };
  154. function indexOf(array, elt) {
  155. for (var i = 0; i < array.length; ++i)
  156. { if (array[i] == elt) { return i } }
  157. return -1
  158. }
  159. // Number of pixels added to scroller and sizer to hide scrollbar
  160. var scrollerGap = 30
  161. // Returned or thrown by various protocols to signal 'I'm not
  162. // handling this'.
  163. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  164. // Reused option objects for setSelection & friends
  165. var sel_dontScroll = {scroll: false};
  166. var sel_mouse = {origin: "*mouse"};
  167. var sel_move = {origin: "+move"};
  168. // The inverse of countColumn -- find the offset that corresponds to
  169. // a particular column.
  170. function findColumn(string, goal, tabSize) {
  171. for (var pos = 0, col = 0;;) {
  172. var nextTab = string.indexOf("\t", pos)
  173. if (nextTab == -1) { nextTab = string.length }
  174. var skipped = nextTab - pos
  175. if (nextTab == string.length || col + skipped >= goal)
  176. { return pos + Math.min(skipped, goal - col) }
  177. col += nextTab - pos
  178. col += tabSize - (col % tabSize)
  179. pos = nextTab + 1
  180. if (col >= goal) { return pos }
  181. }
  182. }
  183. var spaceStrs = [""]
  184. function spaceStr(n) {
  185. while (spaceStrs.length <= n)
  186. { spaceStrs.push(lst(spaceStrs) + " ") }
  187. return spaceStrs[n]
  188. }
  189. function lst(arr) { return arr[arr.length-1] }
  190. function map(array, f) {
  191. var out = []
  192. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  193. return out
  194. }
  195. function insertSorted(array, value, score) {
  196. var pos = 0, priority = score(value)
  197. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  198. array.splice(pos, 0, value)
  199. }
  200. function nothing() {}
  201. function createObj(base, props) {
  202. var inst
  203. if (Object.create) {
  204. inst = Object.create(base)
  205. } else {
  206. nothing.prototype = base
  207. inst = new nothing()
  208. }
  209. if (props) { copyObj(props, inst) }
  210. return inst
  211. }
  212. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  213. function isWordCharBasic(ch) {
  214. return /\w/.test(ch) || ch > "\x80" &&
  215. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  216. }
  217. function isWordChar(ch, helper) {
  218. if (!helper) { return isWordCharBasic(ch) }
  219. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  220. return helper.test(ch)
  221. }
  222. function isEmpty(obj) {
  223. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  224. return true
  225. }
  226. // Extending unicode characters. A series of a non-extending char +
  227. // any number of extending chars is treated as a single unit as far
  228. // as editing and measuring is concerned. This is not fully correct,
  229. // since some scripts/fonts/browsers also treat other configurations
  230. // of code points as a group.
  231. 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]/
  232. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  233. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  234. function skipExtendingChars(str, pos, dir) {
  235. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir }
  236. return pos
  237. }
  238. // Returns the value from the range [`from`; `to`] that satisfies
  239. // `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`.
  240. function findFirst(pred, from, to) {
  241. for (;;) {
  242. if (Math.abs(from - to) <= 1) { return pred(from) ? from : to }
  243. var mid = Math.floor((from + to) / 2)
  244. if (pred(mid)) { to = mid }
  245. else { from = mid }
  246. }
  247. }
  248. // The display handles the DOM integration, both for input reading
  249. // and content drawing. It holds references to DOM nodes and
  250. // display-related state.
  251. function Display(place, doc, input) {
  252. var d = this
  253. this.input = input
  254. // Covers bottom-right square when both scrollbars are present.
  255. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  256. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  257. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  258. // and h scrollbar is present.
  259. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  260. d.gutterFiller.setAttribute("cm-not-content", "true")
  261. // Will contain the actual code, positioned to cover the viewport.
  262. d.lineDiv = elt("div", null, "CodeMirror-code")
  263. // Elements are added to these to represent selection and cursors.
  264. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  265. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  266. // A visibility: hidden element used to find the size of things.
  267. d.measure = elt("div", null, "CodeMirror-measure")
  268. // When lines outside of the viewport are measured, they are drawn in this.
  269. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  270. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  271. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  272. null, "position: relative; outline: none")
  273. // Moved around its parent to cover visible view.
  274. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative")
  275. // Set to the height of the document, allowing scrolling.
  276. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  277. d.sizerWidth = null
  278. // Behavior of elts with overflow: auto and padding is
  279. // inconsistent across browsers. This is used to ensure the
  280. // scrollable area is big enough.
  281. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  282. // Will contain the gutters, if any.
  283. d.gutters = elt("div", null, "CodeMirror-gutters")
  284. d.lineGutter = null
  285. // Actual scrollable element.
  286. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  287. d.scroller.setAttribute("tabIndex", "-1")
  288. // The element in which the editor lives.
  289. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  290. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  291. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  292. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  293. if (place) {
  294. if (place.appendChild) { place.appendChild(d.wrapper) }
  295. else { place(d.wrapper) }
  296. }
  297. // Current rendered range (may be bigger than the view window).
  298. d.viewFrom = d.viewTo = doc.first
  299. d.reportedViewFrom = d.reportedViewTo = doc.first
  300. // Information about the rendered lines.
  301. d.view = []
  302. d.renderedView = null
  303. // Holds info about a single rendered line when it was rendered
  304. // for measurement, while not in view.
  305. d.externalMeasured = null
  306. // Empty space (in pixels) above the view
  307. d.viewOffset = 0
  308. d.lastWrapHeight = d.lastWrapWidth = 0
  309. d.updateLineNumbers = null
  310. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  311. d.scrollbarsClipped = false
  312. // Used to only resize the line number gutter when necessary (when
  313. // the amount of lines crosses a boundary that makes its width change)
  314. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  315. // Set to true when a non-horizontal-scrolling line widget is
  316. // added. As an optimization, line widget aligning is skipped when
  317. // this is false.
  318. d.alignWidgets = false
  319. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  320. // Tracks the maximum line length so that the horizontal scrollbar
  321. // can be kept static when scrolling.
  322. d.maxLine = null
  323. d.maxLineLength = 0
  324. d.maxLineChanged = false
  325. // Used for measuring wheel scrolling granularity
  326. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  327. // True when shift is held down.
  328. d.shift = false
  329. // Used to track whether anything happened since the context menu
  330. // was opened.
  331. d.selForContextMenu = null
  332. d.activeTouch = null
  333. input.init(d)
  334. }
  335. // Find the line object corresponding to the given line number.
  336. function getLine(doc, n) {
  337. n -= doc.first
  338. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  339. var chunk = doc
  340. while (!chunk.lines) {
  341. for (var i = 0;; ++i) {
  342. var child = chunk.children[i], sz = child.chunkSize()
  343. if (n < sz) { chunk = child; break }
  344. n -= sz
  345. }
  346. }
  347. return chunk.lines[n]
  348. }
  349. // Get the part of a document between two positions, as an array of
  350. // strings.
  351. function getBetween(doc, start, end) {
  352. var out = [], n = start.line
  353. doc.iter(start.line, end.line + 1, function (line) {
  354. var text = line.text
  355. if (n == end.line) { text = text.slice(0, end.ch) }
  356. if (n == start.line) { text = text.slice(start.ch) }
  357. out.push(text)
  358. ++n
  359. })
  360. return out
  361. }
  362. // Get the lines between from and to, as array of strings.
  363. function getLines(doc, from, to) {
  364. var out = []
  365. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  366. return out
  367. }
  368. // Update the height of a line, propagating the height change
  369. // upwards to parent nodes.
  370. function updateLineHeight(line, height) {
  371. var diff = height - line.height
  372. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  373. }
  374. // Given a line object, find its line number by walking up through
  375. // its parent links.
  376. function lineNo(line) {
  377. if (line.parent == null) { return null }
  378. var cur = line.parent, no = indexOf(cur.lines, line)
  379. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  380. for (var i = 0;; ++i) {
  381. if (chunk.children[i] == cur) { break }
  382. no += chunk.children[i].chunkSize()
  383. }
  384. }
  385. return no + cur.first
  386. }
  387. // Find the line at the given vertical position, using the height
  388. // information in the document tree.
  389. function lineAtHeight(chunk, h) {
  390. var n = chunk.first
  391. outer: do {
  392. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  393. var child = chunk.children[i$1], ch = child.height
  394. if (h < ch) { chunk = child; continue outer }
  395. h -= ch
  396. n += child.chunkSize()
  397. }
  398. return n
  399. } while (!chunk.lines)
  400. var i = 0
  401. for (; i < chunk.lines.length; ++i) {
  402. var line = chunk.lines[i], lh = line.height
  403. if (h < lh) { break }
  404. h -= lh
  405. }
  406. return n + i
  407. }
  408. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  409. function lineNumberFor(options, i) {
  410. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  411. }
  412. // A Pos instance represents a position within the text.
  413. function Pos(line, ch, sticky) {
  414. if ( sticky === void 0 ) sticky = null;
  415. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  416. this.line = line
  417. this.ch = ch
  418. this.sticky = sticky
  419. }
  420. // Compare two positions, return 0 if they are the same, a negative
  421. // number when a is less, and a positive number otherwise.
  422. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  423. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  424. function copyPos(x) {return Pos(x.line, x.ch)}
  425. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  426. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  427. // Most of the external API clips given positions to make sure they
  428. // actually exist within the document.
  429. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  430. function clipPos(doc, pos) {
  431. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  432. var last = doc.first + doc.size - 1
  433. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  434. return clipToLen(pos, getLine(doc, pos.line).text.length)
  435. }
  436. function clipToLen(pos, linelen) {
  437. var ch = pos.ch
  438. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  439. else if (ch < 0) { return Pos(pos.line, 0) }
  440. else { return pos }
  441. }
  442. function clipPosArray(doc, array) {
  443. var out = []
  444. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  445. return out
  446. }
  447. // Optimize some code when these features are not used.
  448. var sawReadOnlySpans = false;
  449. var sawCollapsedSpans = false;
  450. function seeReadOnlySpans() {
  451. sawReadOnlySpans = true
  452. }
  453. function seeCollapsedSpans() {
  454. sawCollapsedSpans = true
  455. }
  456. // TEXTMARKER SPANS
  457. function MarkedSpan(marker, from, to) {
  458. this.marker = marker
  459. this.from = from; this.to = to
  460. }
  461. // Search an array of spans for a span matching the given marker.
  462. function getMarkedSpanFor(spans, marker) {
  463. if (spans) { for (var i = 0; i < spans.length; ++i) {
  464. var span = spans[i]
  465. if (span.marker == marker) { return span }
  466. } }
  467. }
  468. // Remove a span from an array, returning undefined if no spans are
  469. // left (we don't store arrays for lines without spans).
  470. function removeMarkedSpan(spans, span) {
  471. var r
  472. for (var i = 0; i < spans.length; ++i)
  473. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  474. return r
  475. }
  476. // Add a span to a line.
  477. function addMarkedSpan(line, span) {
  478. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  479. span.marker.attachLine(line)
  480. }
  481. // Used for the algorithm that adjusts markers for a change in the
  482. // document. These functions cut an array of spans at a given
  483. // character position, returning an array of remaining chunks (or
  484. // undefined if nothing remains).
  485. function markedSpansBefore(old, startCh, isInsert) {
  486. var nw
  487. if (old) { for (var i = 0; i < old.length; ++i) {
  488. var span = old[i], marker = span.marker
  489. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  490. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  491. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  492. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  493. }
  494. } }
  495. return nw
  496. }
  497. function markedSpansAfter(old, endCh, isInsert) {
  498. var nw
  499. if (old) { for (var i = 0; i < old.length; ++i) {
  500. var span = old[i], marker = span.marker
  501. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  502. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  503. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  504. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  505. span.to == null ? null : span.to - endCh))
  506. }
  507. } }
  508. return nw
  509. }
  510. // Given a change object, compute the new set of marker spans that
  511. // cover the line in which the change took place. Removes spans
  512. // entirely within the change, reconnects spans belonging to the
  513. // same marker that appear on both sides of the change, and cuts off
  514. // spans partially within the change. Returns an array of span
  515. // arrays with one element for each line in (after) the change.
  516. function stretchSpansOverChange(doc, change) {
  517. if (change.full) { return null }
  518. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  519. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  520. if (!oldFirst && !oldLast) { return null }
  521. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  522. // Get the spans that 'stick out' on both sides
  523. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  524. var last = markedSpansAfter(oldLast, endCh, isInsert)
  525. // Next, merge those two ends
  526. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  527. if (first) {
  528. // Fix up .to properties of first
  529. for (var i = 0; i < first.length; ++i) {
  530. var span = first[i]
  531. if (span.to == null) {
  532. var found = getMarkedSpanFor(last, span.marker)
  533. if (!found) { span.to = startCh }
  534. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  535. }
  536. }
  537. }
  538. if (last) {
  539. // Fix up .from in last (or move them into first in case of sameLine)
  540. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  541. var span$1 = last[i$1]
  542. if (span$1.to != null) { span$1.to += offset }
  543. if (span$1.from == null) {
  544. var found$1 = getMarkedSpanFor(first, span$1.marker)
  545. if (!found$1) {
  546. span$1.from = offset
  547. if (sameLine) { (first || (first = [])).push(span$1) }
  548. }
  549. } else {
  550. span$1.from += offset
  551. if (sameLine) { (first || (first = [])).push(span$1) }
  552. }
  553. }
  554. }
  555. // Make sure we didn't create any zero-length spans
  556. if (first) { first = clearEmptySpans(first) }
  557. if (last && last != first) { last = clearEmptySpans(last) }
  558. var newMarkers = [first]
  559. if (!sameLine) {
  560. // Fill gap with whole-line-spans
  561. var gap = change.text.length - 2, gapMarkers
  562. if (gap > 0 && first)
  563. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  564. { if (first[i$2].to == null)
  565. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  566. for (var i$3 = 0; i$3 < gap; ++i$3)
  567. { newMarkers.push(gapMarkers) }
  568. newMarkers.push(last)
  569. }
  570. return newMarkers
  571. }
  572. // Remove spans that are empty and don't have a clearWhenEmpty
  573. // option of false.
  574. function clearEmptySpans(spans) {
  575. for (var i = 0; i < spans.length; ++i) {
  576. var span = spans[i]
  577. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  578. { spans.splice(i--, 1) }
  579. }
  580. if (!spans.length) { return null }
  581. return spans
  582. }
  583. // Used to 'clip' out readOnly ranges when making a change.
  584. function removeReadOnlyRanges(doc, from, to) {
  585. var markers = null
  586. doc.iter(from.line, to.line + 1, function (line) {
  587. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  588. var mark = line.markedSpans[i].marker
  589. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  590. { (markers || (markers = [])).push(mark) }
  591. } }
  592. })
  593. if (!markers) { return null }
  594. var parts = [{from: from, to: to}]
  595. for (var i = 0; i < markers.length; ++i) {
  596. var mk = markers[i], m = mk.find(0)
  597. for (var j = 0; j < parts.length; ++j) {
  598. var p = parts[j]
  599. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  600. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  601. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  602. { newParts.push({from: p.from, to: m.from}) }
  603. if (dto > 0 || !mk.inclusiveRight && !dto)
  604. { newParts.push({from: m.to, to: p.to}) }
  605. parts.splice.apply(parts, newParts)
  606. j += newParts.length - 3
  607. }
  608. }
  609. return parts
  610. }
  611. // Connect or disconnect spans from a line.
  612. function detachMarkedSpans(line) {
  613. var spans = line.markedSpans
  614. if (!spans) { return }
  615. for (var i = 0; i < spans.length; ++i)
  616. { spans[i].marker.detachLine(line) }
  617. line.markedSpans = null
  618. }
  619. function attachMarkedSpans(line, spans) {
  620. if (!spans) { return }
  621. for (var i = 0; i < spans.length; ++i)
  622. { spans[i].marker.attachLine(line) }
  623. line.markedSpans = spans
  624. }
  625. // Helpers used when computing which overlapping collapsed span
  626. // counts as the larger one.
  627. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  628. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  629. // Returns a number indicating which of two overlapping collapsed
  630. // spans is larger (and thus includes the other). Falls back to
  631. // comparing ids when the spans cover exactly the same range.
  632. function compareCollapsedMarkers(a, b) {
  633. var lenDiff = a.lines.length - b.lines.length
  634. if (lenDiff != 0) { return lenDiff }
  635. var aPos = a.find(), bPos = b.find()
  636. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  637. if (fromCmp) { return -fromCmp }
  638. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  639. if (toCmp) { return toCmp }
  640. return b.id - a.id
  641. }
  642. // Find out whether a line ends or starts in a collapsed span. If
  643. // so, return the marker for that span.
  644. function collapsedSpanAtSide(line, start) {
  645. var sps = sawCollapsedSpans && line.markedSpans, found
  646. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  647. sp = sps[i]
  648. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  649. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  650. { found = sp.marker }
  651. } }
  652. return found
  653. }
  654. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  655. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  656. // Test whether there exists a collapsed span that partially
  657. // overlaps (covers the start or end, but not both) of a new span.
  658. // Such overlap is not allowed.
  659. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  660. var line = getLine(doc, lineNo)
  661. var sps = sawCollapsedSpans && line.markedSpans
  662. if (sps) { for (var i = 0; i < sps.length; ++i) {
  663. var sp = sps[i]
  664. if (!sp.marker.collapsed) { continue }
  665. var found = sp.marker.find(0)
  666. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  667. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  668. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  669. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  670. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  671. { return true }
  672. } }
  673. }
  674. // A visual line is a line as drawn on the screen. Folding, for
  675. // example, can cause multiple logical lines to appear on the same
  676. // visual line. This finds the start of the visual line that the
  677. // given line is part of (usually that is the line itself).
  678. function visualLine(line) {
  679. var merged
  680. while (merged = collapsedSpanAtStart(line))
  681. { line = merged.find(-1, true).line }
  682. return line
  683. }
  684. function visualLineEnd(line) {
  685. var merged
  686. while (merged = collapsedSpanAtEnd(line))
  687. { line = merged.find(1, true).line }
  688. return line
  689. }
  690. // Returns an array of logical lines that continue the visual line
  691. // started by the argument, or undefined if there are no such lines.
  692. function visualLineContinued(line) {
  693. var merged, lines
  694. while (merged = collapsedSpanAtEnd(line)) {
  695. line = merged.find(1, true).line
  696. ;(lines || (lines = [])).push(line)
  697. }
  698. return lines
  699. }
  700. // Get the line number of the start of the visual line that the
  701. // given line number is part of.
  702. function visualLineNo(doc, lineN) {
  703. var line = getLine(doc, lineN), vis = visualLine(line)
  704. if (line == vis) { return lineN }
  705. return lineNo(vis)
  706. }
  707. // Get the line number of the start of the next visual line after
  708. // the given line.
  709. function visualLineEndNo(doc, lineN) {
  710. if (lineN > doc.lastLine()) { return lineN }
  711. var line = getLine(doc, lineN), merged
  712. if (!lineIsHidden(doc, line)) { return lineN }
  713. while (merged = collapsedSpanAtEnd(line))
  714. { line = merged.find(1, true).line }
  715. return lineNo(line) + 1
  716. }
  717. // Compute whether a line is hidden. Lines count as hidden when they
  718. // are part of a visual line that starts with another line, or when
  719. // they are entirely covered by collapsed, non-widget span.
  720. function lineIsHidden(doc, line) {
  721. var sps = sawCollapsedSpans && line.markedSpans
  722. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  723. sp = sps[i]
  724. if (!sp.marker.collapsed) { continue }
  725. if (sp.from == null) { return true }
  726. if (sp.marker.widgetNode) { continue }
  727. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  728. { return true }
  729. } }
  730. }
  731. function lineIsHiddenInner(doc, line, span) {
  732. if (span.to == null) {
  733. var end = span.marker.find(1, true)
  734. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  735. }
  736. if (span.marker.inclusiveRight && span.to == line.text.length)
  737. { return true }
  738. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  739. sp = line.markedSpans[i]
  740. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  741. (sp.to == null || sp.to != span.from) &&
  742. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  743. lineIsHiddenInner(doc, line, sp)) { return true }
  744. }
  745. }
  746. // Find the height above the given line.
  747. function heightAtLine(lineObj) {
  748. lineObj = visualLine(lineObj)
  749. var h = 0, chunk = lineObj.parent
  750. for (var i = 0; i < chunk.lines.length; ++i) {
  751. var line = chunk.lines[i]
  752. if (line == lineObj) { break }
  753. else { h += line.height }
  754. }
  755. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  756. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  757. var cur = p.children[i$1]
  758. if (cur == chunk) { break }
  759. else { h += cur.height }
  760. }
  761. }
  762. return h
  763. }
  764. // Compute the character length of a line, taking into account
  765. // collapsed ranges (see markText) that might hide parts, and join
  766. // other lines onto it.
  767. function lineLength(line) {
  768. if (line.height == 0) { return 0 }
  769. var len = line.text.length, merged, cur = line
  770. while (merged = collapsedSpanAtStart(cur)) {
  771. var found = merged.find(0, true)
  772. cur = found.from.line
  773. len += found.from.ch - found.to.ch
  774. }
  775. cur = line
  776. while (merged = collapsedSpanAtEnd(cur)) {
  777. var found$1 = merged.find(0, true)
  778. len -= cur.text.length - found$1.from.ch
  779. cur = found$1.to.line
  780. len += cur.text.length - found$1.to.ch
  781. }
  782. return len
  783. }
  784. // Find the longest line in the document.
  785. function findMaxLine(cm) {
  786. var d = cm.display, doc = cm.doc
  787. d.maxLine = getLine(doc, doc.first)
  788. d.maxLineLength = lineLength(d.maxLine)
  789. d.maxLineChanged = true
  790. doc.iter(function (line) {
  791. var len = lineLength(line)
  792. if (len > d.maxLineLength) {
  793. d.maxLineLength = len
  794. d.maxLine = line
  795. }
  796. })
  797. }
  798. // BIDI HELPERS
  799. function iterateBidiSections(order, from, to, f) {
  800. if (!order) { return f(from, to, "ltr") }
  801. var found = false
  802. for (var i = 0; i < order.length; ++i) {
  803. var part = order[i]
  804. if (part.from < to && part.to > from || from == to && part.to == from) {
  805. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
  806. found = true
  807. }
  808. }
  809. if (!found) { f(from, to, "ltr") }
  810. }
  811. var bidiOther = null
  812. function getBidiPartAt(order, ch, sticky) {
  813. var found
  814. bidiOther = null
  815. for (var i = 0; i < order.length; ++i) {
  816. var cur = order[i]
  817. if (cur.from < ch && cur.to > ch) { return i }
  818. if (cur.to == ch) {
  819. if (cur.from != cur.to && sticky == "before") { found = i }
  820. else { bidiOther = i }
  821. }
  822. if (cur.from == ch) {
  823. if (cur.from != cur.to && sticky != "before") { found = i }
  824. else { bidiOther = i }
  825. }
  826. }
  827. return found != null ? found : bidiOther
  828. }
  829. // Bidirectional ordering algorithm
  830. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  831. // that this (partially) implements.
  832. // One-char codes used for character types:
  833. // L (L): Left-to-Right
  834. // R (R): Right-to-Left
  835. // r (AL): Right-to-Left Arabic
  836. // 1 (EN): European Number
  837. // + (ES): European Number Separator
  838. // % (ET): European Number Terminator
  839. // n (AN): Arabic Number
  840. // , (CS): Common Number Separator
  841. // m (NSM): Non-Spacing Mark
  842. // b (BN): Boundary Neutral
  843. // s (B): Paragraph Separator
  844. // t (S): Segment Separator
  845. // w (WS): Whitespace
  846. // N (ON): Other Neutrals
  847. // Returns null if characters are ordered as they appear
  848. // (left-to-right), or an array of sections ({from, to, level}
  849. // objects) in the order in which they occur visually.
  850. var bidiOrdering = (function() {
  851. // Character types for codepoints 0 to 0xff
  852. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  853. // Character types for codepoints 0x600 to 0x6f9
  854. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  855. function charType(code) {
  856. if (code <= 0xf7) { return lowTypes.charAt(code) }
  857. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  858. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  859. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  860. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  861. else if (code == 0x200c) { return "b" }
  862. else { return "L" }
  863. }
  864. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  865. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  866. // Browsers seem to always treat the boundaries of block elements as being L.
  867. var outerType = "L"
  868. function BidiSpan(level, from, to) {
  869. this.level = level
  870. this.from = from; this.to = to
  871. }
  872. return function(str) {
  873. if (!bidiRE.test(str)) { return false }
  874. var len = str.length, types = []
  875. for (var i = 0; i < len; ++i)
  876. { types.push(charType(str.charCodeAt(i))) }
  877. // W1. Examine each non-spacing mark (NSM) in the level run, and
  878. // change the type of the NSM to the type of the previous
  879. // character. If the NSM is at the start of the level run, it will
  880. // get the type of sor.
  881. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  882. var type = types[i$1]
  883. if (type == "m") { types[i$1] = prev }
  884. else { prev = type }
  885. }
  886. // W2. Search backwards from each instance of a European number
  887. // until the first strong type (R, L, AL, or sor) is found. If an
  888. // AL is found, change the type of the European number to Arabic
  889. // number.
  890. // W3. Change all ALs to R.
  891. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  892. var type$1 = types[i$2]
  893. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  894. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  895. }
  896. // W4. A single European separator between two European numbers
  897. // changes to a European number. A single common separator between
  898. // two numbers of the same type changes to that type.
  899. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  900. var type$2 = types[i$3]
  901. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  902. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  903. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  904. prev$1 = type$2
  905. }
  906. // W5. A sequence of European terminators adjacent to European
  907. // numbers changes to all European numbers.
  908. // W6. Otherwise, separators and terminators change to Other
  909. // Neutral.
  910. for (var i$4 = 0; i$4 < len; ++i$4) {
  911. var type$3 = types[i$4]
  912. if (type$3 == ",") { types[i$4] = "N" }
  913. else if (type$3 == "%") {
  914. var end = (void 0)
  915. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  916. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  917. for (var j = i$4; j < end; ++j) { types[j] = replace }
  918. i$4 = end - 1
  919. }
  920. }
  921. // W7. Search backwards from each instance of a European number
  922. // until the first strong type (R, L, or sor) is found. If an L is
  923. // found, then change the type of the European number to L.
  924. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  925. var type$4 = types[i$5]
  926. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  927. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  928. }
  929. // N1. A sequence of neutrals takes the direction of the
  930. // surrounding strong text if the text on both sides has the same
  931. // direction. European and Arabic numbers act as if they were R in
  932. // terms of their influence on neutrals. Start-of-level-run (sor)
  933. // and end-of-level-run (eor) are used at level run boundaries.
  934. // N2. Any remaining neutrals take the embedding direction.
  935. for (var i$6 = 0; i$6 < len; ++i$6) {
  936. if (isNeutral.test(types[i$6])) {
  937. var end$1 = (void 0)
  938. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  939. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  940. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  941. var replace$1 = before || after ? "L" : "R"
  942. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  943. i$6 = end$1 - 1
  944. }
  945. }
  946. // Here we depart from the documented algorithm, in order to avoid
  947. // building up an actual levels array. Since there are only three
  948. // levels (0, 1, 2) in an implementation that doesn't take
  949. // explicit embedding into account, we can build up the order on
  950. // the fly, without following the level-based algorithm.
  951. var order = [], m
  952. for (var i$7 = 0; i$7 < len;) {
  953. if (countsAsLeft.test(types[i$7])) {
  954. var start = i$7
  955. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  956. order.push(new BidiSpan(0, start, i$7))
  957. } else {
  958. var pos = i$7, at = order.length
  959. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  960. for (var j$2 = pos; j$2 < i$7;) {
  961. if (countsAsNum.test(types[j$2])) {
  962. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  963. var nstart = j$2
  964. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  965. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  966. pos = j$2
  967. } else { ++j$2 }
  968. }
  969. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  970. }
  971. }
  972. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  973. order[0].from = m[0].length
  974. order.unshift(new BidiSpan(0, 0, m[0].length))
  975. }
  976. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  977. lst(order).to -= m[0].length
  978. order.push(new BidiSpan(0, len - m[0].length, len))
  979. }
  980. return order
  981. }
  982. })()
  983. // Get the bidi ordering for the given line (and cache it). Returns
  984. // false for lines that are fully left-to-right, and an array of
  985. // BidiSpan objects otherwise.
  986. function getOrder(line) {
  987. var order = line.order
  988. if (order == null) { order = line.order = bidiOrdering(line.text) }
  989. return order
  990. }
  991. function moveCharLogically(line, ch, dir) {
  992. var target = skipExtendingChars(line.text, ch + dir, dir)
  993. return target < 0 || target > line.text.length ? null : target
  994. }
  995. function moveLogically(line, start, dir) {
  996. var ch = moveCharLogically(line, start.ch, dir)
  997. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  998. }
  999. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  1000. if (visually) {
  1001. var order = getOrder(lineObj)
  1002. if (order) {
  1003. var part = dir < 0 ? lst(order) : order[0]
  1004. var moveInStorageOrder = (dir < 0) == (part.level == 1)
  1005. var sticky = moveInStorageOrder ? "after" : "before"
  1006. var ch
  1007. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  1008. // it could be that the last bidi part is not on the last visual line,
  1009. // since visual lines contain content order-consecutive chunks.
  1010. // Thus, in rtl, we are looking for the first (content-order) character
  1011. // in the rtl chunk that is on the last line (that is, the same line
  1012. // as the last (content-order) character).
  1013. if (part.level > 0) {
  1014. var prep = prepareMeasureForLine(cm, lineObj)
  1015. ch = dir < 0 ? lineObj.text.length - 1 : 0
  1016. var targetTop = measureCharPrepared(cm, prep, ch).top
  1017. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
  1018. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1, true) }
  1019. } else { ch = dir < 0 ? part.to : part.from }
  1020. return new Pos(lineNo, ch, sticky)
  1021. }
  1022. }
  1023. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  1024. }
  1025. function moveVisually(cm, line, start, dir) {
  1026. var bidi = getOrder(line)
  1027. if (!bidi) { return moveLogically(line, start, dir) }
  1028. if (start.ch >= line.text.length) {
  1029. start.ch = line.text.length
  1030. start.sticky = "before"
  1031. } else if (start.ch <= 0) {
  1032. start.ch = 0
  1033. start.sticky = "after"
  1034. }
  1035. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
  1036. if (part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  1037. // Case 1: We move within an ltr part. Even with wrapped lines,
  1038. // nothing interesting happens.
  1039. return moveLogically(line, start, dir)
  1040. }
  1041. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
  1042. var prep
  1043. var getWrappedLineExtent = function (ch) {
  1044. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  1045. prep = prep || prepareMeasureForLine(cm, line)
  1046. return wrappedLineExtentChar(cm, line, prep, ch)
  1047. }
  1048. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
  1049. if (part.level % 2 == 1) {
  1050. var ch = mv(start, -dir)
  1051. if (ch != null && (dir > 0 ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  1052. // Case 2: We move within an rtl part on the same visual line
  1053. var sticky = dir < 0 ? "before" : "after"
  1054. return new Pos(start.line, ch, sticky)
  1055. }
  1056. }
  1057. // Case 3: Could not move within this bidi part in this visual line, so leave
  1058. // the current bidi part
  1059. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  1060. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  1061. ? new Pos(start.line, mv(ch, 1), "before")
  1062. : new Pos(start.line, ch, "after"); }
  1063. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  1064. var part = bidi[partPos]
  1065. var moveInStorageOrder = (dir > 0) == (part.level != 1)
  1066. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  1067. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  1068. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  1069. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  1070. }
  1071. }
  1072. // Case 3a: Look for other bidi parts on the same visual line
  1073. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  1074. if (res) { return res }
  1075. // Case 3b: Look for other bidi parts on the next visual line
  1076. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  1077. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  1078. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  1079. if (res) { return res }
  1080. }
  1081. // Case 4: Nowhere to move
  1082. return null
  1083. }
  1084. // EVENT HANDLING
  1085. // Lightweight event framework. on/off also work on DOM nodes,
  1086. // registering native DOM handlers.
  1087. var noHandlers = []
  1088. var on = function(emitter, type, f) {
  1089. if (emitter.addEventListener) {
  1090. emitter.addEventListener(type, f, false)
  1091. } else if (emitter.attachEvent) {
  1092. emitter.attachEvent("on" + type, f)
  1093. } else {
  1094. var map = emitter._handlers || (emitter._handlers = {})
  1095. map[type] = (map[type] || noHandlers).concat(f)
  1096. }
  1097. }
  1098. function getHandlers(emitter, type) {
  1099. return emitter._handlers && emitter._handlers[type] || noHandlers
  1100. }
  1101. function off(emitter, type, f) {
  1102. if (emitter.removeEventListener) {
  1103. emitter.removeEventListener(type, f, false)
  1104. } else if (emitter.detachEvent) {
  1105. emitter.detachEvent("on" + type, f)
  1106. } else {
  1107. var map = emitter._handlers, arr = map && map[type]
  1108. if (arr) {
  1109. var index = indexOf(arr, f)
  1110. if (index > -1)
  1111. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1112. }
  1113. }
  1114. }
  1115. function signal(emitter, type /*, values...*/) {
  1116. var handlers = getHandlers(emitter, type)
  1117. if (!handlers.length) { return }
  1118. var args = Array.prototype.slice.call(arguments, 2)
  1119. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1120. }
  1121. // The DOM events that CodeMirror handles can be overridden by
  1122. // registering a (non-DOM) handler on the editor for the event name,
  1123. // and preventDefault-ing the event in that handler.
  1124. function signalDOMEvent(cm, e, override) {
  1125. if (typeof e == "string")
  1126. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1127. signal(cm, override || e.type, cm, e)
  1128. return e_defaultPrevented(e) || e.codemirrorIgnore
  1129. }
  1130. function signalCursorActivity(cm) {
  1131. var arr = cm._handlers && cm._handlers.cursorActivity
  1132. if (!arr) { return }
  1133. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1134. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1135. { set.push(arr[i]) } }
  1136. }
  1137. function hasHandler(emitter, type) {
  1138. return getHandlers(emitter, type).length > 0
  1139. }
  1140. // Add on and off methods to a constructor's prototype, to make
  1141. // registering events on such objects more convenient.
  1142. function eventMixin(ctor) {
  1143. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1144. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1145. }
  1146. // Due to the fact that we still support jurassic IE versions, some
  1147. // compatibility wrappers are needed.
  1148. function e_preventDefault(e) {
  1149. if (e.preventDefault) { e.preventDefault() }
  1150. else { e.returnValue = false }
  1151. }
  1152. function e_stopPropagation(e) {
  1153. if (e.stopPropagation) { e.stopPropagation() }
  1154. else { e.cancelBubble = true }
  1155. }
  1156. function e_defaultPrevented(e) {
  1157. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1158. }
  1159. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1160. function e_target(e) {return e.target || e.srcElement}
  1161. function e_button(e) {
  1162. var b = e.which
  1163. if (b == null) {
  1164. if (e.button & 1) { b = 1 }
  1165. else if (e.button & 2) { b = 3 }
  1166. else if (e.button & 4) { b = 2 }
  1167. }
  1168. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1169. return b
  1170. }
  1171. // Detect drag-and-drop
  1172. var dragAndDrop = function() {
  1173. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1174. // couldn't get it to work yet.
  1175. if (ie && ie_version < 9) { return false }
  1176. var div = elt('div')
  1177. return "draggable" in div || "dragDrop" in div
  1178. }()
  1179. var zwspSupported
  1180. function zeroWidthElement(measure) {
  1181. if (zwspSupported == null) {
  1182. var test = elt("span", "\u200b")
  1183. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1184. if (measure.firstChild.offsetHeight != 0)
  1185. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1186. }
  1187. var node = zwspSupported ? elt("span", "\u200b") :
  1188. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1189. node.setAttribute("cm-text", "")
  1190. return node
  1191. }
  1192. // Feature-detect IE's crummy client rect reporting for bidi text
  1193. var badBidiRects
  1194. function hasBadBidiRects(measure) {
  1195. if (badBidiRects != null) { return badBidiRects }
  1196. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1197. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1198. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1199. removeChildren(measure)
  1200. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1201. return badBidiRects = (r1.right - r0.right < 3)
  1202. }
  1203. // See if "".split is the broken IE version, if so, provide an
  1204. // alternative way to split lines.
  1205. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1206. var pos = 0, result = [], l = string.length
  1207. while (pos <= l) {
  1208. var nl = string.indexOf("\n", pos)
  1209. if (nl == -1) { nl = string.length }
  1210. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1211. var rt = line.indexOf("\r")
  1212. if (rt != -1) {
  1213. result.push(line.slice(0, rt))
  1214. pos += rt + 1
  1215. } else {
  1216. result.push(line)
  1217. pos = nl + 1
  1218. }
  1219. }
  1220. return result
  1221. } : function (string) { return string.split(/\r\n?|\n/); }
  1222. var hasSelection = window.getSelection ? function (te) {
  1223. try { return te.selectionStart != te.selectionEnd }
  1224. catch(e) { return false }
  1225. } : function (te) {
  1226. var range
  1227. try {range = te.ownerDocument.selection.createRange()}
  1228. catch(e) {}
  1229. if (!range || range.parentElement() != te) { return false }
  1230. return range.compareEndPoints("StartToEnd", range) != 0
  1231. }
  1232. var hasCopyEvent = (function () {
  1233. var e = elt("div")
  1234. if ("oncopy" in e) { return true }
  1235. e.setAttribute("oncopy", "return;")
  1236. return typeof e.oncopy == "function"
  1237. })()
  1238. var badZoomedRects = null
  1239. function hasBadZoomedRects(measure) {
  1240. if (badZoomedRects != null) { return badZoomedRects }
  1241. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1242. var normal = node.getBoundingClientRect()
  1243. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1244. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1245. }
  1246. var modes = {};
  1247. var mimeModes = {};
  1248. // Extra arguments are stored as the mode's dependencies, which is
  1249. // used by (legacy) mechanisms like loadmode.js to automatically
  1250. // load a mode. (Preferred mechanism is the require/define calls.)
  1251. function defineMode(name, mode) {
  1252. if (arguments.length > 2)
  1253. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1254. modes[name] = mode
  1255. }
  1256. function defineMIME(mime, spec) {
  1257. mimeModes[mime] = spec
  1258. }
  1259. // Given a MIME type, a {name, ...options} config object, or a name
  1260. // string, return a mode config object.
  1261. function resolveMode(spec) {
  1262. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1263. spec = mimeModes[spec]
  1264. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1265. var found = mimeModes[spec.name]
  1266. if (typeof found == "string") { found = {name: found} }
  1267. spec = createObj(found, spec)
  1268. spec.name = found.name
  1269. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1270. return resolveMode("application/xml")
  1271. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1272. return resolveMode("application/json")
  1273. }
  1274. if (typeof spec == "string") { return {name: spec} }
  1275. else { return spec || {name: "null"} }
  1276. }
  1277. // Given a mode spec (anything that resolveMode accepts), find and
  1278. // initialize an actual mode object.
  1279. function getMode(options, spec) {
  1280. spec = resolveMode(spec)
  1281. var mfactory = modes[spec.name]
  1282. if (!mfactory) { return getMode(options, "text/plain") }
  1283. var modeObj = mfactory(options, spec)
  1284. if (modeExtensions.hasOwnProperty(spec.name)) {
  1285. var exts = modeExtensions[spec.name]
  1286. for (var prop in exts) {
  1287. if (!exts.hasOwnProperty(prop)) { continue }
  1288. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1289. modeObj[prop] = exts[prop]
  1290. }
  1291. }
  1292. modeObj.name = spec.name
  1293. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1294. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1295. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1296. return modeObj
  1297. }
  1298. // This can be used to attach properties to mode objects from
  1299. // outside the actual mode definition.
  1300. var modeExtensions = {}
  1301. function extendMode(mode, properties) {
  1302. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1303. copyObj(properties, exts)
  1304. }
  1305. function copyState(mode, state) {
  1306. if (state === true) { return state }
  1307. if (mode.copyState) { return mode.copyState(state) }
  1308. var nstate = {}
  1309. for (var n in state) {
  1310. var val = state[n]
  1311. if (val instanceof Array) { val = val.concat([]) }
  1312. nstate[n] = val
  1313. }
  1314. return nstate
  1315. }
  1316. // Given a mode and a state (for that mode), find the inner mode and
  1317. // state at the position that the state refers to.
  1318. function innerMode(mode, state) {
  1319. var info
  1320. while (mode.innerMode) {
  1321. info = mode.innerMode(state)
  1322. if (!info || info.mode == mode) { break }
  1323. state = info.state
  1324. mode = info.mode
  1325. }
  1326. return info || {mode: mode, state: state}
  1327. }
  1328. function startState(mode, a1, a2) {
  1329. return mode.startState ? mode.startState(a1, a2) : true
  1330. }
  1331. // STRING STREAM
  1332. // Fed to the mode parsers, provides helper functions to make
  1333. // parsers more succinct.
  1334. var StringStream = function(string, tabSize) {
  1335. this.pos = this.start = 0
  1336. this.string = string
  1337. this.tabSize = tabSize || 8
  1338. this.lastColumnPos = this.lastColumnValue = 0
  1339. this.lineStart = 0
  1340. };
  1341. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1342. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1343. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1344. StringStream.prototype.next = function () {
  1345. if (this.pos < this.string.length)
  1346. { return this.string.charAt(this.pos++) }
  1347. };
  1348. StringStream.prototype.eat = function (match) {
  1349. var ch = this.string.charAt(this.pos)
  1350. var ok
  1351. if (typeof match == "string") { ok = ch == match }
  1352. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1353. if (ok) {++this.pos; return ch}
  1354. };
  1355. StringStream.prototype.eatWhile = function (match) {
  1356. var start = this.pos
  1357. while (this.eat(match)){}
  1358. return this.pos > start
  1359. };
  1360. StringStream.prototype.eatSpace = function () {
  1361. var this$1 = this;
  1362. var start = this.pos
  1363. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1364. return this.pos > start
  1365. };
  1366. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
  1367. StringStream.prototype.skipTo = function (ch) {
  1368. var found = this.string.indexOf(ch, this.pos)
  1369. if (found > -1) {this.pos = found; return true}
  1370. };
  1371. StringStream.prototype.backUp = function (n) {this.pos -= n};
  1372. StringStream.prototype.column = function () {
  1373. if (this.lastColumnPos < this.start) {
  1374. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1375. this.lastColumnPos = this.start
  1376. }
  1377. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1378. };
  1379. StringStream.prototype.indentation = function () {
  1380. return countColumn(this.string, null, this.tabSize) -
  1381. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1382. };
  1383. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1384. if (typeof pattern == "string") {
  1385. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1386. var substr = this.string.substr(this.pos, pattern.length)
  1387. if (cased(substr) == cased(pattern)) {
  1388. if (consume !== false) { this.pos += pattern.length }
  1389. return true
  1390. }
  1391. } else {
  1392. var match = this.string.slice(this.pos).match(pattern)
  1393. if (match && match.index > 0) { return null }
  1394. if (match && consume !== false) { this.pos += match[0].length }
  1395. return match
  1396. }
  1397. };
  1398. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1399. StringStream.prototype.hideFirstChars = function (n, inner) {
  1400. this.lineStart += n
  1401. try { return inner() }
  1402. finally { this.lineStart -= n }
  1403. };
  1404. // Compute a style array (an array starting with a mode generation
  1405. // -- for invalidation -- followed by pairs of end positions and
  1406. // style strings), which is used to highlight the tokens on the
  1407. // line.
  1408. function highlightLine(cm, line, state, forceToEnd) {
  1409. // A styles array always starts with a number identifying the
  1410. // mode/overlays that it is based on (for easy invalidation).
  1411. var st = [cm.state.modeGen], lineClasses = {}
  1412. // Compute the base array of styles
  1413. runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); },
  1414. lineClasses, forceToEnd)
  1415. // Run overlays, adjust style array.
  1416. var loop = function ( o ) {
  1417. var overlay = cm.state.overlays[o], i = 1, at = 0
  1418. runMode(cm, line.text, overlay.mode, true, function (end, style) {
  1419. var start = i
  1420. // Ensure there's a token end at the current position, and that i points at it
  1421. while (at < end) {
  1422. var i_end = st[i]
  1423. if (i_end > end)
  1424. { st.splice(i, 1, end, st[i+1], i_end) }
  1425. i += 2
  1426. at = Math.min(end, i_end)
  1427. }
  1428. if (!style) { return }
  1429. if (overlay.opaque) {
  1430. st.splice(start, i - start, end, "overlay " + style)
  1431. i = start + 2
  1432. } else {
  1433. for (; start < i; start += 2) {
  1434. var cur = st[start+1]
  1435. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1436. }
  1437. }
  1438. }, lineClasses)
  1439. };
  1440. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1441. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1442. }
  1443. function getLineStyles(cm, line, updateFrontier) {
  1444. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1445. var state = getStateBefore(cm, lineNo(line))
  1446. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state)
  1447. line.stateAfter = state
  1448. line.styles = result.styles
  1449. if (result.classes) { line.styleClasses = result.classes }
  1450. else if (line.styleClasses) { line.styleClasses = null }
  1451. if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ }
  1452. }
  1453. return line.styles
  1454. }
  1455. function getStateBefore(cm, n, precise) {
  1456. var doc = cm.doc, display = cm.display
  1457. if (!doc.mode.startState) { return true }
  1458. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter
  1459. if (!state) { state = startState(doc.mode) }
  1460. else { state = copyState(doc.mode, state) }
  1461. doc.iter(pos, n, function (line) {
  1462. processLine(cm, line.text, state)
  1463. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo
  1464. line.stateAfter = save ? copyState(doc.mode, state) : null
  1465. ++pos
  1466. })
  1467. if (precise) { doc.frontier = pos }
  1468. return state
  1469. }
  1470. // Lightweight form of highlight -- proceed over this line and
  1471. // update state, but don't save a style array. Used for lines that
  1472. // aren't currently visible.
  1473. function processLine(cm, text, state, startAt) {
  1474. var mode = cm.doc.mode
  1475. var stream = new StringStream(text, cm.options.tabSize)
  1476. stream.start = stream.pos = startAt || 0
  1477. if (text == "") { callBlankLine(mode, state) }
  1478. while (!stream.eol()) {
  1479. readToken(mode, stream, state)
  1480. stream.start = stream.pos
  1481. }
  1482. }
  1483. function callBlankLine(mode, state) {
  1484. if (mode.blankLine) { return mode.blankLine(state) }
  1485. if (!mode.innerMode) { return }
  1486. var inner = innerMode(mode, state)
  1487. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1488. }
  1489. function readToken(mode, stream, state, inner) {
  1490. for (var i = 0; i < 10; i++) {
  1491. if (inner) { inner[0] = innerMode(mode, state).mode }
  1492. var style = mode.token(stream, state)
  1493. if (stream.pos > stream.start) { return style }
  1494. }
  1495. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1496. }
  1497. // Utility for getTokenAt and getLineTokens
  1498. function takeToken(cm, pos, precise, asArray) {
  1499. var getObj = function (copy) { return ({
  1500. start: stream.start, end: stream.pos,
  1501. string: stream.current(),
  1502. type: style || null,
  1503. state: copy ? copyState(doc.mode, state) : state
  1504. }); }
  1505. var doc = cm.doc, mode = doc.mode, style
  1506. pos = clipPos(doc, pos)
  1507. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise)
  1508. var stream = new StringStream(line.text, cm.options.tabSize), tokens
  1509. if (asArray) { tokens = [] }
  1510. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1511. stream.start = stream.pos
  1512. style = readToken(mode, stream, state)
  1513. if (asArray) { tokens.push(getObj(true)) }
  1514. }
  1515. return asArray ? tokens : getObj()
  1516. }
  1517. function extractLineClasses(type, output) {
  1518. if (type) { for (;;) {
  1519. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1520. if (!lineClass) { break }
  1521. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1522. var prop = lineClass[1] ? "bgClass" : "textClass"
  1523. if (output[prop] == null)
  1524. { output[prop] = lineClass[2] }
  1525. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1526. { output[prop] += " " + lineClass[2] }
  1527. } }
  1528. return type
  1529. }
  1530. // Run the given mode's parser over a line, calling f for each token.
  1531. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  1532. var flattenSpans = mode.flattenSpans
  1533. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1534. var curStart = 0, curStyle = null
  1535. var stream = new StringStream(text, cm.options.tabSize), style
  1536. var inner = cm.options.addModeClass && [null]
  1537. if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) }
  1538. while (!stream.eol()) {
  1539. if (stream.pos > cm.options.maxHighlightLength) {
  1540. flattenSpans = false
  1541. if (forceToEnd) { processLine(cm, text, state, stream.pos) }
  1542. stream.pos = text.length
  1543. style = null
  1544. } else {
  1545. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses)
  1546. }
  1547. if (inner) {
  1548. var mName = inner[0].name
  1549. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1550. }
  1551. if (!flattenSpans || curStyle != style) {
  1552. while (curStart < stream.start) {
  1553. curStart = Math.min(stream.start, curStart + 5000)
  1554. f(curStart, curStyle)
  1555. }
  1556. curStyle = style
  1557. }
  1558. stream.start = stream.pos
  1559. }
  1560. while (curStart < stream.pos) {
  1561. // Webkit seems to refuse to render text nodes longer than 57444
  1562. // characters, and returns inaccurate measurements in nodes
  1563. // starting around 5000 chars.
  1564. var pos = Math.min(stream.pos, curStart + 5000)
  1565. f(pos, curStyle)
  1566. curStart = pos
  1567. }
  1568. }
  1569. // Finds the line to start with when starting a parse. Tries to
  1570. // find a line with a stateAfter, so that it can start with a
  1571. // valid state. If that fails, it returns the line with the
  1572. // smallest indentation, which tends to need the least context to
  1573. // parse correctly.
  1574. function findStartLine(cm, n, precise) {
  1575. var minindent, minline, doc = cm.doc
  1576. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1577. for (var search = n; search > lim; --search) {
  1578. if (search <= doc.first) { return doc.first }
  1579. var line = getLine(doc, search - 1)
  1580. if (line.stateAfter && (!precise || search <= doc.frontier)) { return search }
  1581. var indented = countColumn(line.text, null, cm.options.tabSize)
  1582. if (minline == null || minindent > indented) {
  1583. minline = search - 1
  1584. minindent = indented
  1585. }
  1586. }
  1587. return minline
  1588. }
  1589. // LINE DATA STRUCTURE
  1590. // Line objects. These hold state related to a line, including
  1591. // highlighting info (the styles array).
  1592. var Line = function(text, markedSpans, estimateHeight) {
  1593. this.text = text
  1594. attachMarkedSpans(this, markedSpans)
  1595. this.height = estimateHeight ? estimateHeight(this) : 1
  1596. };
  1597. Line.prototype.lineNo = function () { return lineNo(this) };
  1598. eventMixin(Line)
  1599. // Change the content (text, markers) of a line. Automatically
  1600. // invalidates cached information and tries to re-estimate the
  1601. // line's height.
  1602. function updateLine(line, text, markedSpans, estimateHeight) {
  1603. line.text = text
  1604. if (line.stateAfter) { line.stateAfter = null }
  1605. if (line.styles) { line.styles = null }
  1606. if (line.order != null) { line.order = null }
  1607. detachMarkedSpans(line)
  1608. attachMarkedSpans(line, markedSpans)
  1609. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1610. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1611. }
  1612. // Detach a line from the document tree and its markers.
  1613. function cleanUpLine(line) {
  1614. line.parent = null
  1615. detachMarkedSpans(line)
  1616. }
  1617. // Convert a style as returned by a mode (either null, or a string
  1618. // containing one or more styles) to a CSS style. This is cached,
  1619. // and also looks for line-wide styles.
  1620. var styleToClassCache = {};
  1621. var styleToClassCacheWithMode = {};
  1622. function interpretTokenStyle(style, options) {
  1623. if (!style || /^\s*$/.test(style)) { return null }
  1624. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1625. return cache[style] ||
  1626. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1627. }
  1628. // Render the DOM representation of the text of a line. Also builds
  1629. // up a 'line map', which points at the DOM nodes that represent
  1630. // specific stretches of text, and is used by the measuring code.
  1631. // The returned object contains the DOM node, this map, and
  1632. // information about line-wide styles that were set by the mode.
  1633. function buildLineContent(cm, lineView) {
  1634. // The padding-right forces the element to have a 'border', which
  1635. // is needed on Webkit to be able to get line-level bounding
  1636. // rectangles for it (in measureChar).
  1637. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null)
  1638. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  1639. col: 0, pos: 0, cm: cm,
  1640. trailingSpace: false,
  1641. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1642. // hide from accessibility tree
  1643. content.setAttribute("role", "presentation")
  1644. builder.pre.setAttribute("role", "presentation")
  1645. lineView.measure = {}
  1646. // Iterate over the logical lines that make up this visual line.
  1647. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1648. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1649. builder.pos = 0
  1650. builder.addToken = buildToken
  1651. // Optionally wire in some hacks into the token-rendering
  1652. // algorithm, to deal with browser quirks.
  1653. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  1654. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1655. builder.map = []
  1656. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1657. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1658. if (line.styleClasses) {
  1659. if (line.styleClasses.bgClass)
  1660. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1661. if (line.styleClasses.textClass)
  1662. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1663. }
  1664. // Ensure at least a single node is present, for measuring.
  1665. if (builder.map.length == 0)
  1666. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1667. // Store the map and a cache object for the current logical line
  1668. if (i == 0) {
  1669. lineView.measure.map = builder.map
  1670. lineView.measure.cache = {}
  1671. } else {
  1672. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1673. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1674. }
  1675. }
  1676. // See issue #2901
  1677. if (webkit) {
  1678. var last = builder.content.lastChild
  1679. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1680. { builder.content.className = "cm-tab-wrap-hack" }
  1681. }
  1682. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1683. if (builder.pre.className)
  1684. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1685. return builder
  1686. }
  1687. function defaultSpecialCharPlaceholder(ch) {
  1688. var token = elt("span", "\u2022", "cm-invalidchar")
  1689. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1690. token.setAttribute("aria-label", token.title)
  1691. return token
  1692. }
  1693. // Build up the DOM representation for a single token, and add it to
  1694. // the line map. Takes care to render special characters separately.
  1695. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1696. if (!text) { return }
  1697. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1698. var special = builder.cm.state.specialChars, mustWrap = false
  1699. var content
  1700. if (!special.test(text)) {
  1701. builder.col += text.length
  1702. content = document.createTextNode(displayText)
  1703. builder.map.push(builder.pos, builder.pos + text.length, content)
  1704. if (ie && ie_version < 9) { mustWrap = true }
  1705. builder.pos += text.length
  1706. } else {
  1707. content = document.createDocumentFragment()
  1708. var pos = 0
  1709. while (true) {
  1710. special.lastIndex = pos
  1711. var m = special.exec(text)
  1712. var skipped = m ? m.index - pos : text.length - pos
  1713. if (skipped) {
  1714. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1715. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1716. else { content.appendChild(txt) }
  1717. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1718. builder.col += skipped
  1719. builder.pos += skipped
  1720. }
  1721. if (!m) { break }
  1722. pos += skipped + 1
  1723. var txt$1 = (void 0)
  1724. if (m[0] == "\t") {
  1725. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1726. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1727. txt$1.setAttribute("role", "presentation")
  1728. txt$1.setAttribute("cm-text", "\t")
  1729. builder.col += tabWidth
  1730. } else if (m[0] == "\r" || m[0] == "\n") {
  1731. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1732. txt$1.setAttribute("cm-text", m[0])
  1733. builder.col += 1
  1734. } else {
  1735. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1736. txt$1.setAttribute("cm-text", m[0])
  1737. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1738. else { content.appendChild(txt$1) }
  1739. builder.col += 1
  1740. }
  1741. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1742. builder.pos++
  1743. }
  1744. }
  1745. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1746. if (style || startStyle || endStyle || mustWrap || css) {
  1747. var fullStyle = style || ""
  1748. if (startStyle) { fullStyle += startStyle }
  1749. if (endStyle) { fullStyle += endStyle }
  1750. var token = elt("span", [content], fullStyle, css)
  1751. if (title) { token.title = title }
  1752. return builder.content.appendChild(token)
  1753. }
  1754. builder.content.appendChild(content)
  1755. }
  1756. function splitSpaces(text, trailingBefore) {
  1757. if (text.length > 1 && !/ /.test(text)) { return text }
  1758. var spaceBefore = trailingBefore, result = ""
  1759. for (var i = 0; i < text.length; i++) {
  1760. var ch = text.charAt(i)
  1761. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1762. { ch = "\u00a0" }
  1763. result += ch
  1764. spaceBefore = ch == " "
  1765. }
  1766. return result
  1767. }
  1768. // Work around nonsense dimensions being reported for stretches of
  1769. // right-to-left text.
  1770. function buildTokenBadBidi(inner, order) {
  1771. return function (builder, text, style, startStyle, endStyle, title, css) {
  1772. style = style ? style + " cm-force-border" : "cm-force-border"
  1773. var start = builder.pos, end = start + text.length
  1774. for (;;) {
  1775. // Find the part that overlaps with the start of this text
  1776. var part = (void 0)
  1777. for (var i = 0; i < order.length; i++) {
  1778. part = order[i]
  1779. if (part.to > start && part.from <= start) { break }
  1780. }
  1781. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1782. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1783. startStyle = null
  1784. text = text.slice(part.to - start)
  1785. start = part.to
  1786. }
  1787. }
  1788. }
  1789. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1790. var widget = !ignoreWidget && marker.widgetNode
  1791. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1792. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1793. if (!widget)
  1794. { widget = builder.content.appendChild(document.createElement("span")) }
  1795. widget.setAttribute("cm-marker", marker.id)
  1796. }
  1797. if (widget) {
  1798. builder.cm.display.input.setUneditable(widget)
  1799. builder.content.appendChild(widget)
  1800. }
  1801. builder.pos += size
  1802. builder.trailingSpace = false
  1803. }
  1804. // Outputs a number of spans to make up a line, taking highlighting
  1805. // and marked text into account.
  1806. function insertLineContent(line, builder, styles) {
  1807. var spans = line.markedSpans, allText = line.text, at = 0
  1808. if (!spans) {
  1809. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1810. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1811. return
  1812. }
  1813. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1814. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1815. for (;;) {
  1816. if (nextChange == pos) { // Update current marker set
  1817. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1818. collapsed = null; nextChange = Infinity
  1819. var foundBookmarks = [], endStyles = (void 0)
  1820. for (var j = 0; j < spans.length; ++j) {
  1821. var sp = spans[j], m = sp.marker
  1822. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1823. foundBookmarks.push(m)
  1824. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1825. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1826. nextChange = sp.to
  1827. spanEndStyle = ""
  1828. }
  1829. if (m.className) { spanStyle += " " + m.className }
  1830. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1831. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1832. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1833. if (m.title && !title) { title = m.title }
  1834. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1835. { collapsed = sp }
  1836. } else if (sp.from > pos && nextChange > sp.from) {
  1837. nextChange = sp.from
  1838. }
  1839. }
  1840. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1841. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1842. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1843. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1844. if (collapsed && (collapsed.from || 0) == pos) {
  1845. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1846. collapsed.marker, collapsed.from == null)
  1847. if (collapsed.to == null) { return }
  1848. if (collapsed.to == pos) { collapsed = false }
  1849. }
  1850. }
  1851. if (pos >= len) { break }
  1852. var upto = Math.min(len, nextChange)
  1853. while (true) {
  1854. if (text) {
  1855. var end = pos + text.length
  1856. if (!collapsed) {
  1857. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1858. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1859. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1860. }
  1861. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1862. pos = end
  1863. spanStartStyle = ""
  1864. }
  1865. text = allText.slice(at, at = styles[i++])
  1866. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1867. }
  1868. }
  1869. }
  1870. // These objects are used to represent the visible (currently drawn)
  1871. // part of the document. A LineView may correspond to multiple
  1872. // logical lines, if those are connected by collapsed ranges.
  1873. function LineView(doc, line, lineN) {
  1874. // The starting line
  1875. this.line = line
  1876. // Continuing lines, if any
  1877. this.rest = visualLineContinued(line)
  1878. // Number of logical lines in this visual line
  1879. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1880. this.node = this.text = null
  1881. this.hidden = lineIsHidden(doc, line)
  1882. }
  1883. // Create a range of LineView objects for the given lines.
  1884. function buildViewArray(cm, from, to) {
  1885. var array = [], nextPos
  1886. for (var pos = from; pos < to; pos = nextPos) {
  1887. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1888. nextPos = pos + view.size
  1889. array.push(view)
  1890. }
  1891. return array
  1892. }
  1893. var operationGroup = null
  1894. function pushOperation(op) {
  1895. if (operationGroup) {
  1896. operationGroup.ops.push(op)
  1897. } else {
  1898. op.ownsGroup = operationGroup = {
  1899. ops: [op],
  1900. delayedCallbacks: []
  1901. }
  1902. }
  1903. }
  1904. function fireCallbacksForOps(group) {
  1905. // Calls delayed callbacks and cursorActivity handlers until no
  1906. // new ones appear
  1907. var callbacks = group.delayedCallbacks, i = 0
  1908. do {
  1909. for (; i < callbacks.length; i++)
  1910. { callbacks[i].call(null) }
  1911. for (var j = 0; j < group.ops.length; j++) {
  1912. var op = group.ops[j]
  1913. if (op.cursorActivityHandlers)
  1914. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1915. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1916. }
  1917. } while (i < callbacks.length)
  1918. }
  1919. function finishOperation(op, endCb) {
  1920. var group = op.ownsGroup
  1921. if (!group) { return }
  1922. try { fireCallbacksForOps(group) }
  1923. finally {
  1924. operationGroup = null
  1925. endCb(group)
  1926. }
  1927. }
  1928. var orphanDelayedCallbacks = null
  1929. // Often, we want to signal events at a point where we are in the
  1930. // middle of some work, but don't want the handler to start calling
  1931. // other methods on the editor, which might be in an inconsistent
  1932. // state or simply not expect any other events to happen.
  1933. // signalLater looks whether there are any handlers, and schedules
  1934. // them to be executed when the last operation ends, or, if no
  1935. // operation is active, when a timeout fires.
  1936. function signalLater(emitter, type /*, values...*/) {
  1937. var arr = getHandlers(emitter, type)
  1938. if (!arr.length) { return }
  1939. var args = Array.prototype.slice.call(arguments, 2), list
  1940. if (operationGroup) {
  1941. list = operationGroup.delayedCallbacks
  1942. } else if (orphanDelayedCallbacks) {
  1943. list = orphanDelayedCallbacks
  1944. } else {
  1945. list = orphanDelayedCallbacks = []
  1946. setTimeout(fireOrphanDelayed, 0)
  1947. }
  1948. var loop = function ( i ) {
  1949. list.push(function () { return arr[i].apply(null, args); })
  1950. };
  1951. for (var i = 0; i < arr.length; ++i)
  1952. loop( i );
  1953. }
  1954. function fireOrphanDelayed() {
  1955. var delayed = orphanDelayedCallbacks
  1956. orphanDelayedCallbacks = null
  1957. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1958. }
  1959. // When an aspect of a line changes, a string is added to
  1960. // lineView.changes. This updates the relevant part of the line's
  1961. // DOM structure.
  1962. function updateLineForChanges(cm, lineView, lineN, dims) {
  1963. for (var j = 0; j < lineView.changes.length; j++) {
  1964. var type = lineView.changes[j]
  1965. if (type == "text") { updateLineText(cm, lineView) }
  1966. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1967. else if (type == "class") { updateLineClasses(lineView) }
  1968. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1969. }
  1970. lineView.changes = null
  1971. }
  1972. // Lines with gutter elements, widgets or a background class need to
  1973. // be wrapped, and have the extra elements added to the wrapper div
  1974. function ensureLineWrapped(lineView) {
  1975. if (lineView.node == lineView.text) {
  1976. lineView.node = elt("div", null, null, "position: relative")
  1977. if (lineView.text.parentNode)
  1978. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1979. lineView.node.appendChild(lineView.text)
  1980. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1981. }
  1982. return lineView.node
  1983. }
  1984. function updateLineBackground(lineView) {
  1985. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1986. if (cls) { cls += " CodeMirror-linebackground" }
  1987. if (lineView.background) {
  1988. if (cls) { lineView.background.className = cls }
  1989. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1990. } else if (cls) {
  1991. var wrap = ensureLineWrapped(lineView)
  1992. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1993. }
  1994. }
  1995. // Wrapper around buildLineContent which will reuse the structure
  1996. // in display.externalMeasured when possible.
  1997. function getLineContent(cm, lineView) {
  1998. var ext = cm.display.externalMeasured
  1999. if (ext && ext.line == lineView.line) {
  2000. cm.display.externalMeasured = null
  2001. lineView.measure = ext.measure
  2002. return ext.built
  2003. }
  2004. return buildLineContent(cm, lineView)
  2005. }
  2006. // Redraw the line's text. Interacts with the background and text
  2007. // classes because the mode may output tokens that influence these
  2008. // classes.
  2009. function updateLineText(cm, lineView) {
  2010. var cls = lineView.text.className
  2011. var built = getLineContent(cm, lineView)
  2012. if (lineView.text == lineView.node) { lineView.node = built.pre }
  2013. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2014. lineView.text = built.pre
  2015. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2016. lineView.bgClass = built.bgClass
  2017. lineView.textClass = built.textClass
  2018. updateLineClasses(lineView)
  2019. } else if (cls) {
  2020. lineView.text.className = cls
  2021. }
  2022. }
  2023. function updateLineClasses(lineView) {
  2024. updateLineBackground(lineView)
  2025. if (lineView.line.wrapClass)
  2026. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  2027. else if (lineView.node != lineView.text)
  2028. { lineView.node.className = "" }
  2029. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  2030. lineView.text.className = textClass || ""
  2031. }
  2032. function updateLineGutter(cm, lineView, lineN, dims) {
  2033. if (lineView.gutter) {
  2034. lineView.node.removeChild(lineView.gutter)
  2035. lineView.gutter = null
  2036. }
  2037. if (lineView.gutterBackground) {
  2038. lineView.node.removeChild(lineView.gutterBackground)
  2039. lineView.gutterBackground = null
  2040. }
  2041. if (lineView.line.gutterClass) {
  2042. var wrap = ensureLineWrapped(lineView)
  2043. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2044. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  2045. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2046. }
  2047. var markers = lineView.line.gutterMarkers
  2048. if (cm.options.lineNumbers || markers) {
  2049. var wrap$1 = ensureLineWrapped(lineView)
  2050. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  2051. cm.display.input.setUneditable(gutterWrap)
  2052. wrap$1.insertBefore(gutterWrap, lineView.text)
  2053. if (lineView.line.gutterClass)
  2054. { gutterWrap.className += " " + lineView.line.gutterClass }
  2055. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2056. { lineView.lineNumber = gutterWrap.appendChild(
  2057. elt("div", lineNumberFor(cm.options, lineN),
  2058. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2059. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2060. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2061. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2062. if (found)
  2063. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2064. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2065. } }
  2066. }
  2067. }
  2068. function updateLineWidgets(cm, lineView, dims) {
  2069. if (lineView.alignable) { lineView.alignable = null }
  2070. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2071. next = node.nextSibling
  2072. if (node.className == "CodeMirror-linewidget")
  2073. { lineView.node.removeChild(node) }
  2074. }
  2075. insertLineWidgets(cm, lineView, dims)
  2076. }
  2077. // Build a line's DOM representation from scratch
  2078. function buildLineElement(cm, lineView, lineN, dims) {
  2079. var built = getLineContent(cm, lineView)
  2080. lineView.text = lineView.node = built.pre
  2081. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2082. if (built.textClass) { lineView.textClass = built.textClass }
  2083. updateLineClasses(lineView)
  2084. updateLineGutter(cm, lineView, lineN, dims)
  2085. insertLineWidgets(cm, lineView, dims)
  2086. return lineView.node
  2087. }
  2088. // A lineView may contain multiple logical lines (when merged by
  2089. // collapsed spans). The widgets for all of them need to be drawn.
  2090. function insertLineWidgets(cm, lineView, dims) {
  2091. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2092. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2093. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2094. }
  2095. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2096. if (!line.widgets) { return }
  2097. var wrap = ensureLineWrapped(lineView)
  2098. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2099. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2100. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2101. positionLineWidget(widget, node, lineView, dims)
  2102. cm.display.input.setUneditable(node)
  2103. if (allowAbove && widget.above)
  2104. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2105. else
  2106. { wrap.appendChild(node) }
  2107. signalLater(widget, "redraw")
  2108. }
  2109. }
  2110. function positionLineWidget(widget, node, lineView, dims) {
  2111. if (widget.noHScroll) {
  2112. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2113. var width = dims.wrapperWidth
  2114. node.style.left = dims.fixedPos + "px"
  2115. if (!widget.coverGutter) {
  2116. width -= dims.gutterTotalWidth
  2117. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2118. }
  2119. node.style.width = width + "px"
  2120. }
  2121. if (widget.coverGutter) {
  2122. node.style.zIndex = 5
  2123. node.style.position = "relative"
  2124. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2125. }
  2126. }
  2127. function widgetHeight(widget) {
  2128. if (widget.height != null) { return widget.height }
  2129. var cm = widget.doc.cm
  2130. if (!cm) { return 0 }
  2131. if (!contains(document.body, widget.node)) {
  2132. var parentStyle = "position: relative;"
  2133. if (widget.coverGutter)
  2134. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2135. if (widget.noHScroll)
  2136. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2137. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2138. }
  2139. return widget.height = widget.node.parentNode.offsetHeight
  2140. }
  2141. // Return true when the given mouse event happened in a widget
  2142. function eventInWidget(display, e) {
  2143. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2144. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2145. (n.parentNode == display.sizer && n != display.mover))
  2146. { return true }
  2147. }
  2148. }
  2149. // POSITION MEASUREMENT
  2150. function paddingTop(display) {return display.lineSpace.offsetTop}
  2151. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2152. function paddingH(display) {
  2153. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2154. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2155. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2156. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2157. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2158. return data
  2159. }
  2160. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2161. function displayWidth(cm) {
  2162. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2163. }
  2164. function displayHeight(cm) {
  2165. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2166. }
  2167. // Ensure the lineView.wrapping.heights array is populated. This is
  2168. // an array of bottom offsets for the lines that make up a drawn
  2169. // line. When lineWrapping is on, there might be more than one
  2170. // height.
  2171. function ensureLineHeights(cm, lineView, rect) {
  2172. var wrapping = cm.options.lineWrapping
  2173. var curWidth = wrapping && displayWidth(cm)
  2174. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2175. var heights = lineView.measure.heights = []
  2176. if (wrapping) {
  2177. lineView.measure.width = curWidth
  2178. var rects = lineView.text.firstChild.getClientRects()
  2179. for (var i = 0; i < rects.length - 1; i++) {
  2180. var cur = rects[i], next = rects[i + 1]
  2181. if (Math.abs(cur.bottom - next.bottom) > 2)
  2182. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2183. }
  2184. }
  2185. heights.push(rect.bottom - rect.top)
  2186. }
  2187. }
  2188. // Find a line map (mapping character offsets to text nodes) and a
  2189. // measurement cache for the given line number. (A line view might
  2190. // contain multiple lines when collapsed ranges are present.)
  2191. function mapFromLineView(lineView, line, lineN) {
  2192. if (lineView.line == line)
  2193. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2194. for (var i = 0; i < lineView.rest.length; i++)
  2195. { if (lineView.rest[i] == line)
  2196. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2197. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2198. { if (lineNo(lineView.rest[i$1]) > lineN)
  2199. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2200. }
  2201. // Render a line into the hidden node display.externalMeasured. Used
  2202. // when measurement is needed for a line that's not in the viewport.
  2203. function updateExternalMeasurement(cm, line) {
  2204. line = visualLine(line)
  2205. var lineN = lineNo(line)
  2206. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2207. view.lineN = lineN
  2208. var built = view.built = buildLineContent(cm, view)
  2209. view.text = built.pre
  2210. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2211. return view
  2212. }
  2213. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2214. // for a given character.
  2215. function measureChar(cm, line, ch, bias) {
  2216. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2217. }
  2218. // Find a line view that corresponds to the given line number.
  2219. function findViewForLine(cm, lineN) {
  2220. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2221. { return cm.display.view[findViewIndex(cm, lineN)] }
  2222. var ext = cm.display.externalMeasured
  2223. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2224. { return ext }
  2225. }
  2226. // Measurement can be split in two steps, the set-up work that
  2227. // applies to the whole line, and the measurement of the actual
  2228. // character. Functions like coordsChar, that need to do a lot of
  2229. // measurements in a row, can thus ensure that the set-up work is
  2230. // only done once.
  2231. function prepareMeasureForLine(cm, line) {
  2232. var lineN = lineNo(line)
  2233. var view = findViewForLine(cm, lineN)
  2234. if (view && !view.text) {
  2235. view = null
  2236. } else if (view && view.changes) {
  2237. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2238. cm.curOp.forceUpdate = true
  2239. }
  2240. if (!view)
  2241. { view = updateExternalMeasurement(cm, line) }
  2242. var info = mapFromLineView(view, line, lineN)
  2243. return {
  2244. line: line, view: view, rect: null,
  2245. map: info.map, cache: info.cache, before: info.before,
  2246. hasHeights: false
  2247. }
  2248. }
  2249. // Given a prepared measurement object, measures the position of an
  2250. // actual character (or fetches it from the cache).
  2251. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2252. if (prepared.before) { ch = -1 }
  2253. var key = ch + (bias || ""), found
  2254. if (prepared.cache.hasOwnProperty(key)) {
  2255. found = prepared.cache[key]
  2256. } else {
  2257. if (!prepared.rect)
  2258. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2259. if (!prepared.hasHeights) {
  2260. ensureLineHeights(cm, prepared.view, prepared.rect)
  2261. prepared.hasHeights = true
  2262. }
  2263. found = measureCharInner(cm, prepared, ch, bias)
  2264. if (!found.bogus) { prepared.cache[key] = found }
  2265. }
  2266. return {left: found.left, right: found.right,
  2267. top: varHeight ? found.rtop : found.top,
  2268. bottom: varHeight ? found.rbottom : found.bottom}
  2269. }
  2270. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2271. function nodeAndOffsetInLineMap(map, ch, bias) {
  2272. var node, start, end, collapse, mStart, mEnd
  2273. // First, search the line map for the text node corresponding to,
  2274. // or closest to, the target character.
  2275. for (var i = 0; i < map.length; i += 3) {
  2276. mStart = map[i]
  2277. mEnd = map[i + 1]
  2278. if (ch < mStart) {
  2279. start = 0; end = 1
  2280. collapse = "left"
  2281. } else if (ch < mEnd) {
  2282. start = ch - mStart
  2283. end = start + 1
  2284. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2285. end = mEnd - mStart
  2286. start = end - 1
  2287. if (ch >= mEnd) { collapse = "right" }
  2288. }
  2289. if (start != null) {
  2290. node = map[i + 2]
  2291. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2292. { collapse = bias }
  2293. if (bias == "left" && start == 0)
  2294. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2295. node = map[(i -= 3) + 2]
  2296. collapse = "left"
  2297. } }
  2298. if (bias == "right" && start == mEnd - mStart)
  2299. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2300. node = map[(i += 3) + 2]
  2301. collapse = "right"
  2302. } }
  2303. break
  2304. }
  2305. }
  2306. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2307. }
  2308. function getUsefulRect(rects, bias) {
  2309. var rect = nullRect
  2310. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2311. if ((rect = rects[i]).left != rect.right) { break }
  2312. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2313. if ((rect = rects[i$1]).left != rect.right) { break }
  2314. } }
  2315. return rect
  2316. }
  2317. function measureCharInner(cm, prepared, ch, bias) {
  2318. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2319. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2320. var rect
  2321. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2322. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2323. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2324. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2325. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2326. { rect = node.parentNode.getBoundingClientRect() }
  2327. else
  2328. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2329. if (rect.left || rect.right || start == 0) { break }
  2330. end = start
  2331. start = start - 1
  2332. collapse = "right"
  2333. }
  2334. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2335. } else { // If it is a widget, simply get the box for the whole widget.
  2336. if (start > 0) { collapse = bias = "right" }
  2337. var rects
  2338. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2339. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2340. else
  2341. { rect = node.getBoundingClientRect() }
  2342. }
  2343. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2344. var rSpan = node.parentNode.getClientRects()[0]
  2345. if (rSpan)
  2346. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2347. else
  2348. { rect = nullRect }
  2349. }
  2350. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2351. var mid = (rtop + rbot) / 2
  2352. var heights = prepared.view.measure.heights
  2353. var i = 0
  2354. for (; i < heights.length - 1; i++)
  2355. { if (mid < heights[i]) { break } }
  2356. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2357. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2358. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2359. top: top, bottom: bot}
  2360. if (!rect.left && !rect.right) { result.bogus = true }
  2361. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2362. return result
  2363. }
  2364. // Work around problem with bounding client rects on ranges being
  2365. // returned incorrectly when zoomed on IE10 and below.
  2366. function maybeUpdateRectForZooming(measure, rect) {
  2367. if (!window.screen || screen.logicalXDPI == null ||
  2368. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2369. { return rect }
  2370. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2371. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2372. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2373. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2374. }
  2375. function clearLineMeasurementCacheFor(lineView) {
  2376. if (lineView.measure) {
  2377. lineView.measure.cache = {}
  2378. lineView.measure.heights = null
  2379. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2380. { lineView.measure.caches[i] = {} } }
  2381. }
  2382. }
  2383. function clearLineMeasurementCache(cm) {
  2384. cm.display.externalMeasure = null
  2385. removeChildren(cm.display.lineMeasure)
  2386. for (var i = 0; i < cm.display.view.length; i++)
  2387. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2388. }
  2389. function clearCaches(cm) {
  2390. clearLineMeasurementCache(cm)
  2391. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2392. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2393. cm.display.lineNumChars = null
  2394. }
  2395. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft }
  2396. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop }
  2397. // Converts a {top, bottom, left, right} box from line-local
  2398. // coordinates into another coordinate system. Context may be one of
  2399. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2400. // or "page".
  2401. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2402. if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
  2403. var size = widgetHeight(lineObj.widgets[i])
  2404. rect.top += size; rect.bottom += size
  2405. } } }
  2406. if (context == "line") { return rect }
  2407. if (!context) { context = "local" }
  2408. var yOff = heightAtLine(lineObj)
  2409. if (context == "local") { yOff += paddingTop(cm.display) }
  2410. else { yOff -= cm.display.viewOffset }
  2411. if (context == "page" || context == "window") {
  2412. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2413. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2414. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2415. rect.left += xOff; rect.right += xOff
  2416. }
  2417. rect.top += yOff; rect.bottom += yOff
  2418. return rect
  2419. }
  2420. // Coverts a box from "div" coords to another coordinate system.
  2421. // Context may be "window", "page", "div", or "local"./null.
  2422. function fromCoordSystem(cm, coords, context) {
  2423. if (context == "div") { return coords }
  2424. var left = coords.left, top = coords.top
  2425. // First move into "page" coordinate system
  2426. if (context == "page") {
  2427. left -= pageScrollX()
  2428. top -= pageScrollY()
  2429. } else if (context == "local" || !context) {
  2430. var localBox = cm.display.sizer.getBoundingClientRect()
  2431. left += localBox.left
  2432. top += localBox.top
  2433. }
  2434. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2435. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2436. }
  2437. function charCoords(cm, pos, context, lineObj, bias) {
  2438. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2439. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2440. }
  2441. // Returns a box for a given cursor position, which may have an
  2442. // 'other' property containing the position of the secondary cursor
  2443. // on a bidi boundary.
  2444. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2445. // and after `char - 1` in writing order of `char - 1`
  2446. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2447. // and before `char` in writing order of `char`
  2448. // Examples (upper-case letters are RTL, lower-case are LTR):
  2449. // Pos(0, 1, ...)
  2450. // before after
  2451. // ab a|b a|b
  2452. // aB a|B aB|
  2453. // Ab |Ab A|b
  2454. // AB B|A B|A
  2455. // Every position after the last character on a line is considered to stick
  2456. // to the last character on the line.
  2457. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2458. lineObj = lineObj || getLine(cm.doc, pos.line)
  2459. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2460. function get(ch, right) {
  2461. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2462. if (right) { m.left = m.right; } else { m.right = m.left }
  2463. return intoCoordSystem(cm, lineObj, m, context)
  2464. }
  2465. var order = getOrder(lineObj), ch = pos.ch, sticky = pos.sticky
  2466. if (ch >= lineObj.text.length) {
  2467. ch = lineObj.text.length
  2468. sticky = "before"
  2469. } else if (ch <= 0) {
  2470. ch = 0
  2471. sticky = "after"
  2472. }
  2473. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2474. function getBidi(ch, partPos, invert) {
  2475. var part = order[partPos], right = (part.level % 2) != 0
  2476. return get(invert ? ch - 1 : ch, right != invert)
  2477. }
  2478. var partPos = getBidiPartAt(order, ch, sticky)
  2479. var other = bidiOther
  2480. var val = getBidi(ch, partPos, sticky == "before")
  2481. if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
  2482. return val
  2483. }
  2484. // Used to cheaply estimate the coordinates for a position. Used for
  2485. // intermediate scroll updates.
  2486. function estimateCoords(cm, pos) {
  2487. var left = 0
  2488. pos = clipPos(cm.doc, pos)
  2489. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2490. var lineObj = getLine(cm.doc, pos.line)
  2491. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2492. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2493. }
  2494. // Positions returned by coordsChar contain some extra information.
  2495. // xRel is the relative x position of the input coordinates compared
  2496. // to the found position (so xRel > 0 means the coordinates are to
  2497. // the right of the character position, for example). When outside
  2498. // is true, that means the coordinates lie outside the line's
  2499. // vertical range.
  2500. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2501. var pos = Pos(line, ch, sticky)
  2502. pos.xRel = xRel
  2503. if (outside) { pos.outside = true }
  2504. return pos
  2505. }
  2506. // Compute the character position closest to the given coordinates.
  2507. // Input must be lineSpace-local ("div" coordinate system).
  2508. function coordsChar(cm, x, y) {
  2509. var doc = cm.doc
  2510. y += cm.display.viewOffset
  2511. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2512. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2513. if (lineN > last)
  2514. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2515. if (x < 0) { x = 0 }
  2516. var lineObj = getLine(doc, lineN)
  2517. for (;;) {
  2518. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2519. var merged = collapsedSpanAtEnd(lineObj)
  2520. var mergedPos = merged && merged.find(0, true)
  2521. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2522. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2523. else
  2524. { return found }
  2525. }
  2526. }
  2527. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2528. var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }
  2529. var end = lineObj.text.length
  2530. var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0)
  2531. end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end)
  2532. return {begin: begin, end: end}
  2533. }
  2534. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2535. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  2536. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2537. }
  2538. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2539. y -= heightAtLine(lineObj)
  2540. var begin = 0, end = lineObj.text.length
  2541. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2542. var pos
  2543. var order = getOrder(lineObj)
  2544. if (order) {
  2545. if (cm.options.lineWrapping) {
  2546. ;var assign;
  2547. ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign))
  2548. }
  2549. pos = new Pos(lineNo, begin)
  2550. var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left
  2551. var dir = beginLeft < x ? 1 : -1
  2552. var prevDiff, diff = beginLeft - x, prevPos
  2553. do {
  2554. prevDiff = diff
  2555. prevPos = pos
  2556. pos = moveVisually(cm, lineObj, pos, dir)
  2557. if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) {
  2558. pos = prevPos
  2559. break
  2560. }
  2561. diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x
  2562. } while ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff)))
  2563. if (Math.abs(diff) > Math.abs(prevDiff)) {
  2564. if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") }
  2565. pos = prevPos
  2566. }
  2567. } else {
  2568. var ch = findFirst(function (ch) {
  2569. var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line")
  2570. if (box.top > y) {
  2571. // For the cursor stickiness
  2572. end = Math.min(ch, end)
  2573. return true
  2574. }
  2575. else if (box.bottom <= y) { return false }
  2576. else if (box.left > x) { return true }
  2577. else if (box.right < x) { return false }
  2578. else { return (x - box.left < box.right - x) }
  2579. }, begin, end)
  2580. ch = skipExtendingChars(lineObj.text, ch, 1)
  2581. pos = new Pos(lineNo, ch, ch == end ? "before" : "after")
  2582. }
  2583. var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure)
  2584. if (y < coords.top || coords.bottom < y) { pos.outside = true }
  2585. pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0)
  2586. return pos
  2587. }
  2588. var measureText
  2589. // Compute the default text height.
  2590. function textHeight(display) {
  2591. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2592. if (measureText == null) {
  2593. measureText = elt("pre")
  2594. // Measure a bunch of lines, for browsers that compute
  2595. // fractional heights.
  2596. for (var i = 0; i < 49; ++i) {
  2597. measureText.appendChild(document.createTextNode("x"))
  2598. measureText.appendChild(elt("br"))
  2599. }
  2600. measureText.appendChild(document.createTextNode("x"))
  2601. }
  2602. removeChildrenAndAdd(display.measure, measureText)
  2603. var height = measureText.offsetHeight / 50
  2604. if (height > 3) { display.cachedTextHeight = height }
  2605. removeChildren(display.measure)
  2606. return height || 1
  2607. }
  2608. // Compute the default character width.
  2609. function charWidth(display) {
  2610. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2611. var anchor = elt("span", "xxxxxxxxxx")
  2612. var pre = elt("pre", [anchor])
  2613. removeChildrenAndAdd(display.measure, pre)
  2614. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2615. if (width > 2) { display.cachedCharWidth = width }
  2616. return width || 10
  2617. }
  2618. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2619. // view, so that we don't interleave reading and writing to the DOM.
  2620. function getDimensions(cm) {
  2621. var d = cm.display, left = {}, width = {}
  2622. var gutterLeft = d.gutters.clientLeft
  2623. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2624. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2625. width[cm.options.gutters[i]] = n.clientWidth
  2626. }
  2627. return {fixedPos: compensateForHScroll(d),
  2628. gutterTotalWidth: d.gutters.offsetWidth,
  2629. gutterLeft: left,
  2630. gutterWidth: width,
  2631. wrapperWidth: d.wrapper.clientWidth}
  2632. }
  2633. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2634. // but using getBoundingClientRect to get a sub-pixel-accurate
  2635. // result.
  2636. function compensateForHScroll(display) {
  2637. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2638. }
  2639. // Returns a function that estimates the height of a line, to use as
  2640. // first approximation until the line becomes visible (and is thus
  2641. // properly measurable).
  2642. function estimateHeight(cm) {
  2643. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2644. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2645. return function (line) {
  2646. if (lineIsHidden(cm.doc, line)) { return 0 }
  2647. var widgetsHeight = 0
  2648. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2649. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2650. } }
  2651. if (wrapping)
  2652. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2653. else
  2654. { return widgetsHeight + th }
  2655. }
  2656. }
  2657. function estimateLineHeights(cm) {
  2658. var doc = cm.doc, est = estimateHeight(cm)
  2659. doc.iter(function (line) {
  2660. var estHeight = est(line)
  2661. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2662. })
  2663. }
  2664. // Given a mouse event, find the corresponding position. If liberal
  2665. // is false, it checks whether a gutter or scrollbar was clicked,
  2666. // and returns null if it was. forRect is used by rectangular
  2667. // selections, and tries to estimate a character position even for
  2668. // coordinates beyond the right of the text.
  2669. function posFromMouse(cm, e, liberal, forRect) {
  2670. var display = cm.display
  2671. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2672. var x, y, space = display.lineSpace.getBoundingClientRect()
  2673. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2674. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2675. catch (e) { return null }
  2676. var coords = coordsChar(cm, x, y), line
  2677. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2678. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2679. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2680. }
  2681. return coords
  2682. }
  2683. // Find the view element corresponding to a given line. Return null
  2684. // when the line isn't visible.
  2685. function findViewIndex(cm, n) {
  2686. if (n >= cm.display.viewTo) { return null }
  2687. n -= cm.display.viewFrom
  2688. if (n < 0) { return null }
  2689. var view = cm.display.view
  2690. for (var i = 0; i < view.length; i++) {
  2691. n -= view[i].size
  2692. if (n < 0) { return i }
  2693. }
  2694. }
  2695. function updateSelection(cm) {
  2696. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2697. }
  2698. function prepareSelection(cm, primary) {
  2699. var doc = cm.doc, result = {}
  2700. var curFragment = result.cursors = document.createDocumentFragment()
  2701. var selFragment = result.selection = document.createDocumentFragment()
  2702. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2703. if (primary === false && i == doc.sel.primIndex) { continue }
  2704. var range = doc.sel.ranges[i]
  2705. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2706. var collapsed = range.empty()
  2707. if (collapsed || cm.options.showCursorWhenSelecting)
  2708. { drawSelectionCursor(cm, range.head, curFragment) }
  2709. if (!collapsed)
  2710. { drawSelectionRange(cm, range, selFragment) }
  2711. }
  2712. return result
  2713. }
  2714. // Draws a cursor for the given range
  2715. function drawSelectionCursor(cm, head, output) {
  2716. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2717. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2718. cursor.style.left = pos.left + "px"
  2719. cursor.style.top = pos.top + "px"
  2720. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2721. if (pos.other) {
  2722. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2723. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2724. otherCursor.style.display = ""
  2725. otherCursor.style.left = pos.other.left + "px"
  2726. otherCursor.style.top = pos.other.top + "px"
  2727. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2728. }
  2729. }
  2730. // Draws the given range as a highlighted selection
  2731. function drawSelectionRange(cm, range, output) {
  2732. var display = cm.display, doc = cm.doc
  2733. var fragment = document.createDocumentFragment()
  2734. var padding = paddingH(cm.display), leftSide = padding.left
  2735. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2736. function add(left, top, width, bottom) {
  2737. if (top < 0) { top = 0 }
  2738. top = Math.round(top)
  2739. bottom = Math.round(bottom)
  2740. 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")))
  2741. }
  2742. function drawForLine(line, fromArg, toArg) {
  2743. var lineObj = getLine(doc, line)
  2744. var lineLen = lineObj.text.length
  2745. var start, end
  2746. function coords(ch, bias) {
  2747. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2748. }
  2749. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2750. var leftPos = coords(from, "left"), rightPos, left, right
  2751. if (from == to) {
  2752. rightPos = leftPos
  2753. left = right = leftPos.left
  2754. } else {
  2755. rightPos = coords(to - 1, "right")
  2756. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
  2757. left = leftPos.left
  2758. right = rightPos.right
  2759. }
  2760. if (fromArg == null && from == 0) { left = leftSide }
  2761. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2762. add(left, leftPos.top, null, leftPos.bottom)
  2763. left = leftSide
  2764. if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
  2765. }
  2766. if (toArg == null && to == lineLen) { right = rightSide }
  2767. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2768. { start = leftPos }
  2769. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2770. { end = rightPos }
  2771. if (left < leftSide + 1) { left = leftSide }
  2772. add(left, rightPos.top, right - left, rightPos.bottom)
  2773. })
  2774. return {start: start, end: end}
  2775. }
  2776. var sFrom = range.from(), sTo = range.to()
  2777. if (sFrom.line == sTo.line) {
  2778. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2779. } else {
  2780. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2781. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2782. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2783. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2784. if (singleVLine) {
  2785. if (leftEnd.top < rightStart.top - 2) {
  2786. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2787. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2788. } else {
  2789. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2790. }
  2791. }
  2792. if (leftEnd.bottom < rightStart.top)
  2793. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2794. }
  2795. output.appendChild(fragment)
  2796. }
  2797. // Cursor-blinking
  2798. function restartBlink(cm) {
  2799. if (!cm.state.focused) { return }
  2800. var display = cm.display
  2801. clearInterval(display.blinker)
  2802. var on = true
  2803. display.cursorDiv.style.visibility = ""
  2804. if (cm.options.cursorBlinkRate > 0)
  2805. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2806. cm.options.cursorBlinkRate) }
  2807. else if (cm.options.cursorBlinkRate < 0)
  2808. { display.cursorDiv.style.visibility = "hidden" }
  2809. }
  2810. function ensureFocus(cm) {
  2811. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2812. }
  2813. function delayBlurEvent(cm) {
  2814. cm.state.delayingBlurEvent = true
  2815. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2816. cm.state.delayingBlurEvent = false
  2817. onBlur(cm)
  2818. } }, 100)
  2819. }
  2820. function onFocus(cm, e) {
  2821. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2822. if (cm.options.readOnly == "nocursor") { return }
  2823. if (!cm.state.focused) {
  2824. signal(cm, "focus", cm, e)
  2825. cm.state.focused = true
  2826. addClass(cm.display.wrapper, "CodeMirror-focused")
  2827. // This test prevents this from firing when a context
  2828. // menu is closed (since the input reset would kill the
  2829. // select-all detection hack)
  2830. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2831. cm.display.input.reset()
  2832. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2833. }
  2834. cm.display.input.receivedFocus()
  2835. }
  2836. restartBlink(cm)
  2837. }
  2838. function onBlur(cm, e) {
  2839. if (cm.state.delayingBlurEvent) { return }
  2840. if (cm.state.focused) {
  2841. signal(cm, "blur", cm, e)
  2842. cm.state.focused = false
  2843. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2844. }
  2845. clearInterval(cm.display.blinker)
  2846. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2847. }
  2848. // Re-align line numbers and gutter marks to compensate for
  2849. // horizontal scrolling.
  2850. function alignHorizontally(cm) {
  2851. var display = cm.display, view = display.view
  2852. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  2853. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  2854. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  2855. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  2856. if (cm.options.fixedGutter) {
  2857. if (view[i].gutter)
  2858. { view[i].gutter.style.left = left }
  2859. if (view[i].gutterBackground)
  2860. { view[i].gutterBackground.style.left = left }
  2861. }
  2862. var align = view[i].alignable
  2863. if (align) { for (var j = 0; j < align.length; j++)
  2864. { align[j].style.left = left } }
  2865. } }
  2866. if (cm.options.fixedGutter)
  2867. { display.gutters.style.left = (comp + gutterW) + "px" }
  2868. }
  2869. // Used to ensure that the line number gutter is still the right
  2870. // size for the current document size. Returns true when an update
  2871. // is needed.
  2872. function maybeUpdateLineNumberWidth(cm) {
  2873. if (!cm.options.lineNumbers) { return false }
  2874. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  2875. if (last.length != display.lineNumChars) {
  2876. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2877. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  2878. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  2879. display.lineGutter.style.width = ""
  2880. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  2881. display.lineNumWidth = display.lineNumInnerWidth + padding
  2882. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  2883. display.lineGutter.style.width = display.lineNumWidth + "px"
  2884. updateGutterSpace(cm)
  2885. return true
  2886. }
  2887. return false
  2888. }
  2889. // Read the actual heights of the rendered lines, and update their
  2890. // stored heights to match.
  2891. function updateHeightsInViewport(cm) {
  2892. var display = cm.display
  2893. var prevBottom = display.lineDiv.offsetTop
  2894. for (var i = 0; i < display.view.length; i++) {
  2895. var cur = display.view[i], height = (void 0)
  2896. if (cur.hidden) { continue }
  2897. if (ie && ie_version < 8) {
  2898. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2899. height = bot - prevBottom
  2900. prevBottom = bot
  2901. } else {
  2902. var box = cur.node.getBoundingClientRect()
  2903. height = box.bottom - box.top
  2904. }
  2905. var diff = cur.line.height - height
  2906. if (height < 2) { height = textHeight(display) }
  2907. if (diff > .001 || diff < -.001) {
  2908. updateLineHeight(cur.line, height)
  2909. updateWidgetHeight(cur.line)
  2910. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2911. { updateWidgetHeight(cur.rest[j]) } }
  2912. }
  2913. }
  2914. }
  2915. // Read and store the height of line widgets associated with the
  2916. // given line.
  2917. function updateWidgetHeight(line) {
  2918. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
  2919. { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
  2920. }
  2921. // Compute the lines that are visible in a given viewport (defaults
  2922. // the the current scroll position). viewport may contain top,
  2923. // height, and ensure (see op.scrollToPos) properties.
  2924. function visibleLines(display, doc, viewport) {
  2925. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2926. top = Math.floor(top - paddingTop(display))
  2927. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2928. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2929. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2930. // forces those lines into the viewport (if possible).
  2931. if (viewport && viewport.ensure) {
  2932. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2933. if (ensureFrom < from) {
  2934. from = ensureFrom
  2935. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2936. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2937. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  2938. to = ensureTo
  2939. }
  2940. }
  2941. return {from: from, to: Math.max(to, from + 1)}
  2942. }
  2943. // Sync the scrollable area and scrollbars, ensure the viewport
  2944. // covers the visible area.
  2945. function setScrollTop(cm, val) {
  2946. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  2947. cm.doc.scrollTop = val
  2948. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  2949. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  2950. cm.display.scrollbars.setScrollTop(val)
  2951. if (gecko) { updateDisplaySimple(cm) }
  2952. startWorker(cm, 100)
  2953. }
  2954. // Sync scroller and scrollbar, ensure the gutter elements are
  2955. // aligned.
  2956. function setScrollLeft(cm, val, isScroller) {
  2957. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return }
  2958. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  2959. cm.doc.scrollLeft = val
  2960. alignHorizontally(cm)
  2961. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  2962. cm.display.scrollbars.setScrollLeft(val)
  2963. }
  2964. // Since the delta values reported on mouse wheel events are
  2965. // unstandardized between browsers and even browser versions, and
  2966. // generally horribly unpredictable, this code starts by measuring
  2967. // the scroll effect that the first few mouse wheel events have,
  2968. // and, from that, detects the way it can convert deltas to pixel
  2969. // offsets afterwards.
  2970. //
  2971. // The reason we want to know the amount a wheel event will scroll
  2972. // is that it gives us a chance to update the display before the
  2973. // actual scrolling happens, reducing flickering.
  2974. var wheelSamples = 0;
  2975. var wheelPixelsPerUnit = null;
  2976. // Fill in a browser-detected starting value on browsers where we
  2977. // know one. These don't have to be accurate -- the result of them
  2978. // being wrong would just be a slight flicker on the first wheel
  2979. // scroll (if it is large enough).
  2980. if (ie) { wheelPixelsPerUnit = -.53 }
  2981. else if (gecko) { wheelPixelsPerUnit = 15 }
  2982. else if (chrome) { wheelPixelsPerUnit = -.7 }
  2983. else if (safari) { wheelPixelsPerUnit = -1/3 }
  2984. function wheelEventDelta(e) {
  2985. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  2986. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  2987. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  2988. else if (dy == null) { dy = e.wheelDelta }
  2989. return {x: dx, y: dy}
  2990. }
  2991. function wheelEventPixels(e) {
  2992. var delta = wheelEventDelta(e)
  2993. delta.x *= wheelPixelsPerUnit
  2994. delta.y *= wheelPixelsPerUnit
  2995. return delta
  2996. }
  2997. function onScrollWheel(cm, e) {
  2998. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  2999. var display = cm.display, scroll = display.scroller
  3000. // Quit if there's nothing to scroll here
  3001. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  3002. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  3003. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3004. // Webkit browsers on OS X abort momentum scrolls when the target
  3005. // of the scroll event is removed from the scrollable element.
  3006. // This hack (see related code in patchDisplay) makes sure the
  3007. // element is kept around.
  3008. if (dy && mac && webkit) {
  3009. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3010. for (var i = 0; i < view.length; i++) {
  3011. if (view[i].node == cur) {
  3012. cm.display.currentWheelTarget = cur
  3013. break outer
  3014. }
  3015. }
  3016. }
  3017. }
  3018. // On some browsers, horizontal scrolling will cause redraws to
  3019. // happen before the gutter has been realigned, causing it to
  3020. // wriggle around in a most unseemly way. When we have an
  3021. // estimated pixels/delta value, we just handle horizontal
  3022. // scrolling entirely here. It'll be slightly off from native, but
  3023. // better than glitching out.
  3024. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3025. if (dy && canScrollY)
  3026. { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) }
  3027. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)))
  3028. // Only prevent default scrolling if vertical scrolling is
  3029. // actually possible. Otherwise, it causes vertical scroll
  3030. // jitter on OSX trackpads when deltaX is small and deltaY
  3031. // is large (issue #3579)
  3032. if (!dy || (dy && canScrollY))
  3033. { e_preventDefault(e) }
  3034. display.wheelStartX = null // Abort measurement, if in progress
  3035. return
  3036. }
  3037. // 'Project' the visible viewport to cover the area that is being
  3038. // scrolled into view (if we know enough to estimate it).
  3039. if (dy && wheelPixelsPerUnit != null) {
  3040. var pixels = dy * wheelPixelsPerUnit
  3041. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  3042. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  3043. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  3044. updateDisplaySimple(cm, {top: top, bottom: bot})
  3045. }
  3046. if (wheelSamples < 20) {
  3047. if (display.wheelStartX == null) {
  3048. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  3049. display.wheelDX = dx; display.wheelDY = dy
  3050. setTimeout(function () {
  3051. if (display.wheelStartX == null) { return }
  3052. var movedX = scroll.scrollLeft - display.wheelStartX
  3053. var movedY = scroll.scrollTop - display.wheelStartY
  3054. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3055. (movedX && display.wheelDX && movedX / display.wheelDX)
  3056. display.wheelStartX = display.wheelStartY = null
  3057. if (!sample) { return }
  3058. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  3059. ++wheelSamples
  3060. }, 200)
  3061. } else {
  3062. display.wheelDX += dx; display.wheelDY += dy
  3063. }
  3064. }
  3065. }
  3066. // SCROLLBARS
  3067. // Prepare DOM reads needed to update the scrollbars. Done in one
  3068. // shot to minimize update/measure roundtrips.
  3069. function measureForScrollbars(cm) {
  3070. var d = cm.display, gutterW = d.gutters.offsetWidth
  3071. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  3072. return {
  3073. clientHeight: d.scroller.clientHeight,
  3074. viewHeight: d.wrapper.clientHeight,
  3075. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3076. viewWidth: d.wrapper.clientWidth,
  3077. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3078. docHeight: docH,
  3079. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3080. nativeBarWidth: d.nativeBarWidth,
  3081. gutterWidth: gutterW
  3082. }
  3083. }
  3084. var NativeScrollbars = function(place, scroll, cm) {
  3085. this.cm = cm
  3086. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3087. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3088. place(vert); place(horiz)
  3089. on(vert, "scroll", function () {
  3090. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3091. })
  3092. on(horiz, "scroll", function () {
  3093. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3094. })
  3095. this.checkedZeroWidth = false
  3096. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3097. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3098. };
  3099. NativeScrollbars.prototype.update = function (measure) {
  3100. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3101. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3102. var sWidth = measure.nativeBarWidth
  3103. if (needsV) {
  3104. this.vert.style.display = "block"
  3105. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3106. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3107. // A bug in IE8 can cause this value to be negative, so guard it.
  3108. this.vert.firstChild.style.height =
  3109. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3110. } else {
  3111. this.vert.style.display = ""
  3112. this.vert.firstChild.style.height = "0"
  3113. }
  3114. if (needsH) {
  3115. this.horiz.style.display = "block"
  3116. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3117. this.horiz.style.left = measure.barLeft + "px"
  3118. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3119. this.horiz.firstChild.style.width =
  3120. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3121. } else {
  3122. this.horiz.style.display = ""
  3123. this.horiz.firstChild.style.width = "0"
  3124. }
  3125. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3126. if (sWidth == 0) { this.zeroWidthHack() }
  3127. this.checkedZeroWidth = true
  3128. }
  3129. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3130. };
  3131. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3132. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3133. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) }
  3134. };
  3135. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3136. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3137. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) }
  3138. };
  3139. NativeScrollbars.prototype.zeroWidthHack = function () {
  3140. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3141. this.horiz.style.height = this.vert.style.width = w
  3142. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3143. this.disableHoriz = new Delayed
  3144. this.disableVert = new Delayed
  3145. };
  3146. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay) {
  3147. bar.style.pointerEvents = "auto"
  3148. function maybeDisable() {
  3149. // To find out whether the scrollbar is still visible, we
  3150. // check whether the element under the pixel in the bottom
  3151. // left corner of the scrollbar box is the scrollbar box
  3152. // itself (when the bar is still visible) or its filler child
  3153. // (when the bar is hidden). If it is still visible, we keep
  3154. // it enabled, if it's hidden, we disable pointer events.
  3155. var box = bar.getBoundingClientRect()
  3156. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1)
  3157. if (elt != bar) { bar.style.pointerEvents = "none" }
  3158. else { delay.set(1000, maybeDisable) }
  3159. }
  3160. delay.set(1000, maybeDisable)
  3161. };
  3162. NativeScrollbars.prototype.clear = function () {
  3163. var parent = this.horiz.parentNode
  3164. parent.removeChild(this.horiz)
  3165. parent.removeChild(this.vert)
  3166. };
  3167. var NullScrollbars = function () {};
  3168. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3169. NullScrollbars.prototype.setScrollLeft = function () {};
  3170. NullScrollbars.prototype.setScrollTop = function () {};
  3171. NullScrollbars.prototype.clear = function () {};
  3172. function updateScrollbars(cm, measure) {
  3173. if (!measure) { measure = measureForScrollbars(cm) }
  3174. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3175. updateScrollbarsInner(cm, measure)
  3176. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3177. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3178. { updateHeightsInViewport(cm) }
  3179. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3180. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3181. }
  3182. }
  3183. // Re-synchronize the fake scrollbars with the actual size of the
  3184. // content.
  3185. function updateScrollbarsInner(cm, measure) {
  3186. var d = cm.display
  3187. var sizes = d.scrollbars.update(measure)
  3188. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3189. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3190. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3191. if (sizes.right && sizes.bottom) {
  3192. d.scrollbarFiller.style.display = "block"
  3193. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3194. d.scrollbarFiller.style.width = sizes.right + "px"
  3195. } else { d.scrollbarFiller.style.display = "" }
  3196. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3197. d.gutterFiller.style.display = "block"
  3198. d.gutterFiller.style.height = sizes.bottom + "px"
  3199. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3200. } else { d.gutterFiller.style.display = "" }
  3201. }
  3202. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3203. function initScrollbars(cm) {
  3204. if (cm.display.scrollbars) {
  3205. cm.display.scrollbars.clear()
  3206. if (cm.display.scrollbars.addClass)
  3207. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3208. }
  3209. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3210. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3211. // Prevent clicks in the scrollbars from killing focus
  3212. on(node, "mousedown", function () {
  3213. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3214. })
  3215. node.setAttribute("cm-not-content", "true")
  3216. }, function (pos, axis) {
  3217. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3218. else { setScrollTop(cm, pos) }
  3219. }, cm)
  3220. if (cm.display.scrollbars.addClass)
  3221. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3222. }
  3223. // SCROLLING THINGS INTO VIEW
  3224. // If an editor sits on the top or bottom of the window, partially
  3225. // scrolled out of view, this ensures that the cursor is visible.
  3226. function maybeScrollWindow(cm, coords) {
  3227. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3228. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3229. if (coords.top + box.top < 0) { doScroll = true }
  3230. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3231. if (doScroll != null && !phantom) {
  3232. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;"))
  3233. cm.display.lineSpace.appendChild(scrollNode)
  3234. scrollNode.scrollIntoView(doScroll)
  3235. cm.display.lineSpace.removeChild(scrollNode)
  3236. }
  3237. }
  3238. // Scroll a given position into view (immediately), verifying that
  3239. // it actually became visible (as line heights are accurately
  3240. // measured, the position of something may 'drift' during drawing).
  3241. function scrollPosIntoView(cm, pos, end, margin) {
  3242. if (margin == null) { margin = 0 }
  3243. var coords
  3244. for (var limit = 0; limit < 5; limit++) {
  3245. var changed = false
  3246. coords = cursorCoords(cm, pos)
  3247. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3248. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3249. Math.min(coords.top, endCoords.top) - margin,
  3250. Math.max(coords.left, endCoords.left),
  3251. Math.max(coords.bottom, endCoords.bottom) + margin)
  3252. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3253. if (scrollPos.scrollTop != null) {
  3254. setScrollTop(cm, scrollPos.scrollTop)
  3255. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3256. }
  3257. if (scrollPos.scrollLeft != null) {
  3258. setScrollLeft(cm, scrollPos.scrollLeft)
  3259. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3260. }
  3261. if (!changed) { break }
  3262. }
  3263. return coords
  3264. }
  3265. // Scroll a given set of coordinates into view (immediately).
  3266. function scrollIntoView(cm, x1, y1, x2, y2) {
  3267. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2)
  3268. if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) }
  3269. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3270. }
  3271. // Calculate a new scroll position needed to scroll the given
  3272. // rectangle into view. Returns an object with scrollTop and
  3273. // scrollLeft properties. When these are undefined, the
  3274. // vertical/horizontal position does not need to be adjusted.
  3275. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3276. var display = cm.display, snapMargin = textHeight(cm.display)
  3277. if (y1 < 0) { y1 = 0 }
  3278. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3279. var screen = displayHeight(cm), result = {}
  3280. if (y2 - y1 > screen) { y2 = y1 + screen }
  3281. var docBottom = cm.doc.height + paddingVert(display)
  3282. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin
  3283. if (y1 < screentop) {
  3284. result.scrollTop = atTop ? 0 : y1
  3285. } else if (y2 > screentop + screen) {
  3286. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen)
  3287. if (newTop != screentop) { result.scrollTop = newTop }
  3288. }
  3289. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3290. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3291. var tooWide = x2 - x1 > screenw
  3292. if (tooWide) { x2 = x1 + screenw }
  3293. if (x1 < 10)
  3294. { result.scrollLeft = 0 }
  3295. else if (x1 < screenleft)
  3296. { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) }
  3297. else if (x2 > screenw + screenleft - 3)
  3298. { result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw }
  3299. return result
  3300. }
  3301. // Store a relative adjustment to the scroll position in the current
  3302. // operation (to be applied when the operation finishes).
  3303. function addToScrollPos(cm, left, top) {
  3304. if (left != null || top != null) { resolveScrollToPos(cm) }
  3305. if (left != null)
  3306. { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left }
  3307. if (top != null)
  3308. { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top }
  3309. }
  3310. // Make sure that at the end of the operation the current cursor is
  3311. // shown.
  3312. function ensureCursorVisible(cm) {
  3313. resolveScrollToPos(cm)
  3314. var cur = cm.getCursor(), from = cur, to = cur
  3315. if (!cm.options.lineWrapping) {
  3316. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur
  3317. to = Pos(cur.line, cur.ch + 1)
  3318. }
  3319. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}
  3320. }
  3321. // When an operation has its scrollToPos property set, and another
  3322. // scroll action is applied before the end of the operation, this
  3323. // 'simulates' scrolling that position into view in a cheap way, so
  3324. // that the effect of intermediate scroll commands is not ignored.
  3325. function resolveScrollToPos(cm) {
  3326. var range = cm.curOp.scrollToPos
  3327. if (range) {
  3328. cm.curOp.scrollToPos = null
  3329. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3330. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  3331. Math.min(from.top, to.top) - range.margin,
  3332. Math.max(from.right, to.right),
  3333. Math.max(from.bottom, to.bottom) + range.margin)
  3334. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  3335. }
  3336. }
  3337. // Operations are used to wrap a series of changes to the editor
  3338. // state in such a way that each change won't have to update the
  3339. // cursor and display (which would be awkward, slow, and
  3340. // error-prone). Instead, display updates are batched and then all
  3341. // combined and executed at once.
  3342. var nextOpId = 0
  3343. // Start a new operation.
  3344. function startOperation(cm) {
  3345. cm.curOp = {
  3346. cm: cm,
  3347. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3348. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3349. forceUpdate: false, // Used to force a redraw
  3350. updateInput: null, // Whether to reset the input textarea
  3351. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3352. changeObjs: null, // Accumulated changes, for firing change events
  3353. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3354. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3355. selectionChanged: false, // Whether the selection needs to be redrawn
  3356. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3357. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3358. scrollToPos: null, // Used to scroll to a specific position
  3359. focus: false,
  3360. id: ++nextOpId // Unique ID
  3361. }
  3362. pushOperation(cm.curOp)
  3363. }
  3364. // Finish an operation, updating the display and signalling delayed events
  3365. function endOperation(cm) {
  3366. var op = cm.curOp
  3367. finishOperation(op, function (group) {
  3368. for (var i = 0; i < group.ops.length; i++)
  3369. { group.ops[i].cm.curOp = null }
  3370. endOperations(group)
  3371. })
  3372. }
  3373. // The DOM updates done when an operation finishes are batched so
  3374. // that the minimum number of relayouts are required.
  3375. function endOperations(group) {
  3376. var ops = group.ops
  3377. for (var i = 0; i < ops.length; i++) // Read DOM
  3378. { endOperation_R1(ops[i]) }
  3379. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3380. { endOperation_W1(ops[i$1]) }
  3381. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3382. { endOperation_R2(ops[i$2]) }
  3383. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3384. { endOperation_W2(ops[i$3]) }
  3385. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3386. { endOperation_finish(ops[i$4]) }
  3387. }
  3388. function endOperation_R1(op) {
  3389. var cm = op.cm, display = cm.display
  3390. maybeClipScrollbars(cm)
  3391. if (op.updateMaxLine) { findMaxLine(cm) }
  3392. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3393. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3394. op.scrollToPos.to.line >= display.viewTo) ||
  3395. display.maxLineChanged && cm.options.lineWrapping
  3396. op.update = op.mustUpdate &&
  3397. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3398. }
  3399. function endOperation_W1(op) {
  3400. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3401. }
  3402. function endOperation_R2(op) {
  3403. var cm = op.cm, display = cm.display
  3404. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3405. op.barMeasure = measureForScrollbars(cm)
  3406. // If the max line changed since it was last measured, measure it,
  3407. // and ensure the document's width matches it.
  3408. // updateDisplay_W2 will use these properties to do the actual resizing
  3409. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3410. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3411. cm.display.sizerWidth = op.adjustWidthTo
  3412. op.barMeasure.scrollWidth =
  3413. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3414. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3415. }
  3416. if (op.updatedDisplay || op.selectionChanged)
  3417. { op.preparedSelection = display.input.prepareSelection(op.focus) }
  3418. }
  3419. function endOperation_W2(op) {
  3420. var cm = op.cm
  3421. if (op.adjustWidthTo != null) {
  3422. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3423. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3424. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3425. cm.display.maxLineChanged = false
  3426. }
  3427. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  3428. if (op.preparedSelection)
  3429. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3430. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3431. { updateScrollbars(cm, op.barMeasure) }
  3432. if (op.updatedDisplay)
  3433. { setDocumentHeight(cm, op.barMeasure) }
  3434. if (op.selectionChanged) { restartBlink(cm) }
  3435. if (cm.state.focused && op.updateInput)
  3436. { cm.display.input.reset(op.typing) }
  3437. if (takeFocus) { ensureFocus(op.cm) }
  3438. }
  3439. function endOperation_finish(op) {
  3440. var cm = op.cm, display = cm.display, doc = cm.doc
  3441. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3442. // Abort mouse wheel delta measurement, when scrolling explicitly
  3443. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3444. { display.wheelStartX = display.wheelStartY = null }
  3445. // Propagate the scroll position to the actual DOM scroller
  3446. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  3447. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop))
  3448. display.scrollbars.setScrollTop(doc.scrollTop)
  3449. display.scroller.scrollTop = doc.scrollTop
  3450. }
  3451. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  3452. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft))
  3453. display.scrollbars.setScrollLeft(doc.scrollLeft)
  3454. display.scroller.scrollLeft = doc.scrollLeft
  3455. alignHorizontally(cm)
  3456. }
  3457. // If we need to scroll a specific position into view, do so.
  3458. if (op.scrollToPos) {
  3459. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3460. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3461. if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) }
  3462. }
  3463. // Fire events for markers that are hidden/unidden by editing or
  3464. // undoing
  3465. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3466. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3467. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3468. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3469. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3470. if (display.wrapper.offsetHeight)
  3471. { doc.scrollTop = cm.display.scroller.scrollTop }
  3472. // Fire change events, and delayed event handlers
  3473. if (op.changeObjs)
  3474. { signal(cm, "changes", cm, op.changeObjs) }
  3475. if (op.update)
  3476. { op.update.finish() }
  3477. }
  3478. // Run the given function in an operation
  3479. function runInOp(cm, f) {
  3480. if (cm.curOp) { return f() }
  3481. startOperation(cm)
  3482. try { return f() }
  3483. finally { endOperation(cm) }
  3484. }
  3485. // Wraps a function in an operation. Returns the wrapped function.
  3486. function operation(cm, f) {
  3487. return function() {
  3488. if (cm.curOp) { return f.apply(cm, arguments) }
  3489. startOperation(cm)
  3490. try { return f.apply(cm, arguments) }
  3491. finally { endOperation(cm) }
  3492. }
  3493. }
  3494. // Used to add methods to editor and doc instances, wrapping them in
  3495. // operations.
  3496. function methodOp(f) {
  3497. return function() {
  3498. if (this.curOp) { return f.apply(this, arguments) }
  3499. startOperation(this)
  3500. try { return f.apply(this, arguments) }
  3501. finally { endOperation(this) }
  3502. }
  3503. }
  3504. function docMethodOp(f) {
  3505. return function() {
  3506. var cm = this.cm
  3507. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3508. startOperation(cm)
  3509. try { return f.apply(this, arguments) }
  3510. finally { endOperation(cm) }
  3511. }
  3512. }
  3513. // Updates the display.view data structure for a given change to the
  3514. // document. From and to are in pre-change coordinates. Lendiff is
  3515. // the amount of lines added or subtracted by the change. This is
  3516. // used for changes that span multiple lines, or change the way
  3517. // lines are divided into visual lines. regLineChange (below)
  3518. // registers single-line changes.
  3519. function regChange(cm, from, to, lendiff) {
  3520. if (from == null) { from = cm.doc.first }
  3521. if (to == null) { to = cm.doc.first + cm.doc.size }
  3522. if (!lendiff) { lendiff = 0 }
  3523. var display = cm.display
  3524. if (lendiff && to < display.viewTo &&
  3525. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3526. { display.updateLineNumbers = from }
  3527. cm.curOp.viewChanged = true
  3528. if (from >= display.viewTo) { // Change after
  3529. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3530. { resetView(cm) }
  3531. } else if (to <= display.viewFrom) { // Change before
  3532. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3533. resetView(cm)
  3534. } else {
  3535. display.viewFrom += lendiff
  3536. display.viewTo += lendiff
  3537. }
  3538. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3539. resetView(cm)
  3540. } else if (from <= display.viewFrom) { // Top overlap
  3541. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3542. if (cut) {
  3543. display.view = display.view.slice(cut.index)
  3544. display.viewFrom = cut.lineN
  3545. display.viewTo += lendiff
  3546. } else {
  3547. resetView(cm)
  3548. }
  3549. } else if (to >= display.viewTo) { // Bottom overlap
  3550. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3551. if (cut$1) {
  3552. display.view = display.view.slice(0, cut$1.index)
  3553. display.viewTo = cut$1.lineN
  3554. } else {
  3555. resetView(cm)
  3556. }
  3557. } else { // Gap in the middle
  3558. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3559. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3560. if (cutTop && cutBot) {
  3561. display.view = display.view.slice(0, cutTop.index)
  3562. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3563. .concat(display.view.slice(cutBot.index))
  3564. display.viewTo += lendiff
  3565. } else {
  3566. resetView(cm)
  3567. }
  3568. }
  3569. var ext = display.externalMeasured
  3570. if (ext) {
  3571. if (to < ext.lineN)
  3572. { ext.lineN += lendiff }
  3573. else if (from < ext.lineN + ext.size)
  3574. { display.externalMeasured = null }
  3575. }
  3576. }
  3577. // Register a change to a single line. Type must be one of "text",
  3578. // "gutter", "class", "widget"
  3579. function regLineChange(cm, line, type) {
  3580. cm.curOp.viewChanged = true
  3581. var display = cm.display, ext = cm.display.externalMeasured
  3582. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3583. { display.externalMeasured = null }
  3584. if (line < display.viewFrom || line >= display.viewTo) { return }
  3585. var lineView = display.view[findViewIndex(cm, line)]
  3586. if (lineView.node == null) { return }
  3587. var arr = lineView.changes || (lineView.changes = [])
  3588. if (indexOf(arr, type) == -1) { arr.push(type) }
  3589. }
  3590. // Clear the view.
  3591. function resetView(cm) {
  3592. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3593. cm.display.view = []
  3594. cm.display.viewOffset = 0
  3595. }
  3596. function viewCuttingPoint(cm, oldN, newN, dir) {
  3597. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3598. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3599. { return {index: index, lineN: newN} }
  3600. var n = cm.display.viewFrom
  3601. for (var i = 0; i < index; i++)
  3602. { n += view[i].size }
  3603. if (n != oldN) {
  3604. if (dir > 0) {
  3605. if (index == view.length - 1) { return null }
  3606. diff = (n + view[index].size) - oldN
  3607. index++
  3608. } else {
  3609. diff = n - oldN
  3610. }
  3611. oldN += diff; newN += diff
  3612. }
  3613. while (visualLineNo(cm.doc, newN) != newN) {
  3614. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3615. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3616. index += dir
  3617. }
  3618. return {index: index, lineN: newN}
  3619. }
  3620. // Force the view to cover a given range, adding empty view element
  3621. // or clipping off existing ones as needed.
  3622. function adjustView(cm, from, to) {
  3623. var display = cm.display, view = display.view
  3624. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3625. display.view = buildViewArray(cm, from, to)
  3626. display.viewFrom = from
  3627. } else {
  3628. if (display.viewFrom > from)
  3629. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3630. else if (display.viewFrom < from)
  3631. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3632. display.viewFrom = from
  3633. if (display.viewTo < to)
  3634. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3635. else if (display.viewTo > to)
  3636. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3637. }
  3638. display.viewTo = to
  3639. }
  3640. // Count the number of lines in the view whose DOM representation is
  3641. // out of date (or nonexistent).
  3642. function countDirtyView(cm) {
  3643. var view = cm.display.view, dirty = 0
  3644. for (var i = 0; i < view.length; i++) {
  3645. var lineView = view[i]
  3646. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3647. }
  3648. return dirty
  3649. }
  3650. // HIGHLIGHT WORKER
  3651. function startWorker(cm, time) {
  3652. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  3653. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3654. }
  3655. function highlightWorker(cm) {
  3656. var doc = cm.doc
  3657. if (doc.frontier < doc.first) { doc.frontier = doc.first }
  3658. if (doc.frontier >= cm.display.viewTo) { return }
  3659. var end = +new Date + cm.options.workTime
  3660. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier))
  3661. var changedLines = []
  3662. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3663. if (doc.frontier >= cm.display.viewFrom) { // Visible
  3664. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength
  3665. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true)
  3666. line.styles = highlighted.styles
  3667. var oldCls = line.styleClasses, newCls = highlighted.classes
  3668. if (newCls) { line.styleClasses = newCls }
  3669. else if (oldCls) { line.styleClasses = null }
  3670. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3671. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3672. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3673. if (ischange) { changedLines.push(doc.frontier) }
  3674. line.stateAfter = tooLong ? state : copyState(doc.mode, state)
  3675. } else {
  3676. if (line.text.length <= cm.options.maxHighlightLength)
  3677. { processLine(cm, line.text, state) }
  3678. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null
  3679. }
  3680. ++doc.frontier
  3681. if (+new Date > end) {
  3682. startWorker(cm, cm.options.workDelay)
  3683. return true
  3684. }
  3685. })
  3686. if (changedLines.length) { runInOp(cm, function () {
  3687. for (var i = 0; i < changedLines.length; i++)
  3688. { regLineChange(cm, changedLines[i], "text") }
  3689. }) }
  3690. }
  3691. // DISPLAY DRAWING
  3692. var DisplayUpdate = function(cm, viewport, force) {
  3693. var display = cm.display
  3694. this.viewport = viewport
  3695. // Store some values that we'll need later (but don't want to force a relayout for)
  3696. this.visible = visibleLines(display, cm.doc, viewport)
  3697. this.editorIsHidden = !display.wrapper.offsetWidth
  3698. this.wrapperHeight = display.wrapper.clientHeight
  3699. this.wrapperWidth = display.wrapper.clientWidth
  3700. this.oldDisplayWidth = displayWidth(cm)
  3701. this.force = force
  3702. this.dims = getDimensions(cm)
  3703. this.events = []
  3704. };
  3705. DisplayUpdate.prototype.signal = function (emitter, type) {
  3706. if (hasHandler(emitter, type))
  3707. { this.events.push(arguments) }
  3708. };
  3709. DisplayUpdate.prototype.finish = function () {
  3710. var this$1 = this;
  3711. for (var i = 0; i < this.events.length; i++)
  3712. { signal.apply(null, this$1.events[i]) }
  3713. };
  3714. function maybeClipScrollbars(cm) {
  3715. var display = cm.display
  3716. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3717. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3718. display.heightForcer.style.height = scrollGap(cm) + "px"
  3719. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3720. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3721. display.scrollbarsClipped = true
  3722. }
  3723. }
  3724. // Does the actual updating of the line display. Bails out
  3725. // (returning false) when there is nothing to be done and forced is
  3726. // false.
  3727. function updateDisplayIfNeeded(cm, update) {
  3728. var display = cm.display, doc = cm.doc
  3729. if (update.editorIsHidden) {
  3730. resetView(cm)
  3731. return false
  3732. }
  3733. // Bail out if the visible area is already rendered and nothing changed.
  3734. if (!update.force &&
  3735. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3736. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3737. display.renderedView == display.view && countDirtyView(cm) == 0)
  3738. { return false }
  3739. if (maybeUpdateLineNumberWidth(cm)) {
  3740. resetView(cm)
  3741. update.dims = getDimensions(cm)
  3742. }
  3743. // Compute a suitable new viewport (from & to)
  3744. var end = doc.first + doc.size
  3745. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3746. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3747. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3748. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3749. if (sawCollapsedSpans) {
  3750. from = visualLineNo(cm.doc, from)
  3751. to = visualLineEndNo(cm.doc, to)
  3752. }
  3753. var different = from != display.viewFrom || to != display.viewTo ||
  3754. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3755. adjustView(cm, from, to)
  3756. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3757. // Position the mover div to align with the current scroll position
  3758. cm.display.mover.style.top = display.viewOffset + "px"
  3759. var toUpdate = countDirtyView(cm)
  3760. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3761. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3762. { return false }
  3763. // For big changes, we hide the enclosing element during the
  3764. // update, since that speeds up the operations on most browsers.
  3765. var focused = activeElt()
  3766. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3767. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3768. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3769. display.renderedView = display.view
  3770. // There might have been a widget with a focused element that got
  3771. // hidden or updated, if so re-focus it.
  3772. if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() }
  3773. // Prevent selection and cursors from interfering with the scroll
  3774. // width and height.
  3775. removeChildren(display.cursorDiv)
  3776. removeChildren(display.selectionDiv)
  3777. display.gutters.style.height = display.sizer.style.minHeight = 0
  3778. if (different) {
  3779. display.lastWrapHeight = update.wrapperHeight
  3780. display.lastWrapWidth = update.wrapperWidth
  3781. startWorker(cm, 400)
  3782. }
  3783. display.updateLineNumbers = null
  3784. return true
  3785. }
  3786. function postUpdateDisplay(cm, update) {
  3787. var viewport = update.viewport
  3788. for (var first = true;; first = false) {
  3789. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3790. // Clip forced viewport to actual scrollable area.
  3791. if (viewport && viewport.top != null)
  3792. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3793. // Updated line heights might result in the drawn area not
  3794. // actually covering the viewport. Keep looping until it does.
  3795. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3796. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3797. { break }
  3798. }
  3799. if (!updateDisplayIfNeeded(cm, update)) { break }
  3800. updateHeightsInViewport(cm)
  3801. var barMeasure = measureForScrollbars(cm)
  3802. updateSelection(cm)
  3803. updateScrollbars(cm, barMeasure)
  3804. setDocumentHeight(cm, barMeasure)
  3805. }
  3806. update.signal(cm, "update", cm)
  3807. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3808. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3809. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3810. }
  3811. }
  3812. function updateDisplaySimple(cm, viewport) {
  3813. var update = new DisplayUpdate(cm, viewport)
  3814. if (updateDisplayIfNeeded(cm, update)) {
  3815. updateHeightsInViewport(cm)
  3816. postUpdateDisplay(cm, update)
  3817. var barMeasure = measureForScrollbars(cm)
  3818. updateSelection(cm)
  3819. updateScrollbars(cm, barMeasure)
  3820. setDocumentHeight(cm, barMeasure)
  3821. update.finish()
  3822. }
  3823. }
  3824. // Sync the actual display DOM structure with display.view, removing
  3825. // nodes for lines that are no longer in view, and creating the ones
  3826. // that are not there yet, and updating the ones that are out of
  3827. // date.
  3828. function patchDisplay(cm, updateNumbersFrom, dims) {
  3829. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3830. var container = display.lineDiv, cur = container.firstChild
  3831. function rm(node) {
  3832. var next = node.nextSibling
  3833. // Works around a throw-scroll bug in OS X Webkit
  3834. if (webkit && mac && cm.display.currentWheelTarget == node)
  3835. { node.style.display = "none" }
  3836. else
  3837. { node.parentNode.removeChild(node) }
  3838. return next
  3839. }
  3840. var view = display.view, lineN = display.viewFrom
  3841. // Loop over the elements in the view, syncing cur (the DOM nodes
  3842. // in display.lineDiv) with the view as we go.
  3843. for (var i = 0; i < view.length; i++) {
  3844. var lineView = view[i]
  3845. if (lineView.hidden) {
  3846. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3847. var node = buildLineElement(cm, lineView, lineN, dims)
  3848. container.insertBefore(node, cur)
  3849. } else { // Already drawn
  3850. while (cur != lineView.node) { cur = rm(cur) }
  3851. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3852. updateNumbersFrom <= lineN && lineView.lineNumber
  3853. if (lineView.changes) {
  3854. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3855. updateLineForChanges(cm, lineView, lineN, dims)
  3856. }
  3857. if (updateNumber) {
  3858. removeChildren(lineView.lineNumber)
  3859. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3860. }
  3861. cur = lineView.node.nextSibling
  3862. }
  3863. lineN += lineView.size
  3864. }
  3865. while (cur) { cur = rm(cur) }
  3866. }
  3867. function updateGutterSpace(cm) {
  3868. var width = cm.display.gutters.offsetWidth
  3869. cm.display.sizer.style.marginLeft = width + "px"
  3870. }
  3871. function setDocumentHeight(cm, measure) {
  3872. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3873. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3874. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3875. }
  3876. // Rebuild the gutter elements, ensure the margin to the left of the
  3877. // code matches their width.
  3878. function updateGutters(cm) {
  3879. var gutters = cm.display.gutters, specs = cm.options.gutters
  3880. removeChildren(gutters)
  3881. var i = 0
  3882. for (; i < specs.length; ++i) {
  3883. var gutterClass = specs[i]
  3884. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3885. if (gutterClass == "CodeMirror-linenumbers") {
  3886. cm.display.lineGutter = gElt
  3887. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3888. }
  3889. }
  3890. gutters.style.display = i ? "" : "none"
  3891. updateGutterSpace(cm)
  3892. }
  3893. // Make sure the gutters options contains the element
  3894. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3895. function setGuttersForLineNumbers(options) {
  3896. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3897. if (found == -1 && options.lineNumbers) {
  3898. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3899. } else if (found > -1 && !options.lineNumbers) {
  3900. options.gutters = options.gutters.slice(0)
  3901. options.gutters.splice(found, 1)
  3902. }
  3903. }
  3904. // Selection objects are immutable. A new one is created every time
  3905. // the selection changes. A selection is one or more non-overlapping
  3906. // (and non-touching) ranges, sorted, and an integer that indicates
  3907. // which one is the primary selection (the one that's scrolled into
  3908. // view, that getCursor returns, etc).
  3909. var Selection = function(ranges, primIndex) {
  3910. this.ranges = ranges
  3911. this.primIndex = primIndex
  3912. };
  3913. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  3914. Selection.prototype.equals = function (other) {
  3915. var this$1 = this;
  3916. if (other == this) { return true }
  3917. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  3918. for (var i = 0; i < this.ranges.length; i++) {
  3919. var here = this$1.ranges[i], there = other.ranges[i]
  3920. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  3921. }
  3922. return true
  3923. };
  3924. Selection.prototype.deepCopy = function () {
  3925. var this$1 = this;
  3926. var out = []
  3927. for (var i = 0; i < this.ranges.length; i++)
  3928. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  3929. return new Selection(out, this.primIndex)
  3930. };
  3931. Selection.prototype.somethingSelected = function () {
  3932. var this$1 = this;
  3933. for (var i = 0; i < this.ranges.length; i++)
  3934. { if (!this$1.ranges[i].empty()) { return true } }
  3935. return false
  3936. };
  3937. Selection.prototype.contains = function (pos, end) {
  3938. var this$1 = this;
  3939. if (!end) { end = pos }
  3940. for (var i = 0; i < this.ranges.length; i++) {
  3941. var range = this$1.ranges[i]
  3942. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3943. { return i }
  3944. }
  3945. return -1
  3946. };
  3947. var Range = function(anchor, head) {
  3948. this.anchor = anchor; this.head = head
  3949. };
  3950. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  3951. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  3952. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  3953. // Take an unsorted, potentially overlapping set of ranges, and
  3954. // build a selection out of it. 'Consumes' ranges array (modifying
  3955. // it).
  3956. function normalizeSelection(ranges, primIndex) {
  3957. var prim = ranges[primIndex]
  3958. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  3959. primIndex = indexOf(ranges, prim)
  3960. for (var i = 1; i < ranges.length; i++) {
  3961. var cur = ranges[i], prev = ranges[i - 1]
  3962. if (cmp(prev.to(), cur.from()) >= 0) {
  3963. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  3964. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  3965. if (i <= primIndex) { --primIndex }
  3966. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  3967. }
  3968. }
  3969. return new Selection(ranges, primIndex)
  3970. }
  3971. function simpleSelection(anchor, head) {
  3972. return new Selection([new Range(anchor, head || anchor)], 0)
  3973. }
  3974. // Compute the position of the end of a change (its 'to' property
  3975. // refers to the pre-change end).
  3976. function changeEnd(change) {
  3977. if (!change.text) { return change.to }
  3978. return Pos(change.from.line + change.text.length - 1,
  3979. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  3980. }
  3981. // Adjust a position to refer to the post-change position of the
  3982. // same text, or the end of the change if the change covers it.
  3983. function adjustForChange(pos, change) {
  3984. if (cmp(pos, change.from) < 0) { return pos }
  3985. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  3986. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  3987. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  3988. return Pos(line, ch)
  3989. }
  3990. function computeSelAfterChange(doc, change) {
  3991. var out = []
  3992. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3993. var range = doc.sel.ranges[i]
  3994. out.push(new Range(adjustForChange(range.anchor, change),
  3995. adjustForChange(range.head, change)))
  3996. }
  3997. return normalizeSelection(out, doc.sel.primIndex)
  3998. }
  3999. function offsetPos(pos, old, nw) {
  4000. if (pos.line == old.line)
  4001. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4002. else
  4003. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4004. }
  4005. // Used by replaceSelections to allow moving the selection to the
  4006. // start or around the replaced test. Hint may be "start" or "around".
  4007. function computeReplacedSel(doc, changes, hint) {
  4008. var out = []
  4009. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  4010. for (var i = 0; i < changes.length; i++) {
  4011. var change = changes[i]
  4012. var from = offsetPos(change.from, oldPrev, newPrev)
  4013. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  4014. oldPrev = change.to
  4015. newPrev = to
  4016. if (hint == "around") {
  4017. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  4018. out[i] = new Range(inv ? to : from, inv ? from : to)
  4019. } else {
  4020. out[i] = new Range(from, from)
  4021. }
  4022. }
  4023. return new Selection(out, doc.sel.primIndex)
  4024. }
  4025. // Used to get the editor into a consistent state again when options change.
  4026. function loadMode(cm) {
  4027. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  4028. resetModeState(cm)
  4029. }
  4030. function resetModeState(cm) {
  4031. cm.doc.iter(function (line) {
  4032. if (line.stateAfter) { line.stateAfter = null }
  4033. if (line.styles) { line.styles = null }
  4034. })
  4035. cm.doc.frontier = cm.doc.first
  4036. startWorker(cm, 100)
  4037. cm.state.modeGen++
  4038. if (cm.curOp) { regChange(cm) }
  4039. }
  4040. // DOCUMENT DATA STRUCTURE
  4041. // By default, updates that start and end at the beginning of a line
  4042. // are treated specially, in order to make the association of line
  4043. // widgets and marker elements with the text behave more intuitive.
  4044. function isWholeLineUpdate(doc, change) {
  4045. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4046. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4047. }
  4048. // Perform a change on the document data structure.
  4049. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4050. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4051. function update(line, text, spans) {
  4052. updateLine(line, text, spans, estimateHeight)
  4053. signalLater(line, "change", line, change)
  4054. }
  4055. function linesFor(start, end) {
  4056. var result = []
  4057. for (var i = start; i < end; ++i)
  4058. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  4059. return result
  4060. }
  4061. var from = change.from, to = change.to, text = change.text
  4062. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  4063. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  4064. // Adjust the line structure
  4065. if (change.full) {
  4066. doc.insert(0, linesFor(0, text.length))
  4067. doc.remove(text.length, doc.size - text.length)
  4068. } else if (isWholeLineUpdate(doc, change)) {
  4069. // This is a whole-line replace. Treated specially to make
  4070. // sure line objects move the way they are supposed to.
  4071. var added = linesFor(0, text.length - 1)
  4072. update(lastLine, lastLine.text, lastSpans)
  4073. if (nlines) { doc.remove(from.line, nlines) }
  4074. if (added.length) { doc.insert(from.line, added) }
  4075. } else if (firstLine == lastLine) {
  4076. if (text.length == 1) {
  4077. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4078. } else {
  4079. var added$1 = linesFor(1, text.length - 1)
  4080. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4081. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4082. doc.insert(from.line + 1, added$1)
  4083. }
  4084. } else if (text.length == 1) {
  4085. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4086. doc.remove(from.line + 1, nlines)
  4087. } else {
  4088. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4089. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4090. var added$2 = linesFor(1, text.length - 1)
  4091. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4092. doc.insert(from.line + 1, added$2)
  4093. }
  4094. signalLater(doc, "change", doc, change)
  4095. }
  4096. // Call f for all linked documents.
  4097. function linkedDocs(doc, f, sharedHistOnly) {
  4098. function propagate(doc, skip, sharedHist) {
  4099. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4100. var rel = doc.linked[i]
  4101. if (rel.doc == skip) { continue }
  4102. var shared = sharedHist && rel.sharedHist
  4103. if (sharedHistOnly && !shared) { continue }
  4104. f(rel.doc, shared)
  4105. propagate(rel.doc, doc, shared)
  4106. } }
  4107. }
  4108. propagate(doc, null, true)
  4109. }
  4110. // Attach a document to an editor.
  4111. function attachDoc(cm, doc) {
  4112. if (doc.cm) { throw new Error("This document is already in use.") }
  4113. cm.doc = doc
  4114. doc.cm = cm
  4115. estimateLineHeights(cm)
  4116. loadMode(cm)
  4117. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4118. cm.options.mode = doc.modeOption
  4119. regChange(cm)
  4120. }
  4121. function History(startGen) {
  4122. // Arrays of change events and selections. Doing something adds an
  4123. // event to done and clears undo. Undoing moves events from done
  4124. // to undone, redoing moves them in the other direction.
  4125. this.done = []; this.undone = []
  4126. this.undoDepth = Infinity
  4127. // Used to track when changes can be merged into a single undo
  4128. // event
  4129. this.lastModTime = this.lastSelTime = 0
  4130. this.lastOp = this.lastSelOp = null
  4131. this.lastOrigin = this.lastSelOrigin = null
  4132. // Used by the isClean() method
  4133. this.generation = this.maxGeneration = startGen || 1
  4134. }
  4135. // Create a history change event from an updateDoc-style change
  4136. // object.
  4137. function historyChangeFromChange(doc, change) {
  4138. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4139. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4140. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4141. return histChange
  4142. }
  4143. // Pop all selection events off the end of a history array. Stop at
  4144. // a change event.
  4145. function clearSelectionEvents(array) {
  4146. while (array.length) {
  4147. var last = lst(array)
  4148. if (last.ranges) { array.pop() }
  4149. else { break }
  4150. }
  4151. }
  4152. // Find the top change event in the history. Pop off selection
  4153. // events that are in the way.
  4154. function lastChangeEvent(hist, force) {
  4155. if (force) {
  4156. clearSelectionEvents(hist.done)
  4157. return lst(hist.done)
  4158. } else if (hist.done.length && !lst(hist.done).ranges) {
  4159. return lst(hist.done)
  4160. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4161. hist.done.pop()
  4162. return lst(hist.done)
  4163. }
  4164. }
  4165. // Register a change in the history. Merges changes that are within
  4166. // a single operation, or are close together with an origin that
  4167. // allows merging (starting with "+") into a single event.
  4168. function addChangeToHistory(doc, change, selAfter, opId) {
  4169. var hist = doc.history
  4170. hist.undone.length = 0
  4171. var time = +new Date, cur
  4172. var last
  4173. if ((hist.lastOp == opId ||
  4174. hist.lastOrigin == change.origin && change.origin &&
  4175. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4176. change.origin.charAt(0) == "*")) &&
  4177. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4178. // Merge this change into the last event
  4179. last = lst(cur.changes)
  4180. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4181. // Optimized case for simple insertion -- don't want to add
  4182. // new changesets for every character typed
  4183. last.to = changeEnd(change)
  4184. } else {
  4185. // Add new sub-event
  4186. cur.changes.push(historyChangeFromChange(doc, change))
  4187. }
  4188. } else {
  4189. // Can not be merged, start a new event.
  4190. var before = lst(hist.done)
  4191. if (!before || !before.ranges)
  4192. { pushSelectionToHistory(doc.sel, hist.done) }
  4193. cur = {changes: [historyChangeFromChange(doc, change)],
  4194. generation: hist.generation}
  4195. hist.done.push(cur)
  4196. while (hist.done.length > hist.undoDepth) {
  4197. hist.done.shift()
  4198. if (!hist.done[0].ranges) { hist.done.shift() }
  4199. }
  4200. }
  4201. hist.done.push(selAfter)
  4202. hist.generation = ++hist.maxGeneration
  4203. hist.lastModTime = hist.lastSelTime = time
  4204. hist.lastOp = hist.lastSelOp = opId
  4205. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4206. if (!last) { signal(doc, "historyAdded") }
  4207. }
  4208. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4209. var ch = origin.charAt(0)
  4210. return ch == "*" ||
  4211. ch == "+" &&
  4212. prev.ranges.length == sel.ranges.length &&
  4213. prev.somethingSelected() == sel.somethingSelected() &&
  4214. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4215. }
  4216. // Called whenever the selection changes, sets the new selection as
  4217. // the pending selection in the history, and pushes the old pending
  4218. // selection into the 'done' array when it was significantly
  4219. // different (in number of selected ranges, emptiness, or time).
  4220. function addSelectionToHistory(doc, sel, opId, options) {
  4221. var hist = doc.history, origin = options && options.origin
  4222. // A new event is started when the previous origin does not match
  4223. // the current, or the origins don't allow matching. Origins
  4224. // starting with * are always merged, those starting with + are
  4225. // merged when similar and close together in time.
  4226. if (opId == hist.lastSelOp ||
  4227. (origin && hist.lastSelOrigin == origin &&
  4228. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4229. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4230. { hist.done[hist.done.length - 1] = sel }
  4231. else
  4232. { pushSelectionToHistory(sel, hist.done) }
  4233. hist.lastSelTime = +new Date
  4234. hist.lastSelOrigin = origin
  4235. hist.lastSelOp = opId
  4236. if (options && options.clearRedo !== false)
  4237. { clearSelectionEvents(hist.undone) }
  4238. }
  4239. function pushSelectionToHistory(sel, dest) {
  4240. var top = lst(dest)
  4241. if (!(top && top.ranges && top.equals(sel)))
  4242. { dest.push(sel) }
  4243. }
  4244. // Used to store marked span information in the history.
  4245. function attachLocalSpans(doc, change, from, to) {
  4246. var existing = change["spans_" + doc.id], n = 0
  4247. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4248. if (line.markedSpans)
  4249. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4250. ++n
  4251. })
  4252. }
  4253. // When un/re-doing restores text containing marked spans, those
  4254. // that have been explicitly cleared should not be restored.
  4255. function removeClearedSpans(spans) {
  4256. if (!spans) { return null }
  4257. var out
  4258. for (var i = 0; i < spans.length; ++i) {
  4259. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4260. else if (out) { out.push(spans[i]) }
  4261. }
  4262. return !out ? spans : out.length ? out : null
  4263. }
  4264. // Retrieve and filter the old marked spans stored in a change event.
  4265. function getOldSpans(doc, change) {
  4266. var found = change["spans_" + doc.id]
  4267. if (!found) { return null }
  4268. var nw = []
  4269. for (var i = 0; i < change.text.length; ++i)
  4270. { nw.push(removeClearedSpans(found[i])) }
  4271. return nw
  4272. }
  4273. // Used for un/re-doing changes from the history. Combines the
  4274. // result of computing the existing spans with the set of spans that
  4275. // existed in the history (so that deleting around a span and then
  4276. // undoing brings back the span).
  4277. function mergeOldSpans(doc, change) {
  4278. var old = getOldSpans(doc, change)
  4279. var stretched = stretchSpansOverChange(doc, change)
  4280. if (!old) { return stretched }
  4281. if (!stretched) { return old }
  4282. for (var i = 0; i < old.length; ++i) {
  4283. var oldCur = old[i], stretchCur = stretched[i]
  4284. if (oldCur && stretchCur) {
  4285. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4286. var span = stretchCur[j]
  4287. for (var k = 0; k < oldCur.length; ++k)
  4288. { if (oldCur[k].marker == span.marker) { continue spans } }
  4289. oldCur.push(span)
  4290. }
  4291. } else if (stretchCur) {
  4292. old[i] = stretchCur
  4293. }
  4294. }
  4295. return old
  4296. }
  4297. // Used both to provide a JSON-safe object in .getHistory, and, when
  4298. // detaching a document, to split the history in two
  4299. function copyHistoryArray(events, newGroup, instantiateSel) {
  4300. var copy = []
  4301. for (var i = 0; i < events.length; ++i) {
  4302. var event = events[i]
  4303. if (event.ranges) {
  4304. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4305. continue
  4306. }
  4307. var changes = event.changes, newChanges = []
  4308. copy.push({changes: newChanges})
  4309. for (var j = 0; j < changes.length; ++j) {
  4310. var change = changes[j], m = (void 0)
  4311. newChanges.push({from: change.from, to: change.to, text: change.text})
  4312. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4313. if (indexOf(newGroup, Number(m[1])) > -1) {
  4314. lst(newChanges)[prop] = change[prop]
  4315. delete change[prop]
  4316. }
  4317. } } }
  4318. }
  4319. }
  4320. return copy
  4321. }
  4322. // The 'scroll' parameter given to many of these indicated whether
  4323. // the new cursor position should be scrolled into view after
  4324. // modifying the selection.
  4325. // If shift is held or the extend flag is set, extends a range to
  4326. // include a given position (and optionally a second position).
  4327. // Otherwise, simply returns the range between the given positions.
  4328. // Used for cursor motion and such.
  4329. function extendRange(doc, range, head, other) {
  4330. if (doc.cm && doc.cm.display.shift || doc.extend) {
  4331. var anchor = range.anchor
  4332. if (other) {
  4333. var posBefore = cmp(head, anchor) < 0
  4334. if (posBefore != (cmp(other, anchor) < 0)) {
  4335. anchor = head
  4336. head = other
  4337. } else if (posBefore != (cmp(head, other) < 0)) {
  4338. head = other
  4339. }
  4340. }
  4341. return new Range(anchor, head)
  4342. } else {
  4343. return new Range(other || head, head)
  4344. }
  4345. }
  4346. // Extend the primary selection range, discard the rest.
  4347. function extendSelection(doc, head, other, options) {
  4348. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options)
  4349. }
  4350. // Extend all selections (pos is an array of selections with length
  4351. // equal the number of selections)
  4352. function extendSelections(doc, heads, options) {
  4353. var out = []
  4354. for (var i = 0; i < doc.sel.ranges.length; i++)
  4355. { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) }
  4356. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4357. setSelection(doc, newSel, options)
  4358. }
  4359. // Updates a single range in the selection.
  4360. function replaceOneSelection(doc, i, range, options) {
  4361. var ranges = doc.sel.ranges.slice(0)
  4362. ranges[i] = range
  4363. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4364. }
  4365. // Reset the selection to a single range.
  4366. function setSimpleSelection(doc, anchor, head, options) {
  4367. setSelection(doc, simpleSelection(anchor, head), options)
  4368. }
  4369. // Give beforeSelectionChange handlers a change to influence a
  4370. // selection update.
  4371. function filterSelectionChange(doc, sel, options) {
  4372. var obj = {
  4373. ranges: sel.ranges,
  4374. update: function(ranges) {
  4375. var this$1 = this;
  4376. this.ranges = []
  4377. for (var i = 0; i < ranges.length; i++)
  4378. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4379. clipPos(doc, ranges[i].head)) }
  4380. },
  4381. origin: options && options.origin
  4382. }
  4383. signal(doc, "beforeSelectionChange", doc, obj)
  4384. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4385. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4386. else { return sel }
  4387. }
  4388. function setSelectionReplaceHistory(doc, sel, options) {
  4389. var done = doc.history.done, last = lst(done)
  4390. if (last && last.ranges) {
  4391. done[done.length - 1] = sel
  4392. setSelectionNoUndo(doc, sel, options)
  4393. } else {
  4394. setSelection(doc, sel, options)
  4395. }
  4396. }
  4397. // Set a new selection.
  4398. function setSelection(doc, sel, options) {
  4399. setSelectionNoUndo(doc, sel, options)
  4400. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4401. }
  4402. function setSelectionNoUndo(doc, sel, options) {
  4403. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4404. { sel = filterSelectionChange(doc, sel, options) }
  4405. var bias = options && options.bias ||
  4406. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4407. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4408. if (!(options && options.scroll === false) && doc.cm)
  4409. { ensureCursorVisible(doc.cm) }
  4410. }
  4411. function setSelectionInner(doc, sel) {
  4412. if (sel.equals(doc.sel)) { return }
  4413. doc.sel = sel
  4414. if (doc.cm) {
  4415. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4416. signalCursorActivity(doc.cm)
  4417. }
  4418. signalLater(doc, "cursorActivity", doc)
  4419. }
  4420. // Verify that the selection does not partially select any atomic
  4421. // marked ranges.
  4422. function reCheckSelection(doc) {
  4423. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll)
  4424. }
  4425. // Return a selection that does not partially select any atomic
  4426. // ranges.
  4427. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4428. var out
  4429. for (var i = 0; i < sel.ranges.length; i++) {
  4430. var range = sel.ranges[i]
  4431. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4432. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4433. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4434. if (out || newAnchor != range.anchor || newHead != range.head) {
  4435. if (!out) { out = sel.ranges.slice(0, i) }
  4436. out[i] = new Range(newAnchor, newHead)
  4437. }
  4438. }
  4439. return out ? normalizeSelection(out, sel.primIndex) : sel
  4440. }
  4441. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4442. var line = getLine(doc, pos.line)
  4443. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4444. var sp = line.markedSpans[i], m = sp.marker
  4445. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4446. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4447. if (mayClear) {
  4448. signal(m, "beforeCursorEnter")
  4449. if (m.explicitlyCleared) {
  4450. if (!line.markedSpans) { break }
  4451. else {--i; continue}
  4452. }
  4453. }
  4454. if (!m.atomic) { continue }
  4455. if (oldPos) {
  4456. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4457. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4458. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4459. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4460. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4461. }
  4462. var far = m.find(dir < 0 ? -1 : 1)
  4463. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4464. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4465. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4466. }
  4467. } }
  4468. return pos
  4469. }
  4470. // Ensure a given position is not inside an atomic range.
  4471. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4472. var dir = bias || 1
  4473. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4474. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4475. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4476. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4477. if (!found) {
  4478. doc.cantEdit = true
  4479. return Pos(doc.first, 0)
  4480. }
  4481. return found
  4482. }
  4483. function movePos(doc, pos, dir, line) {
  4484. if (dir < 0 && pos.ch == 0) {
  4485. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4486. else { return null }
  4487. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4488. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4489. else { return null }
  4490. } else {
  4491. return new Pos(pos.line, pos.ch + dir)
  4492. }
  4493. }
  4494. function selectAll(cm) {
  4495. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4496. }
  4497. // UPDATING
  4498. // Allow "beforeChange" event handlers to influence a change
  4499. function filterChange(doc, change, update) {
  4500. var obj = {
  4501. canceled: false,
  4502. from: change.from,
  4503. to: change.to,
  4504. text: change.text,
  4505. origin: change.origin,
  4506. cancel: function () { return obj.canceled = true; }
  4507. }
  4508. if (update) { obj.update = function (from, to, text, origin) {
  4509. if (from) { obj.from = clipPos(doc, from) }
  4510. if (to) { obj.to = clipPos(doc, to) }
  4511. if (text) { obj.text = text }
  4512. if (origin !== undefined) { obj.origin = origin }
  4513. } }
  4514. signal(doc, "beforeChange", doc, obj)
  4515. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4516. if (obj.canceled) { return null }
  4517. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4518. }
  4519. // Apply a change to a document, and add it to the document's
  4520. // history, and propagating it to all linked documents.
  4521. function makeChange(doc, change, ignoreReadOnly) {
  4522. if (doc.cm) {
  4523. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4524. if (doc.cm.state.suppressEdits) { return }
  4525. }
  4526. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4527. change = filterChange(doc, change, true)
  4528. if (!change) { return }
  4529. }
  4530. // Possibly split or suppress the update based on the presence
  4531. // of read-only spans in its range.
  4532. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4533. if (split) {
  4534. for (var i = split.length - 1; i >= 0; --i)
  4535. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) }
  4536. } else {
  4537. makeChangeInner(doc, change)
  4538. }
  4539. }
  4540. function makeChangeInner(doc, change) {
  4541. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4542. var selAfter = computeSelAfterChange(doc, change)
  4543. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4544. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4545. var rebased = []
  4546. linkedDocs(doc, function (doc, sharedHist) {
  4547. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4548. rebaseHist(doc.history, change)
  4549. rebased.push(doc.history)
  4550. }
  4551. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4552. })
  4553. }
  4554. // Revert a change stored in a document's history.
  4555. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4556. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4557. var hist = doc.history, event, selAfter = doc.sel
  4558. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4559. // Verify that there is a useable event (so that ctrl-z won't
  4560. // needlessly clear selection events)
  4561. var i = 0
  4562. for (; i < source.length; i++) {
  4563. event = source[i]
  4564. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4565. { break }
  4566. }
  4567. if (i == source.length) { return }
  4568. hist.lastOrigin = hist.lastSelOrigin = null
  4569. for (;;) {
  4570. event = source.pop()
  4571. if (event.ranges) {
  4572. pushSelectionToHistory(event, dest)
  4573. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4574. setSelection(doc, event, {clearRedo: false})
  4575. return
  4576. }
  4577. selAfter = event
  4578. }
  4579. else { break }
  4580. }
  4581. // Build up a reverse change object to add to the opposite history
  4582. // stack (redo when undoing, and vice versa).
  4583. var antiChanges = []
  4584. pushSelectionToHistory(selAfter, dest)
  4585. dest.push({changes: antiChanges, generation: hist.generation})
  4586. hist.generation = event.generation || ++hist.maxGeneration
  4587. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4588. var loop = function ( i ) {
  4589. var change = event.changes[i]
  4590. change.origin = type
  4591. if (filter && !filterChange(doc, change, false)) {
  4592. source.length = 0
  4593. return {}
  4594. }
  4595. antiChanges.push(historyChangeFromChange(doc, change))
  4596. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4597. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4598. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4599. var rebased = []
  4600. // Propagate to the linked documents
  4601. linkedDocs(doc, function (doc, sharedHist) {
  4602. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4603. rebaseHist(doc.history, change)
  4604. rebased.push(doc.history)
  4605. }
  4606. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4607. })
  4608. };
  4609. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4610. var returned = loop( i$1 );
  4611. if ( returned ) return returned.v;
  4612. }
  4613. }
  4614. // Sub-views need their line numbers shifted when text is added
  4615. // above or below them in the parent document.
  4616. function shiftDoc(doc, distance) {
  4617. if (distance == 0) { return }
  4618. doc.first += distance
  4619. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4620. Pos(range.anchor.line + distance, range.anchor.ch),
  4621. Pos(range.head.line + distance, range.head.ch)
  4622. ); }), doc.sel.primIndex)
  4623. if (doc.cm) {
  4624. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4625. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4626. { regLineChange(doc.cm, l, "gutter") }
  4627. }
  4628. }
  4629. // More lower-level change function, handling only a single document
  4630. // (not linked ones).
  4631. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4632. if (doc.cm && !doc.cm.curOp)
  4633. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4634. if (change.to.line < doc.first) {
  4635. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4636. return
  4637. }
  4638. if (change.from.line > doc.lastLine()) { return }
  4639. // Clip the change to the size of this doc
  4640. if (change.from.line < doc.first) {
  4641. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4642. shiftDoc(doc, shift)
  4643. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4644. text: [lst(change.text)], origin: change.origin}
  4645. }
  4646. var last = doc.lastLine()
  4647. if (change.to.line > last) {
  4648. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4649. text: [change.text[0]], origin: change.origin}
  4650. }
  4651. change.removed = getBetween(doc, change.from, change.to)
  4652. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4653. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4654. else { updateDoc(doc, change, spans) }
  4655. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4656. }
  4657. // Handle the interaction of a change to a document with the editor
  4658. // that this document is part of.
  4659. function makeChangeSingleDocInEditor(cm, change, spans) {
  4660. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4661. var recomputeMaxLength = false, checkWidthStart = from.line
  4662. if (!cm.options.lineWrapping) {
  4663. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4664. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4665. if (line == display.maxLine) {
  4666. recomputeMaxLength = true
  4667. return true
  4668. }
  4669. })
  4670. }
  4671. if (doc.sel.contains(change.from, change.to) > -1)
  4672. { signalCursorActivity(cm) }
  4673. updateDoc(doc, change, spans, estimateHeight(cm))
  4674. if (!cm.options.lineWrapping) {
  4675. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4676. var len = lineLength(line)
  4677. if (len > display.maxLineLength) {
  4678. display.maxLine = line
  4679. display.maxLineLength = len
  4680. display.maxLineChanged = true
  4681. recomputeMaxLength = false
  4682. }
  4683. })
  4684. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4685. }
  4686. // Adjust frontier, schedule worker
  4687. doc.frontier = Math.min(doc.frontier, from.line)
  4688. startWorker(cm, 400)
  4689. var lendiff = change.text.length - (to.line - from.line) - 1
  4690. // Remember that these lines changed, for updating the display
  4691. if (change.full)
  4692. { regChange(cm) }
  4693. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4694. { regLineChange(cm, from.line, "text") }
  4695. else
  4696. { regChange(cm, from.line, to.line + 1, lendiff) }
  4697. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4698. if (changeHandler || changesHandler) {
  4699. var obj = {
  4700. from: from, to: to,
  4701. text: change.text,
  4702. removed: change.removed,
  4703. origin: change.origin
  4704. }
  4705. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4706. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4707. }
  4708. cm.display.selForContextMenu = null
  4709. }
  4710. function replaceRange(doc, code, from, to, origin) {
  4711. if (!to) { to = from }
  4712. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp }
  4713. if (typeof code == "string") { code = doc.splitLines(code) }
  4714. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4715. }
  4716. // Rebasing/resetting history to deal with externally-sourced changes
  4717. function rebaseHistSelSingle(pos, from, to, diff) {
  4718. if (to < pos.line) {
  4719. pos.line += diff
  4720. } else if (from < pos.line) {
  4721. pos.line = from
  4722. pos.ch = 0
  4723. }
  4724. }
  4725. // Tries to rebase an array of history events given a change in the
  4726. // document. If the change touches the same lines as the event, the
  4727. // event, and everything 'behind' it, is discarded. If the change is
  4728. // before the event, the event's positions are updated. Uses a
  4729. // copy-on-write scheme for the positions, to avoid having to
  4730. // reallocate them all on every rebase, but also avoid problems with
  4731. // shared position objects being unsafely updated.
  4732. function rebaseHistArray(array, from, to, diff) {
  4733. for (var i = 0; i < array.length; ++i) {
  4734. var sub = array[i], ok = true
  4735. if (sub.ranges) {
  4736. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4737. for (var j = 0; j < sub.ranges.length; j++) {
  4738. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4739. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4740. }
  4741. continue
  4742. }
  4743. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4744. var cur = sub.changes[j$1]
  4745. if (to < cur.from.line) {
  4746. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4747. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4748. } else if (from <= cur.to.line) {
  4749. ok = false
  4750. break
  4751. }
  4752. }
  4753. if (!ok) {
  4754. array.splice(0, i + 1)
  4755. i = 0
  4756. }
  4757. }
  4758. }
  4759. function rebaseHist(hist, change) {
  4760. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4761. rebaseHistArray(hist.done, from, to, diff)
  4762. rebaseHistArray(hist.undone, from, to, diff)
  4763. }
  4764. // Utility for applying a change to a line by handle or number,
  4765. // returning the number and optionally registering the line as
  4766. // changed.
  4767. function changeLine(doc, handle, changeType, op) {
  4768. var no = handle, line = handle
  4769. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4770. else { no = lineNo(handle) }
  4771. if (no == null) { return null }
  4772. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4773. return line
  4774. }
  4775. // The document is represented as a BTree consisting of leaves, with
  4776. // chunk of lines in them, and branches, with up to ten leaves or
  4777. // other branch nodes below them. The top node is always a branch
  4778. // node, and is the document object itself (meaning it has
  4779. // additional methods and properties).
  4780. //
  4781. // All nodes have parent links. The tree is used both to go from
  4782. // line numbers to line objects, and to go from objects to numbers.
  4783. // It also indexes by height, and is used to convert between height
  4784. // and line object, and to find the total height of the document.
  4785. //
  4786. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4787. var LeafChunk = function(lines) {
  4788. var this$1 = this;
  4789. this.lines = lines
  4790. this.parent = null
  4791. var height = 0
  4792. for (var i = 0; i < lines.length; ++i) {
  4793. lines[i].parent = this$1
  4794. height += lines[i].height
  4795. }
  4796. this.height = height
  4797. };
  4798. LeafChunk.prototype.chunkSize = function () { return this.lines.length };
  4799. // Remove the n lines at offset 'at'.
  4800. LeafChunk.prototype.removeInner = function (at, n) {
  4801. var this$1 = this;
  4802. for (var i = at, e = at + n; i < e; ++i) {
  4803. var line = this$1.lines[i]
  4804. this$1.height -= line.height
  4805. cleanUpLine(line)
  4806. signalLater(line, "delete")
  4807. }
  4808. this.lines.splice(at, n)
  4809. };
  4810. // Helper used to collapse a small branch into a single leaf.
  4811. LeafChunk.prototype.collapse = function (lines) {
  4812. lines.push.apply(lines, this.lines)
  4813. };
  4814. // Insert the given array of lines at offset 'at', count them as
  4815. // having the given height.
  4816. LeafChunk.prototype.insertInner = function (at, lines, height) {
  4817. var this$1 = this;
  4818. this.height += height
  4819. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4820. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4821. };
  4822. // Used to iterate over a part of the tree.
  4823. LeafChunk.prototype.iterN = function (at, n, op) {
  4824. var this$1 = this;
  4825. for (var e = at + n; at < e; ++at)
  4826. { if (op(this$1.lines[at])) { return true } }
  4827. };
  4828. var BranchChunk = function(children) {
  4829. var this$1 = this;
  4830. this.children = children
  4831. var size = 0, height = 0
  4832. for (var i = 0; i < children.length; ++i) {
  4833. var ch = children[i]
  4834. size += ch.chunkSize(); height += ch.height
  4835. ch.parent = this$1
  4836. }
  4837. this.size = size
  4838. this.height = height
  4839. this.parent = null
  4840. };
  4841. BranchChunk.prototype.chunkSize = function () { return this.size };
  4842. BranchChunk.prototype.removeInner = function (at, n) {
  4843. var this$1 = this;
  4844. this.size -= n
  4845. for (var i = 0; i < this.children.length; ++i) {
  4846. var child = this$1.children[i], sz = child.chunkSize()
  4847. if (at < sz) {
  4848. var rm = Math.min(n, sz - at), oldHeight = child.height
  4849. child.removeInner(at, rm)
  4850. this$1.height -= oldHeight - child.height
  4851. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  4852. if ((n -= rm) == 0) { break }
  4853. at = 0
  4854. } else { at -= sz }
  4855. }
  4856. // If the result is smaller than 25 lines, ensure that it is a
  4857. // single leaf node.
  4858. if (this.size - n < 25 &&
  4859. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  4860. var lines = []
  4861. this.collapse(lines)
  4862. this.children = [new LeafChunk(lines)]
  4863. this.children[0].parent = this
  4864. }
  4865. };
  4866. BranchChunk.prototype.collapse = function (lines) {
  4867. var this$1 = this;
  4868. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  4869. };
  4870. BranchChunk.prototype.insertInner = function (at, lines, height) {
  4871. var this$1 = this;
  4872. this.size += lines.length
  4873. this.height += height
  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. child.insertInner(at, lines, height)
  4878. if (child.lines && child.lines.length > 50) {
  4879. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  4880. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  4881. var remaining = child.lines.length % 25 + 25
  4882. for (var pos = remaining; pos < child.lines.length;) {
  4883. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  4884. child.height -= leaf.height
  4885. this$1.children.splice(++i, 0, leaf)
  4886. leaf.parent = this$1
  4887. }
  4888. child.lines = child.lines.slice(0, remaining)
  4889. this$1.maybeSpill()
  4890. }
  4891. break
  4892. }
  4893. at -= sz
  4894. }
  4895. };
  4896. // When a node has grown, check whether it should be split.
  4897. BranchChunk.prototype.maybeSpill = function () {
  4898. if (this.children.length <= 10) { return }
  4899. var me = this
  4900. do {
  4901. var spilled = me.children.splice(me.children.length - 5, 5)
  4902. var sibling = new BranchChunk(spilled)
  4903. if (!me.parent) { // Become the parent node
  4904. var copy = new BranchChunk(me.children)
  4905. copy.parent = me
  4906. me.children = [copy, sibling]
  4907. me = copy
  4908. } else {
  4909. me.size -= sibling.size
  4910. me.height -= sibling.height
  4911. var myIndex = indexOf(me.parent.children, me)
  4912. me.parent.children.splice(myIndex + 1, 0, sibling)
  4913. }
  4914. sibling.parent = me.parent
  4915. } while (me.children.length > 10)
  4916. me.parent.maybeSpill()
  4917. };
  4918. BranchChunk.prototype.iterN = function (at, n, op) {
  4919. var this$1 = this;
  4920. for (var i = 0; i < this.children.length; ++i) {
  4921. var child = this$1.children[i], sz = child.chunkSize()
  4922. if (at < sz) {
  4923. var used = Math.min(n, sz - at)
  4924. if (child.iterN(at, used, op)) { return true }
  4925. if ((n -= used) == 0) { break }
  4926. at = 0
  4927. } else { at -= sz }
  4928. }
  4929. };
  4930. // Line widgets are block elements displayed above or below a line.
  4931. var LineWidget = function(doc, node, options) {
  4932. var this$1 = this;
  4933. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  4934. { this$1[opt] = options[opt] } } }
  4935. this.doc = doc
  4936. this.node = node
  4937. };
  4938. LineWidget.prototype.clear = function () {
  4939. var this$1 = this;
  4940. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  4941. if (no == null || !ws) { return }
  4942. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  4943. if (!ws.length) { line.widgets = null }
  4944. var height = widgetHeight(this)
  4945. updateLineHeight(line, Math.max(0, line.height - height))
  4946. if (cm) {
  4947. runInOp(cm, function () {
  4948. adjustScrollWhenAboveVisible(cm, line, -height)
  4949. regLineChange(cm, no, "widget")
  4950. })
  4951. signalLater(cm, "lineWidgetCleared", cm, this, no)
  4952. }
  4953. };
  4954. LineWidget.prototype.changed = function () {
  4955. var this$1 = this;
  4956. var oldH = this.height, cm = this.doc.cm, line = this.line
  4957. this.height = null
  4958. var diff = widgetHeight(this) - oldH
  4959. if (!diff) { return }
  4960. updateLineHeight(line, line.height + diff)
  4961. if (cm) {
  4962. runInOp(cm, function () {
  4963. cm.curOp.forceUpdate = true
  4964. adjustScrollWhenAboveVisible(cm, line, diff)
  4965. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line))
  4966. })
  4967. }
  4968. };
  4969. eventMixin(LineWidget)
  4970. function adjustScrollWhenAboveVisible(cm, line, diff) {
  4971. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  4972. { addToScrollPos(cm, null, diff) }
  4973. }
  4974. function addLineWidget(doc, handle, node, options) {
  4975. var widget = new LineWidget(doc, node, options)
  4976. var cm = doc.cm
  4977. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  4978. changeLine(doc, handle, "widget", function (line) {
  4979. var widgets = line.widgets || (line.widgets = [])
  4980. if (widget.insertAt == null) { widgets.push(widget) }
  4981. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  4982. widget.line = line
  4983. if (cm && !lineIsHidden(doc, line)) {
  4984. var aboveVisible = heightAtLine(line) < doc.scrollTop
  4985. updateLineHeight(line, line.height + widgetHeight(widget))
  4986. if (aboveVisible) { addToScrollPos(cm, null, widget.height) }
  4987. cm.curOp.forceUpdate = true
  4988. }
  4989. return true
  4990. })
  4991. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle))
  4992. return widget
  4993. }
  4994. // TEXTMARKERS
  4995. // Created with markText and setBookmark methods. A TextMarker is a
  4996. // handle that can be used to clear or find a marked position in the
  4997. // document. Line objects hold arrays (markedSpans) containing
  4998. // {from, to, marker} object pointing to such marker objects, and
  4999. // indicating that such a marker is present on that line. Multiple
  5000. // lines may point to the same marker when it spans across lines.
  5001. // The spans will have null for their from/to properties when the
  5002. // marker continues beyond the start/end of the line. Markers have
  5003. // links back to the lines they currently touch.
  5004. // Collapsed markers have unique ids, in order to be able to order
  5005. // them, which is needed for uniquely determining an outer marker
  5006. // when they overlap (they may nest, but not partially overlap).
  5007. var nextMarkerId = 0
  5008. var TextMarker = function(doc, type) {
  5009. this.lines = []
  5010. this.type = type
  5011. this.doc = doc
  5012. this.id = ++nextMarkerId
  5013. };
  5014. // Clear the marker.
  5015. TextMarker.prototype.clear = function () {
  5016. var this$1 = this;
  5017. if (this.explicitlyCleared) { return }
  5018. var cm = this.doc.cm, withOp = cm && !cm.curOp
  5019. if (withOp) { startOperation(cm) }
  5020. if (hasHandler(this, "clear")) {
  5021. var found = this.find()
  5022. if (found) { signalLater(this, "clear", found.from, found.to) }
  5023. }
  5024. var min = null, max = null
  5025. for (var i = 0; i < this.lines.length; ++i) {
  5026. var line = this$1.lines[i]
  5027. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5028. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  5029. else if (cm) {
  5030. if (span.to != null) { max = lineNo(line) }
  5031. if (span.from != null) { min = lineNo(line) }
  5032. }
  5033. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  5034. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5035. { updateLineHeight(line, textHeight(cm.display)) }
  5036. }
  5037. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5038. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  5039. if (len > cm.display.maxLineLength) {
  5040. cm.display.maxLine = visual
  5041. cm.display.maxLineLength = len
  5042. cm.display.maxLineChanged = true
  5043. }
  5044. } }
  5045. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  5046. this.lines.length = 0
  5047. this.explicitlyCleared = true
  5048. if (this.atomic && this.doc.cantEdit) {
  5049. this.doc.cantEdit = false
  5050. if (cm) { reCheckSelection(cm.doc) }
  5051. }
  5052. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) }
  5053. if (withOp) { endOperation(cm) }
  5054. if (this.parent) { this.parent.clear() }
  5055. };
  5056. // Find the position of the marker in the document. Returns a {from,
  5057. // to} object by default. Side can be passed to get a specific side
  5058. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5059. // Pos objects returned contain a line object, rather than a line
  5060. // number (used to prevent looking up the same line twice).
  5061. TextMarker.prototype.find = function (side, lineObj) {
  5062. var this$1 = this;
  5063. if (side == null && this.type == "bookmark") { side = 1 }
  5064. var from, to
  5065. for (var i = 0; i < this.lines.length; ++i) {
  5066. var line = this$1.lines[i]
  5067. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5068. if (span.from != null) {
  5069. from = Pos(lineObj ? line : lineNo(line), span.from)
  5070. if (side == -1) { return from }
  5071. }
  5072. if (span.to != null) {
  5073. to = Pos(lineObj ? line : lineNo(line), span.to)
  5074. if (side == 1) { return to }
  5075. }
  5076. }
  5077. return from && {from: from, to: to}
  5078. };
  5079. // Signals that the marker's widget changed, and surrounding layout
  5080. // should be recomputed.
  5081. TextMarker.prototype.changed = function () {
  5082. var this$1 = this;
  5083. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5084. if (!pos || !cm) { return }
  5085. runInOp(cm, function () {
  5086. var line = pos.line, lineN = lineNo(pos.line)
  5087. var view = findViewForLine(cm, lineN)
  5088. if (view) {
  5089. clearLineMeasurementCacheFor(view)
  5090. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5091. }
  5092. cm.curOp.updateMaxLine = true
  5093. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5094. var oldHeight = widget.height
  5095. widget.height = null
  5096. var dHeight = widgetHeight(widget) - oldHeight
  5097. if (dHeight)
  5098. { updateLineHeight(line, line.height + dHeight) }
  5099. }
  5100. signalLater(cm, "markerChanged", cm, this$1)
  5101. })
  5102. };
  5103. TextMarker.prototype.attachLine = function (line) {
  5104. if (!this.lines.length && this.doc.cm) {
  5105. var op = this.doc.cm.curOp
  5106. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5107. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5108. }
  5109. this.lines.push(line)
  5110. };
  5111. TextMarker.prototype.detachLine = function (line) {
  5112. this.lines.splice(indexOf(this.lines, line), 1)
  5113. if (!this.lines.length && this.doc.cm) {
  5114. var op = this.doc.cm.curOp
  5115. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5116. }
  5117. };
  5118. eventMixin(TextMarker)
  5119. // Create a marker, wire it up to the right lines, and
  5120. function markText(doc, from, to, options, type) {
  5121. // Shared markers (across linked documents) are handled separately
  5122. // (markTextShared will call out to this again, once per
  5123. // document).
  5124. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5125. // Ensure we are in an operation.
  5126. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5127. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5128. if (options) { copyObj(options, marker, false) }
  5129. // Don't connect empty markers unless clearWhenEmpty is false
  5130. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5131. { return marker }
  5132. if (marker.replacedWith) {
  5133. // Showing up as a widget implies collapsed (widget replaces text)
  5134. marker.collapsed = true
  5135. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget")
  5136. marker.widgetNode.setAttribute("role", "presentation") // hide from accessibility tree
  5137. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5138. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5139. }
  5140. if (marker.collapsed) {
  5141. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5142. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5143. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5144. seeCollapsedSpans()
  5145. }
  5146. if (marker.addToHistory)
  5147. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5148. var curLine = from.line, cm = doc.cm, updateMaxLine
  5149. doc.iter(curLine, to.line + 1, function (line) {
  5150. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5151. { updateMaxLine = true }
  5152. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5153. addMarkedSpan(line, new MarkedSpan(marker,
  5154. curLine == from.line ? from.ch : null,
  5155. curLine == to.line ? to.ch : null))
  5156. ++curLine
  5157. })
  5158. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5159. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5160. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5161. }) }
  5162. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5163. if (marker.readOnly) {
  5164. seeReadOnlySpans()
  5165. if (doc.history.done.length || doc.history.undone.length)
  5166. { doc.clearHistory() }
  5167. }
  5168. if (marker.collapsed) {
  5169. marker.id = ++nextMarkerId
  5170. marker.atomic = true
  5171. }
  5172. if (cm) {
  5173. // Sync editor state
  5174. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5175. if (marker.collapsed)
  5176. { regChange(cm, from.line, to.line + 1) }
  5177. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5178. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5179. if (marker.atomic) { reCheckSelection(cm.doc) }
  5180. signalLater(cm, "markerAdded", cm, marker)
  5181. }
  5182. return marker
  5183. }
  5184. // SHARED TEXTMARKERS
  5185. // A shared marker spans multiple linked documents. It is
  5186. // implemented as a meta-marker-object controlling multiple normal
  5187. // markers.
  5188. var SharedTextMarker = function(markers, primary) {
  5189. var this$1 = this;
  5190. this.markers = markers
  5191. this.primary = primary
  5192. for (var i = 0; i < markers.length; ++i)
  5193. { markers[i].parent = this$1 }
  5194. };
  5195. SharedTextMarker.prototype.clear = function () {
  5196. var this$1 = this;
  5197. if (this.explicitlyCleared) { return }
  5198. this.explicitlyCleared = true
  5199. for (var i = 0; i < this.markers.length; ++i)
  5200. { this$1.markers[i].clear() }
  5201. signalLater(this, "clear")
  5202. };
  5203. SharedTextMarker.prototype.find = function (side, lineObj) {
  5204. return this.primary.find(side, lineObj)
  5205. };
  5206. eventMixin(SharedTextMarker)
  5207. function markTextShared(doc, from, to, options, type) {
  5208. options = copyObj(options)
  5209. options.shared = false
  5210. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5211. var widget = options.widgetNode
  5212. linkedDocs(doc, function (doc) {
  5213. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5214. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5215. for (var i = 0; i < doc.linked.length; ++i)
  5216. { if (doc.linked[i].isParent) { return } }
  5217. primary = lst(markers)
  5218. })
  5219. return new SharedTextMarker(markers, primary)
  5220. }
  5221. function findSharedMarkers(doc) {
  5222. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5223. }
  5224. function copySharedMarkers(doc, markers) {
  5225. for (var i = 0; i < markers.length; i++) {
  5226. var marker = markers[i], pos = marker.find()
  5227. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5228. if (cmp(mFrom, mTo)) {
  5229. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5230. marker.markers.push(subMark)
  5231. subMark.parent = marker
  5232. }
  5233. }
  5234. }
  5235. function detachSharedMarkers(markers) {
  5236. var loop = function ( i ) {
  5237. var marker = markers[i], linked = [marker.primary.doc]
  5238. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5239. for (var j = 0; j < marker.markers.length; j++) {
  5240. var subMarker = marker.markers[j]
  5241. if (indexOf(linked, subMarker.doc) == -1) {
  5242. subMarker.parent = null
  5243. marker.markers.splice(j--, 1)
  5244. }
  5245. }
  5246. };
  5247. for (var i = 0; i < markers.length; i++) loop( i );
  5248. }
  5249. var nextDocId = 0
  5250. var Doc = function(text, mode, firstLine, lineSep) {
  5251. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) }
  5252. if (firstLine == null) { firstLine = 0 }
  5253. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5254. this.first = firstLine
  5255. this.scrollTop = this.scrollLeft = 0
  5256. this.cantEdit = false
  5257. this.cleanGeneration = 1
  5258. this.frontier = firstLine
  5259. var start = Pos(firstLine, 0)
  5260. this.sel = simpleSelection(start)
  5261. this.history = new History(null)
  5262. this.id = ++nextDocId
  5263. this.modeOption = mode
  5264. this.lineSep = lineSep
  5265. this.extend = false
  5266. if (typeof text == "string") { text = this.splitLines(text) }
  5267. updateDoc(this, {from: start, to: start, text: text})
  5268. setSelection(this, simpleSelection(start), sel_dontScroll)
  5269. }
  5270. Doc.prototype = createObj(BranchChunk.prototype, {
  5271. constructor: Doc,
  5272. // Iterate over the document. Supports two forms -- with only one
  5273. // argument, it calls that for each line in the document. With
  5274. // three, it iterates over the range given by the first two (with
  5275. // the second being non-inclusive).
  5276. iter: function(from, to, op) {
  5277. if (op) { this.iterN(from - this.first, to - from, op) }
  5278. else { this.iterN(this.first, this.first + this.size, from) }
  5279. },
  5280. // Non-public interface for adding and removing lines.
  5281. insert: function(at, lines) {
  5282. var height = 0
  5283. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5284. this.insertInner(at - this.first, lines, height)
  5285. },
  5286. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5287. // From here, the methods are part of the public interface. Most
  5288. // are also available from CodeMirror (editor) instances.
  5289. getValue: function(lineSep) {
  5290. var lines = getLines(this, this.first, this.first + this.size)
  5291. if (lineSep === false) { return lines }
  5292. return lines.join(lineSep || this.lineSeparator())
  5293. },
  5294. setValue: docMethodOp(function(code) {
  5295. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5296. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5297. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5298. setSelection(this, simpleSelection(top))
  5299. }),
  5300. replaceRange: function(code, from, to, origin) {
  5301. from = clipPos(this, from)
  5302. to = to ? clipPos(this, to) : from
  5303. replaceRange(this, code, from, to, origin)
  5304. },
  5305. getRange: function(from, to, lineSep) {
  5306. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5307. if (lineSep === false) { return lines }
  5308. return lines.join(lineSep || this.lineSeparator())
  5309. },
  5310. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5311. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5312. getLineNumber: function(line) {return lineNo(line)},
  5313. getLineHandleVisualStart: function(line) {
  5314. if (typeof line == "number") { line = getLine(this, line) }
  5315. return visualLine(line)
  5316. },
  5317. lineCount: function() {return this.size},
  5318. firstLine: function() {return this.first},
  5319. lastLine: function() {return this.first + this.size - 1},
  5320. clipPos: function(pos) {return clipPos(this, pos)},
  5321. getCursor: function(start) {
  5322. var range = this.sel.primary(), pos
  5323. if (start == null || start == "head") { pos = range.head }
  5324. else if (start == "anchor") { pos = range.anchor }
  5325. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5326. else { pos = range.from() }
  5327. return pos
  5328. },
  5329. listSelections: function() { return this.sel.ranges },
  5330. somethingSelected: function() {return this.sel.somethingSelected()},
  5331. setCursor: docMethodOp(function(line, ch, options) {
  5332. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5333. }),
  5334. setSelection: docMethodOp(function(anchor, head, options) {
  5335. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5336. }),
  5337. extendSelection: docMethodOp(function(head, other, options) {
  5338. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5339. }),
  5340. extendSelections: docMethodOp(function(heads, options) {
  5341. extendSelections(this, clipPosArray(this, heads), options)
  5342. }),
  5343. extendSelectionsBy: docMethodOp(function(f, options) {
  5344. var heads = map(this.sel.ranges, f)
  5345. extendSelections(this, clipPosArray(this, heads), options)
  5346. }),
  5347. setSelections: docMethodOp(function(ranges, primary, options) {
  5348. var this$1 = this;
  5349. if (!ranges.length) { return }
  5350. var out = []
  5351. for (var i = 0; i < ranges.length; i++)
  5352. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5353. clipPos(this$1, ranges[i].head)) }
  5354. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5355. setSelection(this, normalizeSelection(out, primary), options)
  5356. }),
  5357. addSelection: docMethodOp(function(anchor, head, options) {
  5358. var ranges = this.sel.ranges.slice(0)
  5359. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5360. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5361. }),
  5362. getSelection: function(lineSep) {
  5363. var this$1 = this;
  5364. var ranges = this.sel.ranges, lines
  5365. for (var i = 0; i < ranges.length; i++) {
  5366. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5367. lines = lines ? lines.concat(sel) : sel
  5368. }
  5369. if (lineSep === false) { return lines }
  5370. else { return lines.join(lineSep || this.lineSeparator()) }
  5371. },
  5372. getSelections: function(lineSep) {
  5373. var this$1 = this;
  5374. var parts = [], ranges = this.sel.ranges
  5375. for (var i = 0; i < ranges.length; i++) {
  5376. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5377. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5378. parts[i] = sel
  5379. }
  5380. return parts
  5381. },
  5382. replaceSelection: function(code, collapse, origin) {
  5383. var dup = []
  5384. for (var i = 0; i < this.sel.ranges.length; i++)
  5385. { dup[i] = code }
  5386. this.replaceSelections(dup, collapse, origin || "+input")
  5387. },
  5388. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5389. var this$1 = this;
  5390. var changes = [], sel = this.sel
  5391. for (var i = 0; i < sel.ranges.length; i++) {
  5392. var range = sel.ranges[i]
  5393. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5394. }
  5395. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5396. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5397. { makeChange(this$1, changes[i$1]) }
  5398. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5399. else if (this.cm) { ensureCursorVisible(this.cm) }
  5400. }),
  5401. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5402. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5403. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5404. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5405. setExtending: function(val) {this.extend = val},
  5406. getExtending: function() {return this.extend},
  5407. historySize: function() {
  5408. var hist = this.history, done = 0, undone = 0
  5409. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5410. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5411. return {undo: done, redo: undone}
  5412. },
  5413. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5414. markClean: function() {
  5415. this.cleanGeneration = this.changeGeneration(true)
  5416. },
  5417. changeGeneration: function(forceSplit) {
  5418. if (forceSplit)
  5419. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5420. return this.history.generation
  5421. },
  5422. isClean: function (gen) {
  5423. return this.history.generation == (gen || this.cleanGeneration)
  5424. },
  5425. getHistory: function() {
  5426. return {done: copyHistoryArray(this.history.done),
  5427. undone: copyHistoryArray(this.history.undone)}
  5428. },
  5429. setHistory: function(histData) {
  5430. var hist = this.history = new History(this.history.maxGeneration)
  5431. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5432. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5433. },
  5434. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5435. return changeLine(this, line, "gutter", function (line) {
  5436. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5437. markers[gutterID] = value
  5438. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5439. return true
  5440. })
  5441. }),
  5442. clearGutter: docMethodOp(function(gutterID) {
  5443. var this$1 = this;
  5444. this.iter(function (line) {
  5445. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5446. changeLine(this$1, line, "gutter", function () {
  5447. line.gutterMarkers[gutterID] = null
  5448. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5449. return true
  5450. })
  5451. }
  5452. })
  5453. }),
  5454. lineInfo: function(line) {
  5455. var n
  5456. if (typeof line == "number") {
  5457. if (!isLine(this, line)) { return null }
  5458. n = line
  5459. line = getLine(this, line)
  5460. if (!line) { return null }
  5461. } else {
  5462. n = lineNo(line)
  5463. if (n == null) { return null }
  5464. }
  5465. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5466. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5467. widgets: line.widgets}
  5468. },
  5469. addLineClass: docMethodOp(function(handle, where, cls) {
  5470. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5471. var prop = where == "text" ? "textClass"
  5472. : where == "background" ? "bgClass"
  5473. : where == "gutter" ? "gutterClass" : "wrapClass"
  5474. if (!line[prop]) { line[prop] = cls }
  5475. else if (classTest(cls).test(line[prop])) { return false }
  5476. else { line[prop] += " " + cls }
  5477. return true
  5478. })
  5479. }),
  5480. removeLineClass: docMethodOp(function(handle, where, cls) {
  5481. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5482. var prop = where == "text" ? "textClass"
  5483. : where == "background" ? "bgClass"
  5484. : where == "gutter" ? "gutterClass" : "wrapClass"
  5485. var cur = line[prop]
  5486. if (!cur) { return false }
  5487. else if (cls == null) { line[prop] = null }
  5488. else {
  5489. var found = cur.match(classTest(cls))
  5490. if (!found) { return false }
  5491. var end = found.index + found[0].length
  5492. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5493. }
  5494. return true
  5495. })
  5496. }),
  5497. addLineWidget: docMethodOp(function(handle, node, options) {
  5498. return addLineWidget(this, handle, node, options)
  5499. }),
  5500. removeLineWidget: function(widget) { widget.clear() },
  5501. markText: function(from, to, options) {
  5502. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5503. },
  5504. setBookmark: function(pos, options) {
  5505. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5506. insertLeft: options && options.insertLeft,
  5507. clearWhenEmpty: false, shared: options && options.shared,
  5508. handleMouseEvents: options && options.handleMouseEvents}
  5509. pos = clipPos(this, pos)
  5510. return markText(this, pos, pos, realOpts, "bookmark")
  5511. },
  5512. findMarksAt: function(pos) {
  5513. pos = clipPos(this, pos)
  5514. var markers = [], spans = getLine(this, pos.line).markedSpans
  5515. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5516. var span = spans[i]
  5517. if ((span.from == null || span.from <= pos.ch) &&
  5518. (span.to == null || span.to >= pos.ch))
  5519. { markers.push(span.marker.parent || span.marker) }
  5520. } }
  5521. return markers
  5522. },
  5523. findMarks: function(from, to, filter) {
  5524. from = clipPos(this, from); to = clipPos(this, to)
  5525. var found = [], lineNo = from.line
  5526. this.iter(from.line, to.line + 1, function (line) {
  5527. var spans = line.markedSpans
  5528. if (spans) { for (var i = 0; i < spans.length; i++) {
  5529. var span = spans[i]
  5530. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5531. span.from == null && lineNo != from.line ||
  5532. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5533. (!filter || filter(span.marker)))
  5534. { found.push(span.marker.parent || span.marker) }
  5535. } }
  5536. ++lineNo
  5537. })
  5538. return found
  5539. },
  5540. getAllMarks: function() {
  5541. var markers = []
  5542. this.iter(function (line) {
  5543. var sps = line.markedSpans
  5544. if (sps) { for (var i = 0; i < sps.length; ++i)
  5545. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5546. })
  5547. return markers
  5548. },
  5549. posFromIndex: function(off) {
  5550. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5551. this.iter(function (line) {
  5552. var sz = line.text.length + sepSize
  5553. if (sz > off) { ch = off; return true }
  5554. off -= sz
  5555. ++lineNo
  5556. })
  5557. return clipPos(this, Pos(lineNo, ch))
  5558. },
  5559. indexFromPos: function (coords) {
  5560. coords = clipPos(this, coords)
  5561. var index = coords.ch
  5562. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5563. var sepSize = this.lineSeparator().length
  5564. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5565. index += line.text.length + sepSize
  5566. })
  5567. return index
  5568. },
  5569. copy: function(copyHistory) {
  5570. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5571. this.modeOption, this.first, this.lineSep)
  5572. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5573. doc.sel = this.sel
  5574. doc.extend = false
  5575. if (copyHistory) {
  5576. doc.history.undoDepth = this.history.undoDepth
  5577. doc.setHistory(this.getHistory())
  5578. }
  5579. return doc
  5580. },
  5581. linkedDoc: function(options) {
  5582. if (!options) { options = {} }
  5583. var from = this.first, to = this.first + this.size
  5584. if (options.from != null && options.from > from) { from = options.from }
  5585. if (options.to != null && options.to < to) { to = options.to }
  5586. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep)
  5587. if (options.sharedHist) { copy.history = this.history
  5588. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5589. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5590. copySharedMarkers(copy, findSharedMarkers(this))
  5591. return copy
  5592. },
  5593. unlinkDoc: function(other) {
  5594. var this$1 = this;
  5595. if (other instanceof CodeMirror) { other = other.doc }
  5596. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5597. var link = this$1.linked[i]
  5598. if (link.doc != other) { continue }
  5599. this$1.linked.splice(i, 1)
  5600. other.unlinkDoc(this$1)
  5601. detachSharedMarkers(findSharedMarkers(this$1))
  5602. break
  5603. } }
  5604. // If the histories were shared, split them again
  5605. if (other.history == this.history) {
  5606. var splitIds = [other.id]
  5607. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5608. other.history = new History(null)
  5609. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5610. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5611. }
  5612. },
  5613. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5614. getMode: function() {return this.mode},
  5615. getEditor: function() {return this.cm},
  5616. splitLines: function(str) {
  5617. if (this.lineSep) { return str.split(this.lineSep) }
  5618. return splitLinesAuto(str)
  5619. },
  5620. lineSeparator: function() { return this.lineSep || "\n" }
  5621. })
  5622. // Public alias.
  5623. Doc.prototype.eachLine = Doc.prototype.iter
  5624. // Kludge to work around strange IE behavior where it'll sometimes
  5625. // re-fire a series of drag-related events right after the drop (#1551)
  5626. var lastDrop = 0
  5627. function onDrop(e) {
  5628. var cm = this
  5629. clearDragCursor(cm)
  5630. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5631. { return }
  5632. e_preventDefault(e)
  5633. if (ie) { lastDrop = +new Date }
  5634. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5635. if (!pos || cm.isReadOnly()) { return }
  5636. // Might be a file drop, in which case we simply extract the text
  5637. // and insert it.
  5638. if (files && files.length && window.FileReader && window.File) {
  5639. var n = files.length, text = Array(n), read = 0
  5640. var loadFile = function (file, i) {
  5641. if (cm.options.allowDropFileTypes &&
  5642. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5643. { return }
  5644. var reader = new FileReader
  5645. reader.onload = operation(cm, function () {
  5646. var content = reader.result
  5647. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5648. text[i] = content
  5649. if (++read == n) {
  5650. pos = clipPos(cm.doc, pos)
  5651. var change = {from: pos, to: pos,
  5652. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5653. origin: "paste"}
  5654. makeChange(cm.doc, change)
  5655. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5656. }
  5657. })
  5658. reader.readAsText(file)
  5659. }
  5660. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5661. } else { // Normal drop
  5662. // Don't do a replace if the drop happened inside of the selected text.
  5663. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5664. cm.state.draggingText(e)
  5665. // Ensure the editor is re-focused
  5666. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5667. return
  5668. }
  5669. try {
  5670. var text$1 = e.dataTransfer.getData("Text")
  5671. if (text$1) {
  5672. var selected
  5673. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5674. { selected = cm.listSelections() }
  5675. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5676. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5677. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5678. cm.replaceSelection(text$1, "around", "paste")
  5679. cm.display.input.focus()
  5680. }
  5681. }
  5682. catch(e){}
  5683. }
  5684. }
  5685. function onDragStart(cm, e) {
  5686. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5687. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5688. e.dataTransfer.setData("Text", cm.getSelection())
  5689. e.dataTransfer.effectAllowed = "copyMove"
  5690. // Use dummy image instead of default browsers image.
  5691. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5692. if (e.dataTransfer.setDragImage && !safari) {
  5693. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5694. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5695. if (presto) {
  5696. img.width = img.height = 1
  5697. cm.display.wrapper.appendChild(img)
  5698. // Force a relayout, or Opera won't use our image for some obscure reason
  5699. img._top = img.offsetTop
  5700. }
  5701. e.dataTransfer.setDragImage(img, 0, 0)
  5702. if (presto) { img.parentNode.removeChild(img) }
  5703. }
  5704. }
  5705. function onDragOver(cm, e) {
  5706. var pos = posFromMouse(cm, e)
  5707. if (!pos) { return }
  5708. var frag = document.createDocumentFragment()
  5709. drawSelectionCursor(cm, pos, frag)
  5710. if (!cm.display.dragCursor) {
  5711. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5712. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5713. }
  5714. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5715. }
  5716. function clearDragCursor(cm) {
  5717. if (cm.display.dragCursor) {
  5718. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5719. cm.display.dragCursor = null
  5720. }
  5721. }
  5722. // These must be handled carefully, because naively registering a
  5723. // handler for each editor will cause the editors to never be
  5724. // garbage collected.
  5725. function forEachCodeMirror(f) {
  5726. if (!document.body.getElementsByClassName) { return }
  5727. var byClass = document.body.getElementsByClassName("CodeMirror")
  5728. for (var i = 0; i < byClass.length; i++) {
  5729. var cm = byClass[i].CodeMirror
  5730. if (cm) { f(cm) }
  5731. }
  5732. }
  5733. var globalsRegistered = false
  5734. function ensureGlobalHandlers() {
  5735. if (globalsRegistered) { return }
  5736. registerGlobalHandlers()
  5737. globalsRegistered = true
  5738. }
  5739. function registerGlobalHandlers() {
  5740. // When the window resizes, we need to refresh active editors.
  5741. var resizeTimer
  5742. on(window, "resize", function () {
  5743. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5744. resizeTimer = null
  5745. forEachCodeMirror(onResize)
  5746. }, 100) }
  5747. })
  5748. // When the window loses focus, we want to show the editor as blurred
  5749. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5750. }
  5751. // Called when the window resizes
  5752. function onResize(cm) {
  5753. var d = cm.display
  5754. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5755. { return }
  5756. // Might be a text scaling operation, clear size caches.
  5757. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5758. d.scrollbarsClipped = false
  5759. cm.setSize()
  5760. }
  5761. var keyNames = {
  5762. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5763. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5764. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5765. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5766. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5767. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5768. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5769. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5770. }
  5771. // Number keys
  5772. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5773. // Alphabetic keys
  5774. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5775. // Function keys
  5776. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5777. var keyMap = {}
  5778. keyMap.basic = {
  5779. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5780. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5781. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5782. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5783. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5784. "Esc": "singleSelection"
  5785. }
  5786. // Note that the save and find-related commands aren't defined by
  5787. // default. User code or addons can define them. Unknown commands
  5788. // are simply ignored.
  5789. keyMap.pcDefault = {
  5790. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5791. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5792. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5793. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5794. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5795. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5796. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5797. fallthrough: "basic"
  5798. }
  5799. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5800. keyMap.emacsy = {
  5801. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5802. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5803. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5804. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5805. "Ctrl-O": "openLine"
  5806. }
  5807. keyMap.macDefault = {
  5808. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5809. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5810. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5811. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5812. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5813. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5814. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5815. fallthrough: ["basic", "emacsy"]
  5816. }
  5817. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5818. // KEYMAP DISPATCH
  5819. function normalizeKeyName(name) {
  5820. var parts = name.split(/-(?!$)/)
  5821. name = parts[parts.length - 1]
  5822. var alt, ctrl, shift, cmd
  5823. for (var i = 0; i < parts.length - 1; i++) {
  5824. var mod = parts[i]
  5825. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5826. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5827. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5828. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5829. else { throw new Error("Unrecognized modifier name: " + mod) }
  5830. }
  5831. if (alt) { name = "Alt-" + name }
  5832. if (ctrl) { name = "Ctrl-" + name }
  5833. if (cmd) { name = "Cmd-" + name }
  5834. if (shift) { name = "Shift-" + name }
  5835. return name
  5836. }
  5837. // This is a kludge to keep keymaps mostly working as raw objects
  5838. // (backwards compatibility) while at the same time support features
  5839. // like normalization and multi-stroke key bindings. It compiles a
  5840. // new normalized keymap, and then updates the old object to reflect
  5841. // this.
  5842. function normalizeKeyMap(keymap) {
  5843. var copy = {}
  5844. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  5845. var value = keymap[keyname]
  5846. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  5847. if (value == "...") { delete keymap[keyname]; continue }
  5848. var keys = map(keyname.split(" "), normalizeKeyName)
  5849. for (var i = 0; i < keys.length; i++) {
  5850. var val = (void 0), name = (void 0)
  5851. if (i == keys.length - 1) {
  5852. name = keys.join(" ")
  5853. val = value
  5854. } else {
  5855. name = keys.slice(0, i + 1).join(" ")
  5856. val = "..."
  5857. }
  5858. var prev = copy[name]
  5859. if (!prev) { copy[name] = val }
  5860. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  5861. }
  5862. delete keymap[keyname]
  5863. } }
  5864. for (var prop in copy) { keymap[prop] = copy[prop] }
  5865. return keymap
  5866. }
  5867. function lookupKey(key, map, handle, context) {
  5868. map = getKeyMap(map)
  5869. var found = map.call ? map.call(key, context) : map[key]
  5870. if (found === false) { return "nothing" }
  5871. if (found === "...") { return "multi" }
  5872. if (found != null && handle(found)) { return "handled" }
  5873. if (map.fallthrough) {
  5874. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5875. { return lookupKey(key, map.fallthrough, handle, context) }
  5876. for (var i = 0; i < map.fallthrough.length; i++) {
  5877. var result = lookupKey(key, map.fallthrough[i], handle, context)
  5878. if (result) { return result }
  5879. }
  5880. }
  5881. }
  5882. // Modifier key presses don't count as 'real' key presses for the
  5883. // purpose of keymap fallthrough.
  5884. function isModifierKey(value) {
  5885. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  5886. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  5887. }
  5888. // Look up the name of a key as indicated by an event object.
  5889. function keyName(event, noShift) {
  5890. if (presto && event.keyCode == 34 && event["char"]) { return false }
  5891. var base = keyNames[event.keyCode], name = base
  5892. if (name == null || event.altGraphKey) { return false }
  5893. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  5894. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  5895. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  5896. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  5897. return name
  5898. }
  5899. function getKeyMap(val) {
  5900. return typeof val == "string" ? keyMap[val] : val
  5901. }
  5902. // Helper for deleting text near the selection(s), used to implement
  5903. // backspace, delete, and similar functionality.
  5904. function deleteNearSelection(cm, compute) {
  5905. var ranges = cm.doc.sel.ranges, kill = []
  5906. // Build up a set of ranges to kill first, merging overlapping
  5907. // ranges.
  5908. for (var i = 0; i < ranges.length; i++) {
  5909. var toKill = compute(ranges[i])
  5910. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  5911. var replaced = kill.pop()
  5912. if (cmp(replaced.from, toKill.from) < 0) {
  5913. toKill.from = replaced.from
  5914. break
  5915. }
  5916. }
  5917. kill.push(toKill)
  5918. }
  5919. // Next, remove those actual ranges.
  5920. runInOp(cm, function () {
  5921. for (var i = kill.length - 1; i >= 0; i--)
  5922. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  5923. ensureCursorVisible(cm)
  5924. })
  5925. }
  5926. // Commands are parameter-less actions that can be performed on an
  5927. // editor, mostly used for keybindings.
  5928. var commands = {
  5929. selectAll: selectAll,
  5930. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  5931. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  5932. if (range.empty()) {
  5933. var len = getLine(cm.doc, range.head.line).text.length
  5934. if (range.head.ch == len && range.head.line < cm.lastLine())
  5935. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  5936. else
  5937. { return {from: range.head, to: Pos(range.head.line, len)} }
  5938. } else {
  5939. return {from: range.from(), to: range.to()}
  5940. }
  5941. }); },
  5942. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5943. from: Pos(range.from().line, 0),
  5944. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  5945. }); }); },
  5946. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  5947. from: Pos(range.from().line, 0), to: range.from()
  5948. }); }); },
  5949. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  5950. var top = cm.charCoords(range.head, "div").top + 5
  5951. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  5952. return {from: leftPos, to: range.from()}
  5953. }); },
  5954. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  5955. var top = cm.charCoords(range.head, "div").top + 5
  5956. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5957. return {from: range.from(), to: rightPos }
  5958. }); },
  5959. undo: function (cm) { return cm.undo(); },
  5960. redo: function (cm) { return cm.redo(); },
  5961. undoSelection: function (cm) { return cm.undoSelection(); },
  5962. redoSelection: function (cm) { return cm.redoSelection(); },
  5963. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  5964. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  5965. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  5966. {origin: "+move", bias: 1}
  5967. ); },
  5968. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  5969. {origin: "+move", bias: 1}
  5970. ); },
  5971. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  5972. {origin: "+move", bias: -1}
  5973. ); },
  5974. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  5975. var top = cm.charCoords(range.head, "div").top + 5
  5976. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  5977. }, sel_move); },
  5978. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  5979. var top = cm.charCoords(range.head, "div").top + 5
  5980. return cm.coordsChar({left: 0, top: top}, "div")
  5981. }, sel_move); },
  5982. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  5983. var top = cm.charCoords(range.head, "div").top + 5
  5984. var pos = cm.coordsChar({left: 0, top: top}, "div")
  5985. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  5986. return pos
  5987. }, sel_move); },
  5988. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  5989. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  5990. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  5991. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  5992. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  5993. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  5994. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  5995. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  5996. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  5997. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  5998. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  5999. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6000. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6001. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6002. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6003. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6004. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6005. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6006. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6007. indentMore: function (cm) { return cm.indentSelection("add"); },
  6008. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6009. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6010. insertSoftTab: function (cm) {
  6011. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  6012. for (var i = 0; i < ranges.length; i++) {
  6013. var pos = ranges[i].from()
  6014. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  6015. spaces.push(spaceStr(tabSize - col % tabSize))
  6016. }
  6017. cm.replaceSelections(spaces)
  6018. },
  6019. defaultTab: function (cm) {
  6020. if (cm.somethingSelected()) { cm.indentSelection("add") }
  6021. else { cm.execCommand("insertTab") }
  6022. },
  6023. // Swap the two chars left and right of each selection's head.
  6024. // Move cursor behind the two swapped characters afterwards.
  6025. //
  6026. // Doesn't consider line feeds a character.
  6027. // Doesn't scan more than one line above to find a character.
  6028. // Doesn't do anything on an empty line.
  6029. // Doesn't do anything with non-empty selections.
  6030. transposeChars: function (cm) { return runInOp(cm, function () {
  6031. var ranges = cm.listSelections(), newSel = []
  6032. for (var i = 0; i < ranges.length; i++) {
  6033. if (!ranges[i].empty()) { continue }
  6034. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  6035. if (line) {
  6036. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  6037. if (cur.ch > 0) {
  6038. cur = new Pos(cur.line, cur.ch + 1)
  6039. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6040. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  6041. } else if (cur.line > cm.doc.first) {
  6042. var prev = getLine(cm.doc, cur.line - 1).text
  6043. if (prev) {
  6044. cur = new Pos(cur.line, 1)
  6045. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6046. prev.charAt(prev.length - 1),
  6047. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  6048. }
  6049. }
  6050. }
  6051. newSel.push(new Range(cur, cur))
  6052. }
  6053. cm.setSelections(newSel)
  6054. }); },
  6055. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6056. var sels = cm.listSelections()
  6057. for (var i = sels.length - 1; i >= 0; i--)
  6058. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  6059. sels = cm.listSelections()
  6060. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6061. { cm.indentLine(sels[i$1].from().line, null, true) }
  6062. ensureCursorVisible(cm)
  6063. }); },
  6064. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6065. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6066. }
  6067. function lineStart(cm, lineN) {
  6068. var line = getLine(cm.doc, lineN)
  6069. var visual = visualLine(line)
  6070. if (visual != line) { lineN = lineNo(visual) }
  6071. return endOfLine(true, cm, visual, lineN, 1)
  6072. }
  6073. function lineEnd(cm, lineN) {
  6074. var line = getLine(cm.doc, lineN)
  6075. var visual = visualLineEnd(line)
  6076. if (visual != line) { lineN = lineNo(visual) }
  6077. return endOfLine(true, cm, line, lineN, -1)
  6078. }
  6079. function lineStartSmart(cm, pos) {
  6080. var start = lineStart(cm, pos.line)
  6081. var line = getLine(cm.doc, start.line)
  6082. var order = getOrder(line)
  6083. if (!order || order[0].level == 0) {
  6084. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6085. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6086. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6087. }
  6088. return start
  6089. }
  6090. // Run a handler that was bound to a key.
  6091. function doHandleBinding(cm, bound, dropShift) {
  6092. if (typeof bound == "string") {
  6093. bound = commands[bound]
  6094. if (!bound) { return false }
  6095. }
  6096. // Ensure previous input has been read, so that the handler sees a
  6097. // consistent view of the document
  6098. cm.display.input.ensurePolled()
  6099. var prevShift = cm.display.shift, done = false
  6100. try {
  6101. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6102. if (dropShift) { cm.display.shift = false }
  6103. done = bound(cm) != Pass
  6104. } finally {
  6105. cm.display.shift = prevShift
  6106. cm.state.suppressEdits = false
  6107. }
  6108. return done
  6109. }
  6110. function lookupKeyForEditor(cm, name, handle) {
  6111. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6112. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6113. if (result) { return result }
  6114. }
  6115. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6116. || lookupKey(name, cm.options.keyMap, handle, cm)
  6117. }
  6118. var stopSeq = new Delayed
  6119. function dispatchKey(cm, name, e, handle) {
  6120. var seq = cm.state.keySeq
  6121. if (seq) {
  6122. if (isModifierKey(name)) { return "handled" }
  6123. stopSeq.set(50, function () {
  6124. if (cm.state.keySeq == seq) {
  6125. cm.state.keySeq = null
  6126. cm.display.input.reset()
  6127. }
  6128. })
  6129. name = seq + " " + name
  6130. }
  6131. var result = lookupKeyForEditor(cm, name, handle)
  6132. if (result == "multi")
  6133. { cm.state.keySeq = name }
  6134. if (result == "handled")
  6135. { signalLater(cm, "keyHandled", cm, name, e) }
  6136. if (result == "handled" || result == "multi") {
  6137. e_preventDefault(e)
  6138. restartBlink(cm)
  6139. }
  6140. if (seq && !result && /\'$/.test(name)) {
  6141. e_preventDefault(e)
  6142. return true
  6143. }
  6144. return !!result
  6145. }
  6146. // Handle a key from the keydown event.
  6147. function handleKeyBinding(cm, e) {
  6148. var name = keyName(e, true)
  6149. if (!name) { return false }
  6150. if (e.shiftKey && !cm.state.keySeq) {
  6151. // First try to resolve full name (including 'Shift-'). Failing
  6152. // that, see if there is a cursor-motion command (starting with
  6153. // 'go') bound to the keyname without 'Shift-'.
  6154. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6155. || dispatchKey(cm, name, e, function (b) {
  6156. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6157. { return doHandleBinding(cm, b) }
  6158. })
  6159. } else {
  6160. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6161. }
  6162. }
  6163. // Handle a key from the keypress event
  6164. function handleCharBinding(cm, e, ch) {
  6165. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6166. }
  6167. var lastStoppedKey = null
  6168. function onKeyDown(e) {
  6169. var cm = this
  6170. cm.curOp.focus = activeElt()
  6171. if (signalDOMEvent(cm, e)) { return }
  6172. // IE does strange things with escape.
  6173. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6174. var code = e.keyCode
  6175. cm.display.shift = code == 16 || e.shiftKey
  6176. var handled = handleKeyBinding(cm, e)
  6177. if (presto) {
  6178. lastStoppedKey = handled ? code : null
  6179. // Opera has no cut event... we try to at least catch the key combo
  6180. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6181. { cm.replaceSelection("", null, "cut") }
  6182. }
  6183. // Turn mouse into crosshair when Alt is held on Mac.
  6184. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6185. { showCrossHair(cm) }
  6186. }
  6187. function showCrossHair(cm) {
  6188. var lineDiv = cm.display.lineDiv
  6189. addClass(lineDiv, "CodeMirror-crosshair")
  6190. function up(e) {
  6191. if (e.keyCode == 18 || !e.altKey) {
  6192. rmClass(lineDiv, "CodeMirror-crosshair")
  6193. off(document, "keyup", up)
  6194. off(document, "mouseover", up)
  6195. }
  6196. }
  6197. on(document, "keyup", up)
  6198. on(document, "mouseover", up)
  6199. }
  6200. function onKeyUp(e) {
  6201. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6202. signalDOMEvent(this, e)
  6203. }
  6204. function onKeyPress(e) {
  6205. var cm = this
  6206. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6207. var keyCode = e.keyCode, charCode = e.charCode
  6208. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6209. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6210. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6211. // Some browsers fire keypress events for backspace
  6212. if (ch == "\x08") { return }
  6213. if (handleCharBinding(cm, e, ch)) { return }
  6214. cm.display.input.onKeyPress(e)
  6215. }
  6216. // A mouse down can be a single click, double click, triple click,
  6217. // start of selection drag, start of text drag, new cursor
  6218. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6219. // middle-click-paste. Or it might be a click on something we should
  6220. // not interfere with, such as a scrollbar or widget.
  6221. function onMouseDown(e) {
  6222. var cm = this, display = cm.display
  6223. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6224. display.input.ensurePolled()
  6225. display.shift = e.shiftKey
  6226. if (eventInWidget(display, e)) {
  6227. if (!webkit) {
  6228. // Briefly turn off draggability, to allow widgets to do
  6229. // normal dragging things.
  6230. display.scroller.draggable = false
  6231. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6232. }
  6233. return
  6234. }
  6235. if (clickInGutter(cm, e)) { return }
  6236. var start = posFromMouse(cm, e)
  6237. window.focus()
  6238. switch (e_button(e)) {
  6239. case 1:
  6240. // #3261: make sure, that we're not starting a second selection
  6241. if (cm.state.selectingText)
  6242. { cm.state.selectingText(e) }
  6243. else if (start)
  6244. { leftButtonDown(cm, e, start) }
  6245. else if (e_target(e) == display.scroller)
  6246. { e_preventDefault(e) }
  6247. break
  6248. case 2:
  6249. if (webkit) { cm.state.lastMiddleDown = +new Date }
  6250. if (start) { extendSelection(cm.doc, start) }
  6251. setTimeout(function () { return display.input.focus(); }, 20)
  6252. e_preventDefault(e)
  6253. break
  6254. case 3:
  6255. if (captureRightClick) { onContextMenu(cm, e) }
  6256. else { delayBlurEvent(cm) }
  6257. break
  6258. }
  6259. }
  6260. var lastClick;
  6261. var lastDoubleClick;
  6262. function leftButtonDown(cm, e, start) {
  6263. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6264. else { cm.curOp.focus = activeElt() }
  6265. var now = +new Date, type
  6266. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  6267. type = "triple"
  6268. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  6269. type = "double"
  6270. lastDoubleClick = {time: now, pos: start}
  6271. } else {
  6272. type = "single"
  6273. lastClick = {time: now, pos: start}
  6274. }
  6275. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained
  6276. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6277. type == "single" && (contained = sel.contains(start)) > -1 &&
  6278. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  6279. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  6280. { leftButtonStartDrag(cm, e, start, modifier) }
  6281. else
  6282. { leftButtonSelect(cm, e, start, type, modifier) }
  6283. }
  6284. // Start a text drag. When it ends, see if any dragging actually
  6285. // happen, and treat as a click if it didn't.
  6286. function leftButtonStartDrag(cm, e, start, modifier) {
  6287. var display = cm.display, startTime = +new Date
  6288. var dragEnd = operation(cm, function (e2) {
  6289. if (webkit) { display.scroller.draggable = false }
  6290. cm.state.draggingText = false
  6291. off(document, "mouseup", dragEnd)
  6292. off(display.scroller, "drop", dragEnd)
  6293. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  6294. e_preventDefault(e2)
  6295. if (!modifier && +new Date - 200 < startTime)
  6296. { extendSelection(cm.doc, start) }
  6297. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6298. if (webkit || ie && ie_version == 9)
  6299. { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
  6300. else
  6301. { display.input.focus() }
  6302. }
  6303. })
  6304. // Let the drag handler handle this.
  6305. if (webkit) { display.scroller.draggable = true }
  6306. cm.state.draggingText = dragEnd
  6307. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  6308. // IE's approach to draggable
  6309. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6310. on(document, "mouseup", dragEnd)
  6311. on(display.scroller, "drop", dragEnd)
  6312. }
  6313. // Normal selection, as opposed to text dragging.
  6314. function leftButtonSelect(cm, e, start, type, addNew) {
  6315. var display = cm.display, doc = cm.doc
  6316. e_preventDefault(e)
  6317. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6318. if (addNew && !e.shiftKey) {
  6319. ourIndex = doc.sel.contains(start)
  6320. if (ourIndex > -1)
  6321. { ourRange = ranges[ourIndex] }
  6322. else
  6323. { ourRange = new Range(start, start) }
  6324. } else {
  6325. ourRange = doc.sel.primary()
  6326. ourIndex = doc.sel.primIndex
  6327. }
  6328. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  6329. type = "rect"
  6330. if (!addNew) { ourRange = new Range(start, start) }
  6331. start = posFromMouse(cm, e, true, true)
  6332. ourIndex = -1
  6333. } else if (type == "double") {
  6334. var word = cm.findWordAt(start)
  6335. if (cm.display.shift || doc.extend)
  6336. { ourRange = extendRange(doc, ourRange, word.anchor, word.head) }
  6337. else
  6338. { ourRange = word }
  6339. } else if (type == "triple") {
  6340. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)))
  6341. if (cm.display.shift || doc.extend)
  6342. { ourRange = extendRange(doc, ourRange, line.anchor, line.head) }
  6343. else
  6344. { ourRange = line }
  6345. } else {
  6346. ourRange = extendRange(doc, ourRange, start)
  6347. }
  6348. if (!addNew) {
  6349. ourIndex = 0
  6350. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6351. startSel = doc.sel
  6352. } else if (ourIndex == -1) {
  6353. ourIndex = ranges.length
  6354. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6355. {scroll: false, origin: "*mouse"})
  6356. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  6357. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6358. {scroll: false, origin: "*mouse"})
  6359. startSel = doc.sel
  6360. } else {
  6361. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6362. }
  6363. var lastPos = start
  6364. function extendTo(pos) {
  6365. if (cmp(lastPos, pos) == 0) { return }
  6366. lastPos = pos
  6367. if (type == "rect") {
  6368. var ranges = [], tabSize = cm.options.tabSize
  6369. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6370. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6371. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6372. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6373. line <= end; line++) {
  6374. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6375. if (left == right)
  6376. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6377. else if (text.length > leftPos)
  6378. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6379. }
  6380. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6381. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6382. {origin: "*mouse", scroll: false})
  6383. cm.scrollIntoView(pos)
  6384. } else {
  6385. var oldRange = ourRange
  6386. var anchor = oldRange.anchor, head = pos
  6387. if (type != "single") {
  6388. var range
  6389. if (type == "double")
  6390. { range = cm.findWordAt(pos) }
  6391. else
  6392. { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) }
  6393. if (cmp(range.anchor, anchor) > 0) {
  6394. head = range.head
  6395. anchor = minPos(oldRange.from(), range.anchor)
  6396. } else {
  6397. head = range.anchor
  6398. anchor = maxPos(oldRange.to(), range.head)
  6399. }
  6400. }
  6401. var ranges$1 = startSel.ranges.slice(0)
  6402. ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head)
  6403. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6404. }
  6405. }
  6406. var editorSize = display.wrapper.getBoundingClientRect()
  6407. // Used to ensure timeout re-tries don't fire when another extend
  6408. // happened in the meantime (clearTimeout isn't reliable -- at
  6409. // least on Chrome, the timeouts still happen even when cleared,
  6410. // if the clear happens after their scheduled firing time).
  6411. var counter = 0
  6412. function extend(e) {
  6413. var curCount = ++counter
  6414. var cur = posFromMouse(cm, e, true, type == "rect")
  6415. if (!cur) { return }
  6416. if (cmp(cur, lastPos) != 0) {
  6417. cm.curOp.focus = activeElt()
  6418. extendTo(cur)
  6419. var visible = visibleLines(display, doc)
  6420. if (cur.line >= visible.to || cur.line < visible.from)
  6421. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6422. } else {
  6423. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6424. if (outside) { setTimeout(operation(cm, function () {
  6425. if (counter != curCount) { return }
  6426. display.scroller.scrollTop += outside
  6427. extend(e)
  6428. }), 50) }
  6429. }
  6430. }
  6431. function done(e) {
  6432. cm.state.selectingText = false
  6433. counter = Infinity
  6434. e_preventDefault(e)
  6435. display.input.focus()
  6436. off(document, "mousemove", move)
  6437. off(document, "mouseup", up)
  6438. doc.history.lastSelOrigin = null
  6439. }
  6440. var move = operation(cm, function (e) {
  6441. if (!e_button(e)) { done(e) }
  6442. else { extend(e) }
  6443. })
  6444. var up = operation(cm, done)
  6445. cm.state.selectingText = up
  6446. on(document, "mousemove", move)
  6447. on(document, "mouseup", up)
  6448. }
  6449. // Determines whether an event happened in the gutter, and fires the
  6450. // handlers for the corresponding event.
  6451. function gutterEvent(cm, e, type, prevent) {
  6452. var mX, mY
  6453. try { mX = e.clientX; mY = e.clientY }
  6454. catch(e) { return false }
  6455. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6456. if (prevent) { e_preventDefault(e) }
  6457. var display = cm.display
  6458. var lineBox = display.lineDiv.getBoundingClientRect()
  6459. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6460. mY -= lineBox.top - display.viewOffset
  6461. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6462. var g = display.gutters.childNodes[i]
  6463. if (g && g.getBoundingClientRect().right >= mX) {
  6464. var line = lineAtHeight(cm.doc, mY)
  6465. var gutter = cm.options.gutters[i]
  6466. signal(cm, type, cm, line, gutter, e)
  6467. return e_defaultPrevented(e)
  6468. }
  6469. }
  6470. }
  6471. function clickInGutter(cm, e) {
  6472. return gutterEvent(cm, e, "gutterClick", true)
  6473. }
  6474. // CONTEXT MENU HANDLING
  6475. // To make the context menu work, we need to briefly unhide the
  6476. // textarea (making it as unobtrusive as possible) to let the
  6477. // right-click take effect on it.
  6478. function onContextMenu(cm, e) {
  6479. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6480. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6481. cm.display.input.onContextMenu(e)
  6482. }
  6483. function contextMenuInGutter(cm, e) {
  6484. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6485. return gutterEvent(cm, e, "gutterContextMenu", false)
  6486. }
  6487. function themeChanged(cm) {
  6488. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6489. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6490. clearCaches(cm)
  6491. }
  6492. var Init = {toString: function(){return "CodeMirror.Init"}}
  6493. var defaults = {}
  6494. var optionHandlers = {}
  6495. function defineOptions(CodeMirror) {
  6496. var optionHandlers = CodeMirror.optionHandlers
  6497. function option(name, deflt, handle, notOnInit) {
  6498. CodeMirror.defaults[name] = deflt
  6499. if (handle) { optionHandlers[name] =
  6500. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6501. }
  6502. CodeMirror.defineOption = option
  6503. // Passed to option handlers when there is no old value.
  6504. CodeMirror.Init = Init
  6505. // These two are, on init, called from the constructor because they
  6506. // have to be initialized before the editor can start at all.
  6507. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6508. option("mode", null, function (cm, val) {
  6509. cm.doc.modeOption = val
  6510. loadMode(cm)
  6511. }, true)
  6512. option("indentUnit", 2, loadMode, true)
  6513. option("indentWithTabs", false)
  6514. option("smartIndent", true)
  6515. option("tabSize", 4, function (cm) {
  6516. resetModeState(cm)
  6517. clearCaches(cm)
  6518. regChange(cm)
  6519. }, true)
  6520. option("lineSeparator", null, function (cm, val) {
  6521. cm.doc.lineSep = val
  6522. if (!val) { return }
  6523. var newBreaks = [], lineNo = cm.doc.first
  6524. cm.doc.iter(function (line) {
  6525. for (var pos = 0;;) {
  6526. var found = line.text.indexOf(val, pos)
  6527. if (found == -1) { break }
  6528. pos = found + val.length
  6529. newBreaks.push(Pos(lineNo, found))
  6530. }
  6531. lineNo++
  6532. })
  6533. for (var i = newBreaks.length - 1; i >= 0; i--)
  6534. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6535. })
  6536. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6537. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6538. if (old != Init) { cm.refresh() }
  6539. })
  6540. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6541. option("electricChars", true)
  6542. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6543. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6544. }, true)
  6545. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6546. option("rtlMoveVisually", !windows)
  6547. option("wholeLineUpdateBefore", true)
  6548. option("theme", "default", function (cm) {
  6549. themeChanged(cm)
  6550. guttersChanged(cm)
  6551. }, true)
  6552. option("keyMap", "default", function (cm, val, old) {
  6553. var next = getKeyMap(val)
  6554. var prev = old != Init && getKeyMap(old)
  6555. if (prev && prev.detach) { prev.detach(cm, next) }
  6556. if (next.attach) { next.attach(cm, prev || null) }
  6557. })
  6558. option("extraKeys", null)
  6559. option("lineWrapping", false, wrappingChanged, true)
  6560. option("gutters", [], function (cm) {
  6561. setGuttersForLineNumbers(cm.options)
  6562. guttersChanged(cm)
  6563. }, true)
  6564. option("fixedGutter", true, function (cm, val) {
  6565. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6566. cm.refresh()
  6567. }, true)
  6568. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6569. option("scrollbarStyle", "native", function (cm) {
  6570. initScrollbars(cm)
  6571. updateScrollbars(cm)
  6572. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6573. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6574. }, true)
  6575. option("lineNumbers", false, function (cm) {
  6576. setGuttersForLineNumbers(cm.options)
  6577. guttersChanged(cm)
  6578. }, true)
  6579. option("firstLineNumber", 1, guttersChanged, true)
  6580. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6581. option("showCursorWhenSelecting", false, updateSelection, true)
  6582. option("resetSelectionOnContextMenu", true)
  6583. option("lineWiseCopyCut", true)
  6584. option("readOnly", false, function (cm, val) {
  6585. if (val == "nocursor") {
  6586. onBlur(cm)
  6587. cm.display.input.blur()
  6588. cm.display.disabled = true
  6589. } else {
  6590. cm.display.disabled = false
  6591. }
  6592. cm.display.input.readOnlyChanged(val)
  6593. })
  6594. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6595. option("dragDrop", true, dragDropChanged)
  6596. option("allowDropFileTypes", null)
  6597. option("cursorBlinkRate", 530)
  6598. option("cursorScrollMargin", 0)
  6599. option("cursorHeight", 1, updateSelection, true)
  6600. option("singleCursorHeightPerLine", true, updateSelection, true)
  6601. option("workTime", 100)
  6602. option("workDelay", 100)
  6603. option("flattenSpans", true, resetModeState, true)
  6604. option("addModeClass", false, resetModeState, true)
  6605. option("pollInterval", 100)
  6606. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6607. option("historyEventDelay", 1250)
  6608. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6609. option("maxHighlightLength", 10000, resetModeState, true)
  6610. option("moveInputWithCursor", true, function (cm, val) {
  6611. if (!val) { cm.display.input.resetPosition() }
  6612. })
  6613. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6614. option("autofocus", null)
  6615. }
  6616. function guttersChanged(cm) {
  6617. updateGutters(cm)
  6618. regChange(cm)
  6619. alignHorizontally(cm)
  6620. }
  6621. function dragDropChanged(cm, value, old) {
  6622. var wasOn = old && old != Init
  6623. if (!value != !wasOn) {
  6624. var funcs = cm.display.dragFunctions
  6625. var toggle = value ? on : off
  6626. toggle(cm.display.scroller, "dragstart", funcs.start)
  6627. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6628. toggle(cm.display.scroller, "dragover", funcs.over)
  6629. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6630. toggle(cm.display.scroller, "drop", funcs.drop)
  6631. }
  6632. }
  6633. function wrappingChanged(cm) {
  6634. if (cm.options.lineWrapping) {
  6635. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6636. cm.display.sizer.style.minWidth = ""
  6637. cm.display.sizerWidth = null
  6638. } else {
  6639. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6640. findMaxLine(cm)
  6641. }
  6642. estimateLineHeights(cm)
  6643. regChange(cm)
  6644. clearCaches(cm)
  6645. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6646. }
  6647. // A CodeMirror instance represents an editor. This is the object
  6648. // that user code is usually dealing with.
  6649. function CodeMirror(place, options) {
  6650. var this$1 = this;
  6651. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  6652. this.options = options = options ? copyObj(options) : {}
  6653. // Determine effective options based on given values and defaults.
  6654. copyObj(defaults, options, false)
  6655. setGuttersForLineNumbers(options)
  6656. var doc = options.value
  6657. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) }
  6658. this.doc = doc
  6659. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  6660. var display = this.display = new Display(place, doc, input)
  6661. display.wrapper.CodeMirror = this
  6662. updateGutters(this)
  6663. themeChanged(this)
  6664. if (options.lineWrapping)
  6665. { this.display.wrapper.className += " CodeMirror-wrap" }
  6666. initScrollbars(this)
  6667. this.state = {
  6668. keyMaps: [], // stores maps added by addKeyMap
  6669. overlays: [], // highlighting overlays, as added by addOverlay
  6670. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  6671. overwrite: false,
  6672. delayingBlurEvent: false,
  6673. focused: false,
  6674. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  6675. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  6676. selectingText: false,
  6677. draggingText: false,
  6678. highlight: new Delayed(), // stores highlight worker timeout
  6679. keySeq: null, // Unfinished key sequence
  6680. specialChars: null
  6681. }
  6682. if (options.autofocus && !mobile) { display.input.focus() }
  6683. // Override magic textarea content restore that IE sometimes does
  6684. // on our hidden textarea on reload
  6685. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  6686. registerEventHandlers(this)
  6687. ensureGlobalHandlers()
  6688. startOperation(this)
  6689. this.curOp.forceUpdate = true
  6690. attachDoc(this, doc)
  6691. if ((options.autofocus && !mobile) || this.hasFocus())
  6692. { setTimeout(bind(onFocus, this), 20) }
  6693. else
  6694. { onBlur(this) }
  6695. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  6696. { optionHandlers[opt](this$1, options[opt], Init) } }
  6697. maybeUpdateLineNumberWidth(this)
  6698. if (options.finishInit) { options.finishInit(this) }
  6699. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  6700. endOperation(this)
  6701. // Suppress optimizelegibility in Webkit, since it breaks text
  6702. // measuring on line wrapping boundaries.
  6703. if (webkit && options.lineWrapping &&
  6704. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  6705. { display.lineDiv.style.textRendering = "auto" }
  6706. }
  6707. // The default configuration options.
  6708. CodeMirror.defaults = defaults
  6709. // Functions to run when options are changed.
  6710. CodeMirror.optionHandlers = optionHandlers
  6711. // Attach the necessary event handlers when initializing the editor
  6712. function registerEventHandlers(cm) {
  6713. var d = cm.display
  6714. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  6715. // Older IE's will not fire a second mousedown for a double click
  6716. if (ie && ie_version < 11)
  6717. { on(d.scroller, "dblclick", operation(cm, function (e) {
  6718. if (signalDOMEvent(cm, e)) { return }
  6719. var pos = posFromMouse(cm, e)
  6720. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  6721. e_preventDefault(e)
  6722. var word = cm.findWordAt(pos)
  6723. extendSelection(cm.doc, word.anchor, word.head)
  6724. })) }
  6725. else
  6726. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  6727. // Some browsers fire contextmenu *after* opening the menu, at
  6728. // which point we can't mess with it anymore. Context menu is
  6729. // handled in onMouseDown for these browsers.
  6730. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  6731. // Used to suppress mouse event handling when a touch happens
  6732. var touchFinished, prevTouch = {end: 0}
  6733. function finishTouch() {
  6734. if (d.activeTouch) {
  6735. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  6736. prevTouch = d.activeTouch
  6737. prevTouch.end = +new Date
  6738. }
  6739. }
  6740. function isMouseLikeTouchEvent(e) {
  6741. if (e.touches.length != 1) { return false }
  6742. var touch = e.touches[0]
  6743. return touch.radiusX <= 1 && touch.radiusY <= 1
  6744. }
  6745. function farAway(touch, other) {
  6746. if (other.left == null) { return true }
  6747. var dx = other.left - touch.left, dy = other.top - touch.top
  6748. return dx * dx + dy * dy > 20 * 20
  6749. }
  6750. on(d.scroller, "touchstart", function (e) {
  6751. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  6752. d.input.ensurePolled()
  6753. clearTimeout(touchFinished)
  6754. var now = +new Date
  6755. d.activeTouch = {start: now, moved: false,
  6756. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  6757. if (e.touches.length == 1) {
  6758. d.activeTouch.left = e.touches[0].pageX
  6759. d.activeTouch.top = e.touches[0].pageY
  6760. }
  6761. }
  6762. })
  6763. on(d.scroller, "touchmove", function () {
  6764. if (d.activeTouch) { d.activeTouch.moved = true }
  6765. })
  6766. on(d.scroller, "touchend", function (e) {
  6767. var touch = d.activeTouch
  6768. if (touch && !eventInWidget(d, e) && touch.left != null &&
  6769. !touch.moved && new Date - touch.start < 300) {
  6770. var pos = cm.coordsChar(d.activeTouch, "page"), range
  6771. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  6772. { range = new Range(pos, pos) }
  6773. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  6774. { range = cm.findWordAt(pos) }
  6775. else // Triple tap
  6776. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6777. cm.setSelection(range.anchor, range.head)
  6778. cm.focus()
  6779. e_preventDefault(e)
  6780. }
  6781. finishTouch()
  6782. })
  6783. on(d.scroller, "touchcancel", finishTouch)
  6784. // Sync scrolling between fake scrollbars and real scrollable
  6785. // area, ensure viewport is updated when scrolling.
  6786. on(d.scroller, "scroll", function () {
  6787. if (d.scroller.clientHeight) {
  6788. setScrollTop(cm, d.scroller.scrollTop)
  6789. setScrollLeft(cm, d.scroller.scrollLeft, true)
  6790. signal(cm, "scroll", cm)
  6791. }
  6792. })
  6793. // Listen to wheel events in order to try and update the viewport on time.
  6794. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  6795. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  6796. // Prevent wrapper from ever scrolling
  6797. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  6798. d.dragFunctions = {
  6799. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  6800. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  6801. start: function (e) { return onDragStart(cm, e); },
  6802. drop: operation(cm, onDrop),
  6803. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  6804. }
  6805. var inp = d.input.getField()
  6806. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  6807. on(inp, "keydown", operation(cm, onKeyDown))
  6808. on(inp, "keypress", operation(cm, onKeyPress))
  6809. on(inp, "focus", function (e) { return onFocus(cm, e); })
  6810. on(inp, "blur", function (e) { return onBlur(cm, e); })
  6811. }
  6812. var initHooks = []
  6813. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  6814. // Indent the given line. The how parameter can be "smart",
  6815. // "add"/null, "subtract", or "prev". When aggressive is false
  6816. // (typically set to true for forced single-line indents), empty
  6817. // lines are not indented, and places where the mode returns Pass
  6818. // are left alone.
  6819. function indentLine(cm, n, how, aggressive) {
  6820. var doc = cm.doc, state
  6821. if (how == null) { how = "add" }
  6822. if (how == "smart") {
  6823. // Fall back to "prev" when the mode doesn't have an indentation
  6824. // method.
  6825. if (!doc.mode.indent) { how = "prev" }
  6826. else { state = getStateBefore(cm, n) }
  6827. }
  6828. var tabSize = cm.options.tabSize
  6829. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  6830. if (line.stateAfter) { line.stateAfter = null }
  6831. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  6832. if (!aggressive && !/\S/.test(line.text)) {
  6833. indentation = 0
  6834. how = "not"
  6835. } else if (how == "smart") {
  6836. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  6837. if (indentation == Pass || indentation > 150) {
  6838. if (!aggressive) { return }
  6839. how = "prev"
  6840. }
  6841. }
  6842. if (how == "prev") {
  6843. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  6844. else { indentation = 0 }
  6845. } else if (how == "add") {
  6846. indentation = curSpace + cm.options.indentUnit
  6847. } else if (how == "subtract") {
  6848. indentation = curSpace - cm.options.indentUnit
  6849. } else if (typeof how == "number") {
  6850. indentation = curSpace + how
  6851. }
  6852. indentation = Math.max(0, indentation)
  6853. var indentString = "", pos = 0
  6854. if (cm.options.indentWithTabs)
  6855. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  6856. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  6857. if (indentString != curSpaceString) {
  6858. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  6859. line.stateAfter = null
  6860. return true
  6861. } else {
  6862. // Ensure that, if the cursor was in the whitespace at the start
  6863. // of the line, it is moved to the end of that space.
  6864. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  6865. var range = doc.sel.ranges[i$1]
  6866. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6867. var pos$1 = Pos(n, curSpaceString.length)
  6868. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  6869. break
  6870. }
  6871. }
  6872. }
  6873. }
  6874. // This will be set to a {lineWise: bool, text: [string]} object, so
  6875. // that, when pasting, we know what kind of selections the copied
  6876. // text was made out of.
  6877. var lastCopied = null
  6878. function setLastCopied(newLastCopied) {
  6879. lastCopied = newLastCopied
  6880. }
  6881. function applyTextInput(cm, inserted, deleted, sel, origin) {
  6882. var doc = cm.doc
  6883. cm.display.shift = false
  6884. if (!sel) { sel = doc.sel }
  6885. var paste = cm.state.pasteIncoming || origin == "paste"
  6886. var textLines = splitLinesAuto(inserted), multiPaste = null
  6887. // When pasing N lines into N selections, insert one line per selection
  6888. if (paste && sel.ranges.length > 1) {
  6889. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  6890. if (sel.ranges.length % lastCopied.text.length == 0) {
  6891. multiPaste = []
  6892. for (var i = 0; i < lastCopied.text.length; i++)
  6893. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  6894. }
  6895. } else if (textLines.length == sel.ranges.length) {
  6896. multiPaste = map(textLines, function (l) { return [l]; })
  6897. }
  6898. }
  6899. var updateInput
  6900. // Normal behavior is to insert the new text into every selection
  6901. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  6902. var range = sel.ranges[i$1]
  6903. var from = range.from(), to = range.to()
  6904. if (range.empty()) {
  6905. if (deleted && deleted > 0) // Handle deletion
  6906. { from = Pos(from.line, from.ch - deleted) }
  6907. else if (cm.state.overwrite && !paste) // Handle overwrite
  6908. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  6909. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  6910. { from = to = Pos(from.line, 0) }
  6911. }
  6912. updateInput = cm.curOp.updateInput
  6913. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  6914. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  6915. makeChange(cm.doc, changeEvent)
  6916. signalLater(cm, "inputRead", cm, changeEvent)
  6917. }
  6918. if (inserted && !paste)
  6919. { triggerElectric(cm, inserted) }
  6920. ensureCursorVisible(cm)
  6921. cm.curOp.updateInput = updateInput
  6922. cm.curOp.typing = true
  6923. cm.state.pasteIncoming = cm.state.cutIncoming = false
  6924. }
  6925. function handlePaste(e, cm) {
  6926. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  6927. if (pasted) {
  6928. e.preventDefault()
  6929. if (!cm.isReadOnly() && !cm.options.disableInput)
  6930. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  6931. return true
  6932. }
  6933. }
  6934. function triggerElectric(cm, inserted) {
  6935. // When an 'electric' character is inserted, immediately trigger a reindent
  6936. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  6937. var sel = cm.doc.sel
  6938. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  6939. var range = sel.ranges[i]
  6940. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  6941. var mode = cm.getModeAt(range.head)
  6942. var indented = false
  6943. if (mode.electricChars) {
  6944. for (var j = 0; j < mode.electricChars.length; j++)
  6945. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  6946. indented = indentLine(cm, range.head.line, "smart")
  6947. break
  6948. } }
  6949. } else if (mode.electricInput) {
  6950. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  6951. { indented = indentLine(cm, range.head.line, "smart") }
  6952. }
  6953. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  6954. }
  6955. }
  6956. function copyableRanges(cm) {
  6957. var text = [], ranges = []
  6958. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  6959. var line = cm.doc.sel.ranges[i].head.line
  6960. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  6961. ranges.push(lineRange)
  6962. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  6963. }
  6964. return {text: text, ranges: ranges}
  6965. }
  6966. function disableBrowserMagic(field, spellcheck) {
  6967. field.setAttribute("autocorrect", "off")
  6968. field.setAttribute("autocapitalize", "off")
  6969. field.setAttribute("spellcheck", !!spellcheck)
  6970. }
  6971. function hiddenTextarea() {
  6972. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  6973. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  6974. // The textarea is kept positioned near the cursor to prevent the
  6975. // fact that it'll be scrolled into view on input from scrolling
  6976. // our fake cursor out of view. On webkit, when wrap=off, paste is
  6977. // very slow. So make the area wide instead.
  6978. if (webkit) { te.style.width = "1000px" }
  6979. else { te.setAttribute("wrap", "off") }
  6980. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  6981. if (ios) { te.style.border = "1px solid black" }
  6982. disableBrowserMagic(te)
  6983. return div
  6984. }
  6985. // The publicly visible API. Note that methodOp(f) means
  6986. // 'wrap f in an operation, performed on its `this` parameter'.
  6987. // This is not the complete set of editor methods. Most of the
  6988. // methods defined on the Doc type are also injected into
  6989. // CodeMirror.prototype, for backwards compatibility and
  6990. // convenience.
  6991. function addEditorMethods(CodeMirror) {
  6992. var optionHandlers = CodeMirror.optionHandlers
  6993. var helpers = CodeMirror.helpers = {}
  6994. CodeMirror.prototype = {
  6995. constructor: CodeMirror,
  6996. focus: function(){window.focus(); this.display.input.focus()},
  6997. setOption: function(option, value) {
  6998. var options = this.options, old = options[option]
  6999. if (options[option] == value && option != "mode") { return }
  7000. options[option] = value
  7001. if (optionHandlers.hasOwnProperty(option))
  7002. { operation(this, optionHandlers[option])(this, value, old) }
  7003. signal(this, "optionChange", this, option)
  7004. },
  7005. getOption: function(option) {return this.options[option]},
  7006. getDoc: function() {return this.doc},
  7007. addKeyMap: function(map, bottom) {
  7008. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  7009. },
  7010. removeKeyMap: function(map) {
  7011. var maps = this.state.keyMaps
  7012. for (var i = 0; i < maps.length; ++i)
  7013. { if (maps[i] == map || maps[i].name == map) {
  7014. maps.splice(i, 1)
  7015. return true
  7016. } }
  7017. },
  7018. addOverlay: methodOp(function(spec, options) {
  7019. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  7020. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7021. insertSorted(this.state.overlays,
  7022. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7023. priority: (options && options.priority) || 0},
  7024. function (overlay) { return overlay.priority; })
  7025. this.state.modeGen++
  7026. regChange(this)
  7027. }),
  7028. removeOverlay: methodOp(function(spec) {
  7029. var this$1 = this;
  7030. var overlays = this.state.overlays
  7031. for (var i = 0; i < overlays.length; ++i) {
  7032. var cur = overlays[i].modeSpec
  7033. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7034. overlays.splice(i, 1)
  7035. this$1.state.modeGen++
  7036. regChange(this$1)
  7037. return
  7038. }
  7039. }
  7040. }),
  7041. indentLine: methodOp(function(n, dir, aggressive) {
  7042. if (typeof dir != "string" && typeof dir != "number") {
  7043. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  7044. else { dir = dir ? "add" : "subtract" }
  7045. }
  7046. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  7047. }),
  7048. indentSelection: methodOp(function(how) {
  7049. var this$1 = this;
  7050. var ranges = this.doc.sel.ranges, end = -1
  7051. for (var i = 0; i < ranges.length; i++) {
  7052. var range = ranges[i]
  7053. if (!range.empty()) {
  7054. var from = range.from(), to = range.to()
  7055. var start = Math.max(end, from.line)
  7056. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  7057. for (var j = start; j < end; ++j)
  7058. { indentLine(this$1, j, how) }
  7059. var newRanges = this$1.doc.sel.ranges
  7060. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7061. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  7062. } else if (range.head.line > end) {
  7063. indentLine(this$1, range.head.line, how, true)
  7064. end = range.head.line
  7065. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  7066. }
  7067. }
  7068. }),
  7069. // Fetch the parser token for a given character. Useful for hacks
  7070. // that want to inspect the mode state (say, for completion).
  7071. getTokenAt: function(pos, precise) {
  7072. return takeToken(this, pos, precise)
  7073. },
  7074. getLineTokens: function(line, precise) {
  7075. return takeToken(this, Pos(line), precise, true)
  7076. },
  7077. getTokenTypeAt: function(pos) {
  7078. pos = clipPos(this.doc, pos)
  7079. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7080. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7081. var type
  7082. if (ch == 0) { type = styles[2] }
  7083. else { for (;;) {
  7084. var mid = (before + after) >> 1
  7085. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7086. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7087. else { type = styles[mid * 2 + 2]; break }
  7088. } }
  7089. var cut = type ? type.indexOf("overlay ") : -1
  7090. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7091. },
  7092. getModeAt: function(pos) {
  7093. var mode = this.doc.mode
  7094. if (!mode.innerMode) { return mode }
  7095. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7096. },
  7097. getHelper: function(pos, type) {
  7098. return this.getHelpers(pos, type)[0]
  7099. },
  7100. getHelpers: function(pos, type) {
  7101. var this$1 = this;
  7102. var found = []
  7103. if (!helpers.hasOwnProperty(type)) { return found }
  7104. var help = helpers[type], mode = this.getModeAt(pos)
  7105. if (typeof mode[type] == "string") {
  7106. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7107. } else if (mode[type]) {
  7108. for (var i = 0; i < mode[type].length; i++) {
  7109. var val = help[mode[type][i]]
  7110. if (val) { found.push(val) }
  7111. }
  7112. } else if (mode.helperType && help[mode.helperType]) {
  7113. found.push(help[mode.helperType])
  7114. } else if (help[mode.name]) {
  7115. found.push(help[mode.name])
  7116. }
  7117. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7118. var cur = help._global[i$1]
  7119. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7120. { found.push(cur.val) }
  7121. }
  7122. return found
  7123. },
  7124. getStateAfter: function(line, precise) {
  7125. var doc = this.doc
  7126. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7127. return getStateBefore(this, line + 1, precise)
  7128. },
  7129. cursorCoords: function(start, mode) {
  7130. var pos, range = this.doc.sel.primary()
  7131. if (start == null) { pos = range.head }
  7132. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7133. else { pos = start ? range.from() : range.to() }
  7134. return cursorCoords(this, pos, mode || "page")
  7135. },
  7136. charCoords: function(pos, mode) {
  7137. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7138. },
  7139. coordsChar: function(coords, mode) {
  7140. coords = fromCoordSystem(this, coords, mode || "page")
  7141. return coordsChar(this, coords.left, coords.top)
  7142. },
  7143. lineAtHeight: function(height, mode) {
  7144. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7145. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7146. },
  7147. heightAtLine: function(line, mode, includeWidgets) {
  7148. var end = false, lineObj
  7149. if (typeof line == "number") {
  7150. var last = this.doc.first + this.doc.size - 1
  7151. if (line < this.doc.first) { line = this.doc.first }
  7152. else if (line > last) { line = last; end = true }
  7153. lineObj = getLine(this.doc, line)
  7154. } else {
  7155. lineObj = line
  7156. }
  7157. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7158. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7159. },
  7160. defaultTextHeight: function() { return textHeight(this.display) },
  7161. defaultCharWidth: function() { return charWidth(this.display) },
  7162. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7163. addWidget: function(pos, node, scroll, vert, horiz) {
  7164. var display = this.display
  7165. pos = cursorCoords(this, clipPos(this.doc, pos))
  7166. var top = pos.bottom, left = pos.left
  7167. node.style.position = "absolute"
  7168. node.setAttribute("cm-ignore-events", "true")
  7169. this.display.input.setUneditable(node)
  7170. display.sizer.appendChild(node)
  7171. if (vert == "over") {
  7172. top = pos.top
  7173. } else if (vert == "above" || vert == "near") {
  7174. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7175. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7176. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7177. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7178. { top = pos.top - node.offsetHeight }
  7179. else if (pos.bottom + node.offsetHeight <= vspace)
  7180. { top = pos.bottom }
  7181. if (left + node.offsetWidth > hspace)
  7182. { left = hspace - node.offsetWidth }
  7183. }
  7184. node.style.top = top + "px"
  7185. node.style.left = node.style.right = ""
  7186. if (horiz == "right") {
  7187. left = display.sizer.clientWidth - node.offsetWidth
  7188. node.style.right = "0px"
  7189. } else {
  7190. if (horiz == "left") { left = 0 }
  7191. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7192. node.style.left = left + "px"
  7193. }
  7194. if (scroll)
  7195. { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) }
  7196. },
  7197. triggerOnKeyDown: methodOp(onKeyDown),
  7198. triggerOnKeyPress: methodOp(onKeyPress),
  7199. triggerOnKeyUp: onKeyUp,
  7200. execCommand: function(cmd) {
  7201. if (commands.hasOwnProperty(cmd))
  7202. { return commands[cmd].call(null, this) }
  7203. },
  7204. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7205. findPosH: function(from, amount, unit, visually) {
  7206. var this$1 = this;
  7207. var dir = 1
  7208. if (amount < 0) { dir = -1; amount = -amount }
  7209. var cur = clipPos(this.doc, from)
  7210. for (var i = 0; i < amount; ++i) {
  7211. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7212. if (cur.hitSide) { break }
  7213. }
  7214. return cur
  7215. },
  7216. moveH: methodOp(function(dir, unit) {
  7217. var this$1 = this;
  7218. this.extendSelectionsBy(function (range) {
  7219. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7220. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7221. else
  7222. { return dir < 0 ? range.from() : range.to() }
  7223. }, sel_move)
  7224. }),
  7225. deleteH: methodOp(function(dir, unit) {
  7226. var sel = this.doc.sel, doc = this.doc
  7227. if (sel.somethingSelected())
  7228. { doc.replaceSelection("", null, "+delete") }
  7229. else
  7230. { deleteNearSelection(this, function (range) {
  7231. var other = findPosH(doc, range.head, dir, unit, false)
  7232. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7233. }) }
  7234. }),
  7235. findPosV: function(from, amount, unit, goalColumn) {
  7236. var this$1 = this;
  7237. var dir = 1, x = goalColumn
  7238. if (amount < 0) { dir = -1; amount = -amount }
  7239. var cur = clipPos(this.doc, from)
  7240. for (var i = 0; i < amount; ++i) {
  7241. var coords = cursorCoords(this$1, cur, "div")
  7242. if (x == null) { x = coords.left }
  7243. else { coords.left = x }
  7244. cur = findPosV(this$1, coords, dir, unit)
  7245. if (cur.hitSide) { break }
  7246. }
  7247. return cur
  7248. },
  7249. moveV: methodOp(function(dir, unit) {
  7250. var this$1 = this;
  7251. var doc = this.doc, goals = []
  7252. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7253. doc.extendSelectionsBy(function (range) {
  7254. if (collapse)
  7255. { return dir < 0 ? range.from() : range.to() }
  7256. var headPos = cursorCoords(this$1, range.head, "div")
  7257. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7258. goals.push(headPos.left)
  7259. var pos = findPosV(this$1, headPos, dir, unit)
  7260. if (unit == "page" && range == doc.sel.primary())
  7261. { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) }
  7262. return pos
  7263. }, sel_move)
  7264. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7265. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7266. }),
  7267. // Find the word at the given position (as returned by coordsChar).
  7268. findWordAt: function(pos) {
  7269. var doc = this.doc, line = getLine(doc, pos.line).text
  7270. var start = pos.ch, end = pos.ch
  7271. if (line) {
  7272. var helper = this.getHelper(pos, "wordChars")
  7273. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end }
  7274. var startChar = line.charAt(start)
  7275. var check = isWordChar(startChar, helper)
  7276. ? function (ch) { return isWordChar(ch, helper); }
  7277. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7278. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7279. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7280. while (end < line.length && check(line.charAt(end))) { ++end }
  7281. }
  7282. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7283. },
  7284. toggleOverwrite: function(value) {
  7285. if (value != null && value == this.state.overwrite) { return }
  7286. if (this.state.overwrite = !this.state.overwrite)
  7287. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7288. else
  7289. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7290. signal(this, "overwriteToggle", this, this.state.overwrite)
  7291. },
  7292. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7293. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7294. scrollTo: methodOp(function(x, y) {
  7295. if (x != null || y != null) { resolveScrollToPos(this) }
  7296. if (x != null) { this.curOp.scrollLeft = x }
  7297. if (y != null) { this.curOp.scrollTop = y }
  7298. }),
  7299. getScrollInfo: function() {
  7300. var scroller = this.display.scroller
  7301. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7302. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7303. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7304. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7305. },
  7306. scrollIntoView: methodOp(function(range, margin) {
  7307. if (range == null) {
  7308. range = {from: this.doc.sel.primary().head, to: null}
  7309. if (margin == null) { margin = this.options.cursorScrollMargin }
  7310. } else if (typeof range == "number") {
  7311. range = {from: Pos(range, 0), to: null}
  7312. } else if (range.from == null) {
  7313. range = {from: range, to: null}
  7314. }
  7315. if (!range.to) { range.to = range.from }
  7316. range.margin = margin || 0
  7317. if (range.from.line != null) {
  7318. resolveScrollToPos(this)
  7319. this.curOp.scrollToPos = range
  7320. } else {
  7321. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  7322. Math.min(range.from.top, range.to.top) - range.margin,
  7323. Math.max(range.from.right, range.to.right),
  7324. Math.max(range.from.bottom, range.to.bottom) + range.margin)
  7325. this.scrollTo(sPos.scrollLeft, sPos.scrollTop)
  7326. }
  7327. }),
  7328. setSize: methodOp(function(width, height) {
  7329. var this$1 = this;
  7330. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7331. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7332. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7333. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7334. var lineNo = this.display.viewFrom
  7335. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7336. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7337. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7338. ++lineNo
  7339. })
  7340. this.curOp.forceUpdate = true
  7341. signal(this, "refresh", this)
  7342. }),
  7343. operation: function(f){return runInOp(this, f)},
  7344. refresh: methodOp(function() {
  7345. var oldHeight = this.display.cachedTextHeight
  7346. regChange(this)
  7347. this.curOp.forceUpdate = true
  7348. clearCaches(this)
  7349. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop)
  7350. updateGutterSpace(this)
  7351. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7352. { estimateLineHeights(this) }
  7353. signal(this, "refresh", this)
  7354. }),
  7355. swapDoc: methodOp(function(doc) {
  7356. var old = this.doc
  7357. old.cm = null
  7358. attachDoc(this, doc)
  7359. clearCaches(this)
  7360. this.display.input.reset()
  7361. this.scrollTo(doc.scrollLeft, doc.scrollTop)
  7362. this.curOp.forceScroll = true
  7363. signalLater(this, "swapDoc", this, old)
  7364. return old
  7365. }),
  7366. getInputField: function(){return this.display.input.getField()},
  7367. getWrapperElement: function(){return this.display.wrapper},
  7368. getScrollerElement: function(){return this.display.scroller},
  7369. getGutterElement: function(){return this.display.gutters}
  7370. }
  7371. eventMixin(CodeMirror)
  7372. CodeMirror.registerHelper = function(type, name, value) {
  7373. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7374. helpers[type][name] = value
  7375. }
  7376. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7377. CodeMirror.registerHelper(type, name, value)
  7378. helpers[type]._global.push({pred: predicate, val: value})
  7379. }
  7380. }
  7381. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7382. // right), unit can be "char", "column" (like char, but doesn't
  7383. // cross line boundaries), "word" (across next word), or "group" (to
  7384. // the start of next group of word or non-word-non-whitespace
  7385. // chars). The visually param controls whether, in right-to-left
  7386. // text, direction 1 means to move towards the next index in the
  7387. // string, or towards the character to the right of the current
  7388. // position. The resulting position will have a hitSide=true
  7389. // property if it reached the end of the document.
  7390. function findPosH(doc, pos, dir, unit, visually) {
  7391. var oldPos = pos
  7392. var origDir = dir
  7393. var lineObj = getLine(doc, pos.line)
  7394. function findNextLine() {
  7395. var l = pos.line + dir
  7396. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7397. pos = new Pos(l, pos.ch, pos.sticky)
  7398. return lineObj = getLine(doc, l)
  7399. }
  7400. function moveOnce(boundToLine) {
  7401. var next
  7402. if (visually) {
  7403. next = moveVisually(doc.cm, lineObj, pos, dir)
  7404. } else {
  7405. next = moveLogically(lineObj, pos, dir)
  7406. }
  7407. if (next == null) {
  7408. if (!boundToLine && findNextLine())
  7409. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) }
  7410. else
  7411. { return false }
  7412. } else {
  7413. pos = next
  7414. }
  7415. return true
  7416. }
  7417. if (unit == "char") {
  7418. moveOnce()
  7419. } else if (unit == "column") {
  7420. moveOnce(true)
  7421. } else if (unit == "word" || unit == "group") {
  7422. var sawType = null, group = unit == "group"
  7423. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7424. for (var first = true;; first = false) {
  7425. if (dir < 0 && !moveOnce(!first)) { break }
  7426. var cur = lineObj.text.charAt(pos.ch) || "\n"
  7427. var type = isWordChar(cur, helper) ? "w"
  7428. : group && cur == "\n" ? "n"
  7429. : !group || /\s/.test(cur) ? null
  7430. : "p"
  7431. if (group && !first && !type) { type = "s" }
  7432. if (sawType && sawType != type) {
  7433. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"}
  7434. break
  7435. }
  7436. if (type) { sawType = type }
  7437. if (dir > 0 && !moveOnce(!first)) { break }
  7438. }
  7439. }
  7440. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  7441. if (equalCursorPos(oldPos, result)) { result.hitSide = true }
  7442. return result
  7443. }
  7444. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7445. // "page" or "line". The resulting position will have a hitSide=true
  7446. // property if it reached the end of the document.
  7447. function findPosV(cm, pos, dir, unit) {
  7448. var doc = cm.doc, x = pos.left, y
  7449. if (unit == "page") {
  7450. var pagesize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7451. var moveAmount = Math.max(pagesize - .5 * textHeight(cm.display), 3)
  7452. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7453. } else if (unit == "line") {
  7454. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7455. }
  7456. var target
  7457. for (;;) {
  7458. target = coordsChar(cm, x, y)
  7459. if (!target.outside) { break }
  7460. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7461. y += dir * 5
  7462. }
  7463. return target
  7464. }
  7465. // CONTENTEDITABLE INPUT STYLE
  7466. var ContentEditableInput = function(cm) {
  7467. this.cm = cm
  7468. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7469. this.polling = new Delayed()
  7470. this.composing = null
  7471. this.gracePeriod = false
  7472. this.readDOMTimeout = null
  7473. };
  7474. ContentEditableInput.prototype.init = function (display) {
  7475. var this$1 = this;
  7476. var input = this, cm = input.cm
  7477. var div = input.div = display.lineDiv
  7478. disableBrowserMagic(div, cm.options.spellcheck)
  7479. on(div, "paste", function (e) {
  7480. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7481. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7482. if (ie_version <= 11) { setTimeout(operation(cm, function () {
  7483. if (!input.pollContent()) { regChange(cm) }
  7484. }), 20) }
  7485. })
  7486. on(div, "compositionstart", function (e) {
  7487. this$1.composing = {data: e.data, done: false}
  7488. })
  7489. on(div, "compositionupdate", function (e) {
  7490. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7491. })
  7492. on(div, "compositionend", function (e) {
  7493. if (this$1.composing) {
  7494. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7495. this$1.composing.done = true
  7496. }
  7497. })
  7498. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7499. on(div, "input", function () {
  7500. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7501. })
  7502. function onCopyCut(e) {
  7503. if (signalDOMEvent(cm, e)) { return }
  7504. if (cm.somethingSelected()) {
  7505. setLastCopied({lineWise: false, text: cm.getSelections()})
  7506. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7507. } else if (!cm.options.lineWiseCopyCut) {
  7508. return
  7509. } else {
  7510. var ranges = copyableRanges(cm)
  7511. setLastCopied({lineWise: true, text: ranges.text})
  7512. if (e.type == "cut") {
  7513. cm.operation(function () {
  7514. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7515. cm.replaceSelection("", null, "cut")
  7516. })
  7517. }
  7518. }
  7519. if (e.clipboardData) {
  7520. e.clipboardData.clearData()
  7521. var content = lastCopied.text.join("\n")
  7522. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7523. e.clipboardData.setData("Text", content)
  7524. if (e.clipboardData.getData("Text") == content) {
  7525. e.preventDefault()
  7526. return
  7527. }
  7528. }
  7529. // Old-fashioned briefly-focus-a-textarea hack
  7530. var kludge = hiddenTextarea(), te = kludge.firstChild
  7531. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7532. te.value = lastCopied.text.join("\n")
  7533. var hadFocus = document.activeElement
  7534. selectInput(te)
  7535. setTimeout(function () {
  7536. cm.display.lineSpace.removeChild(kludge)
  7537. hadFocus.focus()
  7538. if (hadFocus == div) { input.showPrimarySelection() }
  7539. }, 50)
  7540. }
  7541. on(div, "copy", onCopyCut)
  7542. on(div, "cut", onCopyCut)
  7543. };
  7544. ContentEditableInput.prototype.prepareSelection = function () {
  7545. var result = prepareSelection(this.cm, false)
  7546. result.focus = this.cm.state.focused
  7547. return result
  7548. };
  7549. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7550. if (!info || !this.cm.display.view.length) { return }
  7551. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7552. this.showMultipleSelections(info)
  7553. };
  7554. ContentEditableInput.prototype.showPrimarySelection = function () {
  7555. var sel = window.getSelection(), prim = this.cm.doc.sel.primary()
  7556. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset)
  7557. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset)
  7558. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7559. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  7560. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  7561. { return }
  7562. var start = posToDOM(this.cm, prim.from())
  7563. var end = posToDOM(this.cm, prim.to())
  7564. if (!start && !end) { return }
  7565. var view = this.cm.display.view
  7566. var old = sel.rangeCount && sel.getRangeAt(0)
  7567. if (!start) {
  7568. start = {node: view[0].measure.map[2], offset: 0}
  7569. } else if (!end) { // FIXME dangerously hacky
  7570. var measure = view[view.length - 1].measure
  7571. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7572. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7573. }
  7574. var rng
  7575. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7576. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7577. if (rng) {
  7578. if (!gecko && this.cm.state.focused) {
  7579. sel.collapse(start.node, start.offset)
  7580. if (!rng.collapsed) {
  7581. sel.removeAllRanges()
  7582. sel.addRange(rng)
  7583. }
  7584. } else {
  7585. sel.removeAllRanges()
  7586. sel.addRange(rng)
  7587. }
  7588. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7589. else if (gecko) { this.startGracePeriod() }
  7590. }
  7591. this.rememberSelection()
  7592. };
  7593. ContentEditableInput.prototype.startGracePeriod = function () {
  7594. var this$1 = this;
  7595. clearTimeout(this.gracePeriod)
  7596. this.gracePeriod = setTimeout(function () {
  7597. this$1.gracePeriod = false
  7598. if (this$1.selectionChanged())
  7599. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7600. }, 20)
  7601. };
  7602. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7603. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7604. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7605. };
  7606. ContentEditableInput.prototype.rememberSelection = function () {
  7607. var sel = window.getSelection()
  7608. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7609. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7610. };
  7611. ContentEditableInput.prototype.selectionInEditor = function () {
  7612. var sel = window.getSelection()
  7613. if (!sel.rangeCount) { return false }
  7614. var node = sel.getRangeAt(0).commonAncestorContainer
  7615. return contains(this.div, node)
  7616. };
  7617. ContentEditableInput.prototype.focus = function () {
  7618. if (this.cm.options.readOnly != "nocursor") {
  7619. if (!this.selectionInEditor())
  7620. { this.showSelection(this.prepareSelection(), true) }
  7621. this.div.focus()
  7622. }
  7623. };
  7624. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7625. ContentEditableInput.prototype.getField = function () { return this.div };
  7626. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7627. ContentEditableInput.prototype.receivedFocus = function () {
  7628. var input = this
  7629. if (this.selectionInEditor())
  7630. { this.pollSelection() }
  7631. else
  7632. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7633. function poll() {
  7634. if (input.cm.state.focused) {
  7635. input.pollSelection()
  7636. input.polling.set(input.cm.options.pollInterval, poll)
  7637. }
  7638. }
  7639. this.polling.set(this.cm.options.pollInterval, poll)
  7640. };
  7641. ContentEditableInput.prototype.selectionChanged = function () {
  7642. var sel = window.getSelection()
  7643. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7644. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7645. };
  7646. ContentEditableInput.prototype.pollSelection = function () {
  7647. if (!this.composing && this.readDOMTimeout == null && !this.gracePeriod && this.selectionChanged()) {
  7648. var sel = window.getSelection(), cm = this.cm
  7649. this.rememberSelection()
  7650. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7651. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  7652. if (anchor && head) { runInOp(cm, function () {
  7653. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  7654. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  7655. }) }
  7656. }
  7657. };
  7658. ContentEditableInput.prototype.pollContent = function () {
  7659. if (this.readDOMTimeout != null) {
  7660. clearTimeout(this.readDOMTimeout)
  7661. this.readDOMTimeout = null
  7662. }
  7663. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  7664. var from = sel.from(), to = sel.to()
  7665. if (from.ch == 0 && from.line > cm.firstLine())
  7666. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  7667. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  7668. { to = Pos(to.line + 1, 0) }
  7669. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  7670. var fromIndex, fromLine, fromNode
  7671. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  7672. fromLine = lineNo(display.view[0].line)
  7673. fromNode = display.view[0].node
  7674. } else {
  7675. fromLine = lineNo(display.view[fromIndex].line)
  7676. fromNode = display.view[fromIndex - 1].node.nextSibling
  7677. }
  7678. var toIndex = findViewIndex(cm, to.line)
  7679. var toLine, toNode
  7680. if (toIndex == display.view.length - 1) {
  7681. toLine = display.viewTo - 1
  7682. toNode = display.lineDiv.lastChild
  7683. } else {
  7684. toLine = lineNo(display.view[toIndex + 1].line) - 1
  7685. toNode = display.view[toIndex + 1].node.previousSibling
  7686. }
  7687. if (!fromNode) { return false }
  7688. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  7689. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  7690. while (newText.length > 1 && oldText.length > 1) {
  7691. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  7692. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  7693. else { break }
  7694. }
  7695. var cutFront = 0, cutEnd = 0
  7696. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  7697. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  7698. { ++cutFront }
  7699. var newBot = lst(newText), oldBot = lst(oldText)
  7700. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  7701. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  7702. while (cutEnd < maxCutEnd &&
  7703. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  7704. { ++cutEnd }
  7705. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  7706. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  7707. var chFrom = Pos(fromLine, cutFront)
  7708. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  7709. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  7710. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  7711. return true
  7712. }
  7713. };
  7714. ContentEditableInput.prototype.ensurePolled = function () {
  7715. this.forceCompositionEnd()
  7716. };
  7717. ContentEditableInput.prototype.reset = function () {
  7718. this.forceCompositionEnd()
  7719. };
  7720. ContentEditableInput.prototype.forceCompositionEnd = function () {
  7721. if (!this.composing) { return }
  7722. clearTimeout(this.readDOMTimeout)
  7723. this.composing = null
  7724. if (!this.pollContent()) { regChange(this.cm) }
  7725. this.div.blur()
  7726. this.div.focus()
  7727. };
  7728. ContentEditableInput.prototype.readFromDOMSoon = function () {
  7729. var this$1 = this;
  7730. if (this.readDOMTimeout != null) { return }
  7731. this.readDOMTimeout = setTimeout(function () {
  7732. this$1.readDOMTimeout = null
  7733. if (this$1.composing) {
  7734. if (this$1.composing.done) { this$1.composing = null }
  7735. else { return }
  7736. }
  7737. if (this$1.cm.isReadOnly() || !this$1.pollContent())
  7738. { runInOp(this$1.cm, function () { return regChange(this$1.cm); }) }
  7739. }, 80)
  7740. };
  7741. ContentEditableInput.prototype.setUneditable = function (node) {
  7742. node.contentEditable = "false"
  7743. };
  7744. ContentEditableInput.prototype.onKeyPress = function (e) {
  7745. if (e.charCode == 0) { return }
  7746. e.preventDefault()
  7747. if (!this.cm.isReadOnly())
  7748. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  7749. };
  7750. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  7751. this.div.contentEditable = String(val != "nocursor")
  7752. };
  7753. ContentEditableInput.prototype.onContextMenu = function () {};
  7754. ContentEditableInput.prototype.resetPosition = function () {};
  7755. ContentEditableInput.prototype.needsContentAttribute = true
  7756. function posToDOM(cm, pos) {
  7757. var view = findViewForLine(cm, pos.line)
  7758. if (!view || view.hidden) { return null }
  7759. var line = getLine(cm.doc, pos.line)
  7760. var info = mapFromLineView(view, line, pos.line)
  7761. var order = getOrder(line), side = "left"
  7762. if (order) {
  7763. var partPos = getBidiPartAt(order, pos.ch)
  7764. side = partPos % 2 ? "right" : "left"
  7765. }
  7766. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  7767. result.offset = result.collapse == "right" ? result.end : result.start
  7768. return result
  7769. }
  7770. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  7771. function domTextBetween(cm, from, to, fromLine, toLine) {
  7772. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  7773. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  7774. function walk(node) {
  7775. if (node.nodeType == 1) {
  7776. var cmText = node.getAttribute("cm-text")
  7777. if (cmText != null) {
  7778. if (cmText == "") { text += node.textContent.replace(/\u200b/g, "") }
  7779. else { text += cmText }
  7780. return
  7781. }
  7782. var markerID = node.getAttribute("cm-marker"), range
  7783. if (markerID) {
  7784. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  7785. if (found.length && (range = found[0].find()))
  7786. { text += getBetween(cm.doc, range.from, range.to).join(lineSep) }
  7787. return
  7788. }
  7789. if (node.getAttribute("contenteditable") == "false") { return }
  7790. for (var i = 0; i < node.childNodes.length; i++)
  7791. { walk(node.childNodes[i]) }
  7792. if (/^(pre|div|p)$/i.test(node.nodeName))
  7793. { closing = true }
  7794. } else if (node.nodeType == 3) {
  7795. var val = node.nodeValue
  7796. if (!val) { return }
  7797. if (closing) {
  7798. text += lineSep
  7799. closing = false
  7800. }
  7801. text += val
  7802. }
  7803. }
  7804. for (;;) {
  7805. walk(from)
  7806. if (from == to) { break }
  7807. from = from.nextSibling
  7808. }
  7809. return text
  7810. }
  7811. function domToPos(cm, node, offset) {
  7812. var lineNode
  7813. if (node == cm.display.lineDiv) {
  7814. lineNode = cm.display.lineDiv.childNodes[offset]
  7815. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  7816. node = null; offset = 0
  7817. } else {
  7818. for (lineNode = node;; lineNode = lineNode.parentNode) {
  7819. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  7820. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  7821. }
  7822. }
  7823. for (var i = 0; i < cm.display.view.length; i++) {
  7824. var lineView = cm.display.view[i]
  7825. if (lineView.node == lineNode)
  7826. { return locateNodeInLineView(lineView, node, offset) }
  7827. }
  7828. }
  7829. function locateNodeInLineView(lineView, node, offset) {
  7830. var wrapper = lineView.text.firstChild, bad = false
  7831. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  7832. if (node == wrapper) {
  7833. bad = true
  7834. node = wrapper.childNodes[offset]
  7835. offset = 0
  7836. if (!node) {
  7837. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  7838. return badPos(Pos(lineNo(line), line.text.length), bad)
  7839. }
  7840. }
  7841. var textNode = node.nodeType == 3 ? node : null, topNode = node
  7842. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  7843. textNode = node.firstChild
  7844. if (offset) { offset = textNode.nodeValue.length }
  7845. }
  7846. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  7847. var measure = lineView.measure, maps = measure.maps
  7848. function find(textNode, topNode, offset) {
  7849. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  7850. var map = i < 0 ? measure.map : maps[i]
  7851. for (var j = 0; j < map.length; j += 3) {
  7852. var curNode = map[j + 2]
  7853. if (curNode == textNode || curNode == topNode) {
  7854. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  7855. var ch = map[j] + offset
  7856. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  7857. return Pos(line, ch)
  7858. }
  7859. }
  7860. }
  7861. }
  7862. var found = find(textNode, topNode, offset)
  7863. if (found) { return badPos(found, bad) }
  7864. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  7865. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  7866. found = find(after, after.firstChild, 0)
  7867. if (found)
  7868. { return badPos(Pos(found.line, found.ch - dist), bad) }
  7869. else
  7870. { dist += after.textContent.length }
  7871. }
  7872. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  7873. found = find(before, before.firstChild, -1)
  7874. if (found)
  7875. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  7876. else
  7877. { dist$1 += before.textContent.length }
  7878. }
  7879. }
  7880. // TEXTAREA INPUT STYLE
  7881. var TextareaInput = function(cm) {
  7882. this.cm = cm
  7883. // See input.poll and input.reset
  7884. this.prevInput = ""
  7885. // Flag that indicates whether we expect input to appear real soon
  7886. // now (after some event like 'keypress' or 'input') and are
  7887. // polling intensively.
  7888. this.pollingFast = false
  7889. // Self-resetting timeout for the poller
  7890. this.polling = new Delayed()
  7891. // Tracks when input.reset has punted to just putting a short
  7892. // string into the textarea instead of the full selection.
  7893. this.inaccurateSelection = false
  7894. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  7895. this.hasSelection = false
  7896. this.composing = null
  7897. };
  7898. TextareaInput.prototype.init = function (display) {
  7899. var this$1 = this;
  7900. var input = this, cm = this.cm
  7901. // Wraps and hides input textarea
  7902. var div = this.wrapper = hiddenTextarea()
  7903. // The semihidden textarea that is focused when the editor is
  7904. // focused, and receives input.
  7905. var te = this.textarea = div.firstChild
  7906. display.wrapper.insertBefore(div, display.wrapper.firstChild)
  7907. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  7908. if (ios) { te.style.width = "0px" }
  7909. on(te, "input", function () {
  7910. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  7911. input.poll()
  7912. })
  7913. on(te, "paste", function (e) {
  7914. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7915. cm.state.pasteIncoming = true
  7916. input.fastPoll()
  7917. })
  7918. function prepareCopyCut(e) {
  7919. if (signalDOMEvent(cm, e)) { return }
  7920. if (cm.somethingSelected()) {
  7921. setLastCopied({lineWise: false, text: cm.getSelections()})
  7922. if (input.inaccurateSelection) {
  7923. input.prevInput = ""
  7924. input.inaccurateSelection = false
  7925. te.value = lastCopied.text.join("\n")
  7926. selectInput(te)
  7927. }
  7928. } else if (!cm.options.lineWiseCopyCut) {
  7929. return
  7930. } else {
  7931. var ranges = copyableRanges(cm)
  7932. setLastCopied({lineWise: true, text: ranges.text})
  7933. if (e.type == "cut") {
  7934. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  7935. } else {
  7936. input.prevInput = ""
  7937. te.value = ranges.text.join("\n")
  7938. selectInput(te)
  7939. }
  7940. }
  7941. if (e.type == "cut") { cm.state.cutIncoming = true }
  7942. }
  7943. on(te, "cut", prepareCopyCut)
  7944. on(te, "copy", prepareCopyCut)
  7945. on(display.scroller, "paste", function (e) {
  7946. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  7947. cm.state.pasteIncoming = true
  7948. input.focus()
  7949. })
  7950. // Prevent normal selection in the editor (we handle our own)
  7951. on(display.lineSpace, "selectstart", function (e) {
  7952. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  7953. })
  7954. on(te, "compositionstart", function () {
  7955. var start = cm.getCursor("from")
  7956. if (input.composing) { input.composing.range.clear() }
  7957. input.composing = {
  7958. start: start,
  7959. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  7960. }
  7961. })
  7962. on(te, "compositionend", function () {
  7963. if (input.composing) {
  7964. input.poll()
  7965. input.composing.range.clear()
  7966. input.composing = null
  7967. }
  7968. })
  7969. };
  7970. TextareaInput.prototype.prepareSelection = function () {
  7971. // Redraw the selection and/or cursor
  7972. var cm = this.cm, display = cm.display, doc = cm.doc
  7973. var result = prepareSelection(cm)
  7974. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  7975. if (cm.options.moveInputWithCursor) {
  7976. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  7977. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  7978. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  7979. headPos.top + lineOff.top - wrapOff.top))
  7980. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  7981. headPos.left + lineOff.left - wrapOff.left))
  7982. }
  7983. return result
  7984. };
  7985. TextareaInput.prototype.showSelection = function (drawn) {
  7986. var cm = this.cm, display = cm.display
  7987. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  7988. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  7989. if (drawn.teTop != null) {
  7990. this.wrapper.style.top = drawn.teTop + "px"
  7991. this.wrapper.style.left = drawn.teLeft + "px"
  7992. }
  7993. };
  7994. // Reset the input to correspond to the selection (or to be empty,
  7995. // when not typing and nothing is selected)
  7996. TextareaInput.prototype.reset = function (typing) {
  7997. if (this.contextMenuPending) { return }
  7998. var minimal, selected, cm = this.cm, doc = cm.doc
  7999. if (cm.somethingSelected()) {
  8000. this.prevInput = ""
  8001. var range = doc.sel.primary()
  8002. minimal = hasCopyEvent &&
  8003. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000)
  8004. var content = minimal ? "-" : selected || cm.getSelection()
  8005. this.textarea.value = content
  8006. if (cm.state.focused) { selectInput(this.textarea) }
  8007. if (ie && ie_version >= 9) { this.hasSelection = content }
  8008. } else if (!typing) {
  8009. this.prevInput = this.textarea.value = ""
  8010. if (ie && ie_version >= 9) { this.hasSelection = null }
  8011. }
  8012. this.inaccurateSelection = minimal
  8013. };
  8014. TextareaInput.prototype.getField = function () { return this.textarea };
  8015. TextareaInput.prototype.supportsTouch = function () { return false };
  8016. TextareaInput.prototype.focus = function () {
  8017. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8018. try { this.textarea.focus() }
  8019. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8020. }
  8021. };
  8022. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  8023. TextareaInput.prototype.resetPosition = function () {
  8024. this.wrapper.style.top = this.wrapper.style.left = 0
  8025. };
  8026. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  8027. // Poll for input changes, using the normal rate of polling. This
  8028. // runs as long as the editor is focused.
  8029. TextareaInput.prototype.slowPoll = function () {
  8030. var this$1 = this;
  8031. if (this.pollingFast) { return }
  8032. this.polling.set(this.cm.options.pollInterval, function () {
  8033. this$1.poll()
  8034. if (this$1.cm.state.focused) { this$1.slowPoll() }
  8035. })
  8036. };
  8037. // When an event has just come in that is likely to add or change
  8038. // something in the input textarea, we poll faster, to ensure that
  8039. // the change appears on the screen quickly.
  8040. TextareaInput.prototype.fastPoll = function () {
  8041. var missed = false, input = this
  8042. input.pollingFast = true
  8043. function p() {
  8044. var changed = input.poll()
  8045. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  8046. else {input.pollingFast = false; input.slowPoll()}
  8047. }
  8048. input.polling.set(20, p)
  8049. };
  8050. // Read input from the textarea, and update the document to match.
  8051. // When something is selected, it is present in the textarea, and
  8052. // selected (unless it is huge, in which case a placeholder is
  8053. // used). When nothing is selected, the cursor sits after previously
  8054. // seen text (can be empty), which is stored in prevInput (we must
  8055. // not reset the textarea when typing, because that breaks IME).
  8056. TextareaInput.prototype.poll = function () {
  8057. var this$1 = this;
  8058. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  8059. // Since this is called a *lot*, try to bail out as cheaply as
  8060. // possible when it is clear that nothing happened. hasSelection
  8061. // will be the case when there is a lot of text in the textarea,
  8062. // in which case reading its value would be expensive.
  8063. if (this.contextMenuPending || !cm.state.focused ||
  8064. (hasSelection(input) && !prevInput && !this.composing) ||
  8065. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8066. { return false }
  8067. var text = input.value
  8068. // If nothing changed, bail.
  8069. if (text == prevInput && !cm.somethingSelected()) { return false }
  8070. // Work around nonsensical selection resetting in IE9/10, and
  8071. // inexplicable appearance of private area unicode characters on
  8072. // some key combos in Mac (#2689).
  8073. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8074. mac && /[\uf700-\uf7ff]/.test(text)) {
  8075. cm.display.input.reset()
  8076. return false
  8077. }
  8078. if (cm.doc.sel == cm.display.selForContextMenu) {
  8079. var first = text.charCodeAt(0)
  8080. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  8081. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8082. }
  8083. // Find the part of the input that is actually new
  8084. var same = 0, l = Math.min(prevInput.length, text.length)
  8085. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8086. runInOp(cm, function () {
  8087. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8088. null, this$1.composing ? "*compose" : null)
  8089. // Don't leave long text in the textarea, since it makes further polling slow
  8090. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8091. else { this$1.prevInput = text }
  8092. if (this$1.composing) {
  8093. this$1.composing.range.clear()
  8094. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8095. {className: "CodeMirror-composing"})
  8096. }
  8097. })
  8098. return true
  8099. };
  8100. TextareaInput.prototype.ensurePolled = function () {
  8101. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8102. };
  8103. TextareaInput.prototype.onKeyPress = function () {
  8104. if (ie && ie_version >= 9) { this.hasSelection = null }
  8105. this.fastPoll()
  8106. };
  8107. TextareaInput.prototype.onContextMenu = function (e) {
  8108. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8109. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8110. if (!pos || presto) { return } // Opera is difficult.
  8111. // Reset the current text selection only if the click is done outside of the selection
  8112. // and 'resetSelectionOnContextMenu' option is true.
  8113. var reset = cm.options.resetSelectionOnContextMenu
  8114. if (reset && cm.doc.sel.contains(pos) == -1)
  8115. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8116. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8117. input.wrapper.style.cssText = "position: absolute"
  8118. var wrapperBox = input.wrapper.getBoundingClientRect()
  8119. 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);"
  8120. var oldScrollY
  8121. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8122. display.input.focus()
  8123. if (webkit) { window.scrollTo(null, oldScrollY) }
  8124. display.input.reset()
  8125. // Adds "Select all" to context menu in FF
  8126. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8127. input.contextMenuPending = true
  8128. display.selForContextMenu = cm.doc.sel
  8129. clearTimeout(display.detectingSelectAll)
  8130. // Select-all will be greyed out if there's nothing to select, so
  8131. // this adds a zero-width space so that we can later check whether
  8132. // it got selected.
  8133. function prepareSelectAllHack() {
  8134. if (te.selectionStart != null) {
  8135. var selected = cm.somethingSelected()
  8136. var extval = "\u200b" + (selected ? te.value : "")
  8137. te.value = "\u21da" // Used to catch context-menu undo
  8138. te.value = extval
  8139. input.prevInput = selected ? "" : "\u200b"
  8140. te.selectionStart = 1; te.selectionEnd = extval.length
  8141. // Re-set this, in case some other handler touched the
  8142. // selection in the meantime.
  8143. display.selForContextMenu = cm.doc.sel
  8144. }
  8145. }
  8146. function rehide() {
  8147. input.contextMenuPending = false
  8148. input.wrapper.style.cssText = oldWrapperCSS
  8149. te.style.cssText = oldCSS
  8150. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8151. // Try to detect the user choosing select-all
  8152. if (te.selectionStart != null) {
  8153. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8154. var i = 0, poll = function () {
  8155. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8156. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8157. operation(cm, selectAll)(cm)
  8158. } else if (i++ < 10) {
  8159. display.detectingSelectAll = setTimeout(poll, 500)
  8160. } else {
  8161. display.selForContextMenu = null
  8162. display.input.reset()
  8163. }
  8164. }
  8165. display.detectingSelectAll = setTimeout(poll, 200)
  8166. }
  8167. }
  8168. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8169. if (captureRightClick) {
  8170. e_stop(e)
  8171. var mouseup = function () {
  8172. off(window, "mouseup", mouseup)
  8173. setTimeout(rehide, 20)
  8174. }
  8175. on(window, "mouseup", mouseup)
  8176. } else {
  8177. setTimeout(rehide, 50)
  8178. }
  8179. };
  8180. TextareaInput.prototype.readOnlyChanged = function (val) {
  8181. if (!val) { this.reset() }
  8182. };
  8183. TextareaInput.prototype.setUneditable = function () {};
  8184. TextareaInput.prototype.needsContentAttribute = false
  8185. function fromTextArea(textarea, options) {
  8186. options = options ? copyObj(options) : {}
  8187. options.value = textarea.value
  8188. if (!options.tabindex && textarea.tabIndex)
  8189. { options.tabindex = textarea.tabIndex }
  8190. if (!options.placeholder && textarea.placeholder)
  8191. { options.placeholder = textarea.placeholder }
  8192. // Set autofocus to true if this textarea is focused, or if it has
  8193. // autofocus and no other element is focused.
  8194. if (options.autofocus == null) {
  8195. var hasFocus = activeElt()
  8196. options.autofocus = hasFocus == textarea ||
  8197. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8198. }
  8199. function save() {textarea.value = cm.getValue()}
  8200. var realSubmit
  8201. if (textarea.form) {
  8202. on(textarea.form, "submit", save)
  8203. // Deplorable hack to make the submit method do the right thing.
  8204. if (!options.leaveSubmitMethodAlone) {
  8205. var form = textarea.form
  8206. realSubmit = form.submit
  8207. try {
  8208. var wrappedSubmit = form.submit = function () {
  8209. save()
  8210. form.submit = realSubmit
  8211. form.submit()
  8212. form.submit = wrappedSubmit
  8213. }
  8214. } catch(e) {}
  8215. }
  8216. }
  8217. options.finishInit = function (cm) {
  8218. cm.save = save
  8219. cm.getTextArea = function () { return textarea; }
  8220. cm.toTextArea = function () {
  8221. cm.toTextArea = isNaN // Prevent this from being ran twice
  8222. save()
  8223. textarea.parentNode.removeChild(cm.getWrapperElement())
  8224. textarea.style.display = ""
  8225. if (textarea.form) {
  8226. off(textarea.form, "submit", save)
  8227. if (typeof textarea.form.submit == "function")
  8228. { textarea.form.submit = realSubmit }
  8229. }
  8230. }
  8231. }
  8232. textarea.style.display = "none"
  8233. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8234. options)
  8235. return cm
  8236. }
  8237. function addLegacyProps(CodeMirror) {
  8238. CodeMirror.off = off
  8239. CodeMirror.on = on
  8240. CodeMirror.wheelEventPixels = wheelEventPixels
  8241. CodeMirror.Doc = Doc
  8242. CodeMirror.splitLines = splitLinesAuto
  8243. CodeMirror.countColumn = countColumn
  8244. CodeMirror.findColumn = findColumn
  8245. CodeMirror.isWordChar = isWordCharBasic
  8246. CodeMirror.Pass = Pass
  8247. CodeMirror.signal = signal
  8248. CodeMirror.Line = Line
  8249. CodeMirror.changeEnd = changeEnd
  8250. CodeMirror.scrollbarModel = scrollbarModel
  8251. CodeMirror.Pos = Pos
  8252. CodeMirror.cmpPos = cmp
  8253. CodeMirror.modes = modes
  8254. CodeMirror.mimeModes = mimeModes
  8255. CodeMirror.resolveMode = resolveMode
  8256. CodeMirror.getMode = getMode
  8257. CodeMirror.modeExtensions = modeExtensions
  8258. CodeMirror.extendMode = extendMode
  8259. CodeMirror.copyState = copyState
  8260. CodeMirror.startState = startState
  8261. CodeMirror.innerMode = innerMode
  8262. CodeMirror.commands = commands
  8263. CodeMirror.keyMap = keyMap
  8264. CodeMirror.keyName = keyName
  8265. CodeMirror.isModifierKey = isModifierKey
  8266. CodeMirror.lookupKey = lookupKey
  8267. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8268. CodeMirror.StringStream = StringStream
  8269. CodeMirror.SharedTextMarker = SharedTextMarker
  8270. CodeMirror.TextMarker = TextMarker
  8271. CodeMirror.LineWidget = LineWidget
  8272. CodeMirror.e_preventDefault = e_preventDefault
  8273. CodeMirror.e_stopPropagation = e_stopPropagation
  8274. CodeMirror.e_stop = e_stop
  8275. CodeMirror.addClass = addClass
  8276. CodeMirror.contains = contains
  8277. CodeMirror.rmClass = rmClass
  8278. CodeMirror.keyNames = keyNames
  8279. }
  8280. // EDITOR CONSTRUCTOR
  8281. defineOptions(CodeMirror)
  8282. addEditorMethods(CodeMirror)
  8283. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8284. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8285. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8286. { CodeMirror.prototype[prop] = (function(method) {
  8287. return function() {return method.apply(this.doc, arguments)}
  8288. })(Doc.prototype[prop]) } }
  8289. eventMixin(Doc)
  8290. // INPUT HANDLING
  8291. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8292. // MODE DEFINITION AND QUERYING
  8293. // Extra arguments are stored as the mode's dependencies, which is
  8294. // used by (legacy) mechanisms like loadmode.js to automatically
  8295. // load a mode. (Preferred mechanism is the require/define calls.)
  8296. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8297. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8298. defineMode.apply(this, arguments)
  8299. }
  8300. CodeMirror.defineMIME = defineMIME
  8301. // Minimal default mode.
  8302. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8303. CodeMirror.defineMIME("text/plain", "null")
  8304. // EXTENSIONS
  8305. CodeMirror.defineExtension = function (name, func) {
  8306. CodeMirror.prototype[name] = func
  8307. }
  8308. CodeMirror.defineDocExtension = function (name, func) {
  8309. Doc.prototype[name] = func
  8310. }
  8311. CodeMirror.fromTextArea = fromTextArea
  8312. addLegacyProps(CodeMirror)
  8313. CodeMirror.version = "5.24.2"
  8314. return CodeMirror;
  8315. })));