codemirror.js (365757B)
1 // CodeMirror, copyright (c) by Marijn Haverbeke and others 2 // Distributed under an MIT license: http://codemirror.net/LICENSE 3 4 // This is CodeMirror (http://codemirror.net), a code editor 5 // implemented in JavaScript on top of the browser's DOM. 6 // 7 // You can find some technical background for some of the code below 8 // at http://marijnhaverbeke.nl/blog/#cm-internals . 9 10 (function (global, factory) { 11 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 12 typeof define === 'function' && define.amd ? define(factory) : 13 (global.CodeMirror = factory()); 14 }(this, (function () { 'use strict'; 15 16 // Kludges for bugs and behavior differences that can't be feature 17 // detected are enabled based on userAgent etc sniffing. 18 var userAgent = navigator.userAgent; 19 var platform = navigator.platform; 20 21 var gecko = /gecko\/\d/i.test(userAgent); 22 var ie_upto10 = /MSIE \d/.test(userAgent); 23 var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); 24 var edge = /Edge\/(\d+)/.exec(userAgent); 25 var ie = ie_upto10 || ie_11up || edge; 26 var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); 27 var webkit = !edge && /WebKit\//.test(userAgent); 28 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); 29 var chrome = !edge && /Chrome\//.test(userAgent); 30 var presto = /Opera\//.test(userAgent); 31 var safari = /Apple Computer/.test(navigator.vendor); 32 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); 33 var phantom = /PhantomJS/.test(userAgent); 34 35 var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); 36 var android = /Android/.test(userAgent); 37 // This is woefully incomplete. Suggestions for alternative methods welcome. 38 var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); 39 var mac = ios || /Mac/.test(platform); 40 var chromeOS = /\bCrOS\b/.test(userAgent); 41 var windows = /win/i.test(platform); 42 43 var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); 44 if (presto_version) { presto_version = Number(presto_version[1]); } 45 if (presto_version && presto_version >= 15) { presto = false; webkit = true; } 46 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X 47 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); 48 var captureRightClick = gecko || (ie && ie_version >= 9); 49 50 function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } 51 52 var rmClass = function(node, cls) { 53 var current = node.className; 54 var match = classTest(cls).exec(current); 55 if (match) { 56 var after = current.slice(match.index + match[0].length); 57 node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); 58 } 59 }; 60 61 function removeChildren(e) { 62 for (var count = e.childNodes.length; count > 0; --count) 63 { e.removeChild(e.firstChild); } 64 return e 65 } 66 67 function removeChildrenAndAdd(parent, e) { 68 return removeChildren(parent).appendChild(e) 69 } 70 71 function elt(tag, content, className, style) { 72 var e = document.createElement(tag); 73 if (className) { e.className = className; } 74 if (style) { e.style.cssText = style; } 75 if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } 76 else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } 77 return e 78 } 79 // wrapper for elt, which removes the elt from the accessibility tree 80 function eltP(tag, content, className, style) { 81 var e = elt(tag, content, className, style); 82 e.setAttribute("role", "presentation"); 83 return e 84 } 85 86 var range; 87 if (document.createRange) { range = function(node, start, end, endNode) { 88 var r = document.createRange(); 89 r.setEnd(endNode || node, end); 90 r.setStart(node, start); 91 return r 92 }; } 93 else { range = function(node, start, end) { 94 var r = document.body.createTextRange(); 95 try { r.moveToElementText(node.parentNode); } 96 catch(e) { return r } 97 r.collapse(true); 98 r.moveEnd("character", end); 99 r.moveStart("character", start); 100 return r 101 }; } 102 103 function contains(parent, child) { 104 if (child.nodeType == 3) // Android browser always returns false when child is a textnode 105 { child = child.parentNode; } 106 if (parent.contains) 107 { return parent.contains(child) } 108 do { 109 if (child.nodeType == 11) { child = child.host; } 110 if (child == parent) { return true } 111 } while (child = child.parentNode) 112 } 113 114 function activeElt() { 115 // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. 116 // IE < 10 will throw when accessed while the page is loading or in an iframe. 117 // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. 118 var activeElement; 119 try { 120 activeElement = document.activeElement; 121 } catch(e) { 122 activeElement = document.body || null; 123 } 124 while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) 125 { activeElement = activeElement.shadowRoot.activeElement; } 126 return activeElement 127 } 128 129 function addClass(node, cls) { 130 var current = node.className; 131 if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } 132 } 133 function joinClasses(a, b) { 134 var as = a.split(" "); 135 for (var i = 0; i < as.length; i++) 136 { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } 137 return b 138 } 139 140 var selectInput = function(node) { node.select(); }; 141 if (ios) // Mobile Safari apparently has a bug where select() is broken. 142 { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } 143 else if (ie) // Suppress mysterious IE10 errors 144 { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } 145 146 function bind(f) { 147 var args = Array.prototype.slice.call(arguments, 1); 148 return function(){return f.apply(null, args)} 149 } 150 151 function copyObj(obj, target, overwrite) { 152 if (!target) { target = {}; } 153 for (var prop in obj) 154 { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) 155 { target[prop] = obj[prop]; } } 156 return target 157 } 158 159 // Counts the column offset in a string, taking tabs into account. 160 // Used mostly to find indentation. 161 function countColumn(string, end, tabSize, startIndex, startValue) { 162 if (end == null) { 163 end = string.search(/[^\s\u00a0]/); 164 if (end == -1) { end = string.length; } 165 } 166 for (var i = startIndex || 0, n = startValue || 0;;) { 167 var nextTab = string.indexOf("\t", i); 168 if (nextTab < 0 || nextTab >= end) 169 { return n + (end - i) } 170 n += nextTab - i; 171 n += tabSize - (n % tabSize); 172 i = nextTab + 1; 173 } 174 } 175 176 var Delayed = function() {this.id = null;}; 177 Delayed.prototype.set = function (ms, f) { 178 clearTimeout(this.id); 179 this.id = setTimeout(f, ms); 180 }; 181 182 function indexOf(array, elt) { 183 for (var i = 0; i < array.length; ++i) 184 { if (array[i] == elt) { return i } } 185 return -1 186 } 187 188 // Number of pixels added to scroller and sizer to hide scrollbar 189 var scrollerGap = 30; 190 191 // Returned or thrown by various protocols to signal 'I'm not 192 // handling this'. 193 var Pass = {toString: function(){return "CodeMirror.Pass"}}; 194 195 // Reused option objects for setSelection & friends 196 var sel_dontScroll = {scroll: false}; 197 var sel_mouse = {origin: "*mouse"}; 198 var sel_move = {origin: "+move"}; 199 200 // The inverse of countColumn -- find the offset that corresponds to 201 // a particular column. 202 function findColumn(string, goal, tabSize) { 203 for (var pos = 0, col = 0;;) { 204 var nextTab = string.indexOf("\t", pos); 205 if (nextTab == -1) { nextTab = string.length; } 206 var skipped = nextTab - pos; 207 if (nextTab == string.length || col + skipped >= goal) 208 { return pos + Math.min(skipped, goal - col) } 209 col += nextTab - pos; 210 col += tabSize - (col % tabSize); 211 pos = nextTab + 1; 212 if (col >= goal) { return pos } 213 } 214 } 215 216 var spaceStrs = [""]; 217 function spaceStr(n) { 218 while (spaceStrs.length <= n) 219 { spaceStrs.push(lst(spaceStrs) + " "); } 220 return spaceStrs[n] 221 } 222 223 function lst(arr) { return arr[arr.length-1] } 224 225 function map(array, f) { 226 var out = []; 227 for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } 228 return out 229 } 230 231 function insertSorted(array, value, score) { 232 var pos = 0, priority = score(value); 233 while (pos < array.length && score(array[pos]) <= priority) { pos++; } 234 array.splice(pos, 0, value); 235 } 236 237 function nothing() {} 238 239 function createObj(base, props) { 240 var inst; 241 if (Object.create) { 242 inst = Object.create(base); 243 } else { 244 nothing.prototype = base; 245 inst = new nothing(); 246 } 247 if (props) { copyObj(props, inst); } 248 return inst 249 } 250 251 var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; 252 function isWordCharBasic(ch) { 253 return /\w/.test(ch) || ch > "\x80" && 254 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) 255 } 256 function isWordChar(ch, helper) { 257 if (!helper) { return isWordCharBasic(ch) } 258 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } 259 return helper.test(ch) 260 } 261 262 function isEmpty(obj) { 263 for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } 264 return true 265 } 266 267 // Extending unicode characters. A series of a non-extending char + 268 // any number of extending chars is treated as a single unit as far 269 // as editing and measuring is concerned. This is not fully correct, 270 // since some scripts/fonts/browsers also treat other configurations 271 // of code points as a group. 272 var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; 273 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } 274 275 // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. 276 function skipExtendingChars(str, pos, dir) { 277 while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } 278 return pos 279 } 280 281 // Returns the value from the range [`from`; `to`] that satisfies 282 // `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`. 283 function findFirst(pred, from, to) { 284 for (;;) { 285 if (Math.abs(from - to) <= 1) { return pred(from) ? from : to } 286 var mid = Math.floor((from + to) / 2); 287 if (pred(mid)) { to = mid; } 288 else { from = mid; } 289 } 290 } 291 292 // The display handles the DOM integration, both for input reading 293 // and content drawing. It holds references to DOM nodes and 294 // display-related state. 295 296 function Display(place, doc, input) { 297 var d = this; 298 this.input = input; 299 300 // Covers bottom-right square when both scrollbars are present. 301 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); 302 d.scrollbarFiller.setAttribute("cm-not-content", "true"); 303 // Covers bottom of gutter when coverGutterNextToScrollbar is on 304 // and h scrollbar is present. 305 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); 306 d.gutterFiller.setAttribute("cm-not-content", "true"); 307 // Will contain the actual code, positioned to cover the viewport. 308 d.lineDiv = eltP("div", null, "CodeMirror-code"); 309 // Elements are added to these to represent selection and cursors. 310 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); 311 d.cursorDiv = elt("div", null, "CodeMirror-cursors"); 312 // A visibility: hidden element used to find the size of things. 313 d.measure = elt("div", null, "CodeMirror-measure"); 314 // When lines outside of the viewport are measured, they are drawn in this. 315 d.lineMeasure = elt("div", null, "CodeMirror-measure"); 316 // Wraps everything that needs to exist inside the vertically-padded coordinate system 317 d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], 318 null, "position: relative; outline: none"); 319 var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); 320 // Moved around its parent to cover visible view. 321 d.mover = elt("div", [lines], null, "position: relative"); 322 // Set to the height of the document, allowing scrolling. 323 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); 324 d.sizerWidth = null; 325 // Behavior of elts with overflow: auto and padding is 326 // inconsistent across browsers. This is used to ensure the 327 // scrollable area is big enough. 328 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); 329 // Will contain the gutters, if any. 330 d.gutters = elt("div", null, "CodeMirror-gutters"); 331 d.lineGutter = null; 332 // Actual scrollable element. 333 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); 334 d.scroller.setAttribute("tabIndex", "-1"); 335 // The element in which the editor lives. 336 d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); 337 338 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) 339 if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } 340 if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } 341 342 if (place) { 343 if (place.appendChild) { place.appendChild(d.wrapper); } 344 else { place(d.wrapper); } 345 } 346 347 // Current rendered range (may be bigger than the view window). 348 d.viewFrom = d.viewTo = doc.first; 349 d.reportedViewFrom = d.reportedViewTo = doc.first; 350 // Information about the rendered lines. 351 d.view = []; 352 d.renderedView = null; 353 // Holds info about a single rendered line when it was rendered 354 // for measurement, while not in view. 355 d.externalMeasured = null; 356 // Empty space (in pixels) above the view 357 d.viewOffset = 0; 358 d.lastWrapHeight = d.lastWrapWidth = 0; 359 d.updateLineNumbers = null; 360 361 d.nativeBarWidth = d.barHeight = d.barWidth = 0; 362 d.scrollbarsClipped = false; 363 364 // Used to only resize the line number gutter when necessary (when 365 // the amount of lines crosses a boundary that makes its width change) 366 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; 367 // Set to true when a non-horizontal-scrolling line widget is 368 // added. As an optimization, line widget aligning is skipped when 369 // this is false. 370 d.alignWidgets = false; 371 372 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 373 374 // Tracks the maximum line length so that the horizontal scrollbar 375 // can be kept static when scrolling. 376 d.maxLine = null; 377 d.maxLineLength = 0; 378 d.maxLineChanged = false; 379 380 // Used for measuring wheel scrolling granularity 381 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; 382 383 // True when shift is held down. 384 d.shift = false; 385 386 // Used to track whether anything happened since the context menu 387 // was opened. 388 d.selForContextMenu = null; 389 390 d.activeTouch = null; 391 392 input.init(d); 393 } 394 395 // Find the line object corresponding to the given line number. 396 function getLine(doc, n) { 397 n -= doc.first; 398 if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } 399 var chunk = doc; 400 while (!chunk.lines) { 401 for (var i = 0;; ++i) { 402 var child = chunk.children[i], sz = child.chunkSize(); 403 if (n < sz) { chunk = child; break } 404 n -= sz; 405 } 406 } 407 return chunk.lines[n] 408 } 409 410 // Get the part of a document between two positions, as an array of 411 // strings. 412 function getBetween(doc, start, end) { 413 var out = [], n = start.line; 414 doc.iter(start.line, end.line + 1, function (line) { 415 var text = line.text; 416 if (n == end.line) { text = text.slice(0, end.ch); } 417 if (n == start.line) { text = text.slice(start.ch); } 418 out.push(text); 419 ++n; 420 }); 421 return out 422 } 423 // Get the lines between from and to, as array of strings. 424 function getLines(doc, from, to) { 425 var out = []; 426 doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value 427 return out 428 } 429 430 // Update the height of a line, propagating the height change 431 // upwards to parent nodes. 432 function updateLineHeight(line, height) { 433 var diff = height - line.height; 434 if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } 435 } 436 437 // Given a line object, find its line number by walking up through 438 // its parent links. 439 function lineNo(line) { 440 if (line.parent == null) { return null } 441 var cur = line.parent, no = indexOf(cur.lines, line); 442 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 443 for (var i = 0;; ++i) { 444 if (chunk.children[i] == cur) { break } 445 no += chunk.children[i].chunkSize(); 446 } 447 } 448 return no + cur.first 449 } 450 451 // Find the line at the given vertical position, using the height 452 // information in the document tree. 453 function lineAtHeight(chunk, h) { 454 var n = chunk.first; 455 outer: do { 456 for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { 457 var child = chunk.children[i$1], ch = child.height; 458 if (h < ch) { chunk = child; continue outer } 459 h -= ch; 460 n += child.chunkSize(); 461 } 462 return n 463 } while (!chunk.lines) 464 var i = 0; 465 for (; i < chunk.lines.length; ++i) { 466 var line = chunk.lines[i], lh = line.height; 467 if (h < lh) { break } 468 h -= lh; 469 } 470 return n + i 471 } 472 473 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} 474 475 function lineNumberFor(options, i) { 476 return String(options.lineNumberFormatter(i + options.firstLineNumber)) 477 } 478 479 // A Pos instance represents a position within the text. 480 function Pos(line, ch, sticky) { 481 if ( sticky === void 0 ) sticky = null; 482 483 if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } 484 this.line = line; 485 this.ch = ch; 486 this.sticky = sticky; 487 } 488 489 // Compare two positions, return 0 if they are the same, a negative 490 // number when a is less, and a positive number otherwise. 491 function cmp(a, b) { return a.line - b.line || a.ch - b.ch } 492 493 function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } 494 495 function copyPos(x) {return Pos(x.line, x.ch)} 496 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } 497 function minPos(a, b) { return cmp(a, b) < 0 ? a : b } 498 499 // Most of the external API clips given positions to make sure they 500 // actually exist within the document. 501 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} 502 function clipPos(doc, pos) { 503 if (pos.line < doc.first) { return Pos(doc.first, 0) } 504 var last = doc.first + doc.size - 1; 505 if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } 506 return clipToLen(pos, getLine(doc, pos.line).text.length) 507 } 508 function clipToLen(pos, linelen) { 509 var ch = pos.ch; 510 if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } 511 else if (ch < 0) { return Pos(pos.line, 0) } 512 else { return pos } 513 } 514 function clipPosArray(doc, array) { 515 var out = []; 516 for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } 517 return out 518 } 519 520 // Optimize some code when these features are not used. 521 var sawReadOnlySpans = false; 522 var sawCollapsedSpans = false; 523 524 function seeReadOnlySpans() { 525 sawReadOnlySpans = true; 526 } 527 528 function seeCollapsedSpans() { 529 sawCollapsedSpans = true; 530 } 531 532 // TEXTMARKER SPANS 533 534 function MarkedSpan(marker, from, to) { 535 this.marker = marker; 536 this.from = from; this.to = to; 537 } 538 539 // Search an array of spans for a span matching the given marker. 540 function getMarkedSpanFor(spans, marker) { 541 if (spans) { for (var i = 0; i < spans.length; ++i) { 542 var span = spans[i]; 543 if (span.marker == marker) { return span } 544 } } 545 } 546 // Remove a span from an array, returning undefined if no spans are 547 // left (we don't store arrays for lines without spans). 548 function removeMarkedSpan(spans, span) { 549 var r; 550 for (var i = 0; i < spans.length; ++i) 551 { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } 552 return r 553 } 554 // Add a span to a line. 555 function addMarkedSpan(line, span) { 556 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 557 span.marker.attachLine(line); 558 } 559 560 // Used for the algorithm that adjusts markers for a change in the 561 // document. These functions cut an array of spans at a given 562 // character position, returning an array of remaining chunks (or 563 // undefined if nothing remains). 564 function markedSpansBefore(old, startCh, isInsert) { 565 var nw; 566 if (old) { for (var i = 0; i < old.length; ++i) { 567 var span = old[i], marker = span.marker; 568 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 569 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { 570 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); 571 } 572 } } 573 return nw 574 } 575 function markedSpansAfter(old, endCh, isInsert) { 576 var nw; 577 if (old) { for (var i = 0; i < old.length; ++i) { 578 var span = old[i], marker = span.marker; 579 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 580 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { 581 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, 582 span.to == null ? null : span.to - endCh)); 583 } 584 } } 585 return nw 586 } 587 588 // Given a change object, compute the new set of marker spans that 589 // cover the line in which the change took place. Removes spans 590 // entirely within the change, reconnects spans belonging to the 591 // same marker that appear on both sides of the change, and cuts off 592 // spans partially within the change. Returns an array of span 593 // arrays with one element for each line in (after) the change. 594 function stretchSpansOverChange(doc, change) { 595 if (change.full) { return null } 596 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 597 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 598 if (!oldFirst && !oldLast) { return null } 599 600 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; 601 // Get the spans that 'stick out' on both sides 602 var first = markedSpansBefore(oldFirst, startCh, isInsert); 603 var last = markedSpansAfter(oldLast, endCh, isInsert); 604 605 // Next, merge those two ends 606 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 607 if (first) { 608 // Fix up .to properties of first 609 for (var i = 0; i < first.length; ++i) { 610 var span = first[i]; 611 if (span.to == null) { 612 var found = getMarkedSpanFor(last, span.marker); 613 if (!found) { span.to = startCh; } 614 else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } 615 } 616 } 617 } 618 if (last) { 619 // Fix up .from in last (or move them into first in case of sameLine) 620 for (var i$1 = 0; i$1 < last.length; ++i$1) { 621 var span$1 = last[i$1]; 622 if (span$1.to != null) { span$1.to += offset; } 623 if (span$1.from == null) { 624 var found$1 = getMarkedSpanFor(first, span$1.marker); 625 if (!found$1) { 626 span$1.from = offset; 627 if (sameLine) { (first || (first = [])).push(span$1); } 628 } 629 } else { 630 span$1.from += offset; 631 if (sameLine) { (first || (first = [])).push(span$1); } 632 } 633 } 634 } 635 // Make sure we didn't create any zero-length spans 636 if (first) { first = clearEmptySpans(first); } 637 if (last && last != first) { last = clearEmptySpans(last); } 638 639 var newMarkers = [first]; 640 if (!sameLine) { 641 // Fill gap with whole-line-spans 642 var gap = change.text.length - 2, gapMarkers; 643 if (gap > 0 && first) 644 { for (var i$2 = 0; i$2 < first.length; ++i$2) 645 { if (first[i$2].to == null) 646 { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } 647 for (var i$3 = 0; i$3 < gap; ++i$3) 648 { newMarkers.push(gapMarkers); } 649 newMarkers.push(last); 650 } 651 return newMarkers 652 } 653 654 // Remove spans that are empty and don't have a clearWhenEmpty 655 // option of false. 656 function clearEmptySpans(spans) { 657 for (var i = 0; i < spans.length; ++i) { 658 var span = spans[i]; 659 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) 660 { spans.splice(i--, 1); } 661 } 662 if (!spans.length) { return null } 663 return spans 664 } 665 666 // Used to 'clip' out readOnly ranges when making a change. 667 function removeReadOnlyRanges(doc, from, to) { 668 var markers = null; 669 doc.iter(from.line, to.line + 1, function (line) { 670 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 671 var mark = line.markedSpans[i].marker; 672 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 673 { (markers || (markers = [])).push(mark); } 674 } } 675 }); 676 if (!markers) { return null } 677 var parts = [{from: from, to: to}]; 678 for (var i = 0; i < markers.length; ++i) { 679 var mk = markers[i], m = mk.find(0); 680 for (var j = 0; j < parts.length; ++j) { 681 var p = parts[j]; 682 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } 683 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); 684 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) 685 { newParts.push({from: p.from, to: m.from}); } 686 if (dto > 0 || !mk.inclusiveRight && !dto) 687 { newParts.push({from: m.to, to: p.to}); } 688 parts.splice.apply(parts, newParts); 689 j += newParts.length - 3; 690 } 691 } 692 return parts 693 } 694 695 // Connect or disconnect spans from a line. 696 function detachMarkedSpans(line) { 697 var spans = line.markedSpans; 698 if (!spans) { return } 699 for (var i = 0; i < spans.length; ++i) 700 { spans[i].marker.detachLine(line); } 701 line.markedSpans = null; 702 } 703 function attachMarkedSpans(line, spans) { 704 if (!spans) { return } 705 for (var i = 0; i < spans.length; ++i) 706 { spans[i].marker.attachLine(line); } 707 line.markedSpans = spans; 708 } 709 710 // Helpers used when computing which overlapping collapsed span 711 // counts as the larger one. 712 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } 713 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } 714 715 // Returns a number indicating which of two overlapping collapsed 716 // spans is larger (and thus includes the other). Falls back to 717 // comparing ids when the spans cover exactly the same range. 718 function compareCollapsedMarkers(a, b) { 719 var lenDiff = a.lines.length - b.lines.length; 720 if (lenDiff != 0) { return lenDiff } 721 var aPos = a.find(), bPos = b.find(); 722 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); 723 if (fromCmp) { return -fromCmp } 724 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); 725 if (toCmp) { return toCmp } 726 return b.id - a.id 727 } 728 729 // Find out whether a line ends or starts in a collapsed span. If 730 // so, return the marker for that span. 731 function collapsedSpanAtSide(line, start) { 732 var sps = sawCollapsedSpans && line.markedSpans, found; 733 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 734 sp = sps[i]; 735 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && 736 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) 737 { found = sp.marker; } 738 } } 739 return found 740 } 741 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } 742 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } 743 744 // Test whether there exists a collapsed span that partially 745 // overlaps (covers the start or end, but not both) of a new span. 746 // Such overlap is not allowed. 747 function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { 748 var line = getLine(doc, lineNo$$1); 749 var sps = sawCollapsedSpans && line.markedSpans; 750 if (sps) { for (var i = 0; i < sps.length; ++i) { 751 var sp = sps[i]; 752 if (!sp.marker.collapsed) { continue } 753 var found = sp.marker.find(0); 754 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); 755 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); 756 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } 757 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || 758 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) 759 { return true } 760 } } 761 } 762 763 // A visual line is a line as drawn on the screen. Folding, for 764 // example, can cause multiple logical lines to appear on the same 765 // visual line. This finds the start of the visual line that the 766 // given line is part of (usually that is the line itself). 767 function visualLine(line) { 768 var merged; 769 while (merged = collapsedSpanAtStart(line)) 770 { line = merged.find(-1, true).line; } 771 return line 772 } 773 774 function visualLineEnd(line) { 775 var merged; 776 while (merged = collapsedSpanAtEnd(line)) 777 { line = merged.find(1, true).line; } 778 return line 779 } 780 781 // Returns an array of logical lines that continue the visual line 782 // started by the argument, or undefined if there are no such lines. 783 function visualLineContinued(line) { 784 var merged, lines; 785 while (merged = collapsedSpanAtEnd(line)) { 786 line = merged.find(1, true).line 787 ;(lines || (lines = [])).push(line); 788 } 789 return lines 790 } 791 792 // Get the line number of the start of the visual line that the 793 // given line number is part of. 794 function visualLineNo(doc, lineN) { 795 var line = getLine(doc, lineN), vis = visualLine(line); 796 if (line == vis) { return lineN } 797 return lineNo(vis) 798 } 799 800 // Get the line number of the start of the next visual line after 801 // the given line. 802 function visualLineEndNo(doc, lineN) { 803 if (lineN > doc.lastLine()) { return lineN } 804 var line = getLine(doc, lineN), merged; 805 if (!lineIsHidden(doc, line)) { return lineN } 806 while (merged = collapsedSpanAtEnd(line)) 807 { line = merged.find(1, true).line; } 808 return lineNo(line) + 1 809 } 810 811 // Compute whether a line is hidden. Lines count as hidden when they 812 // are part of a visual line that starts with another line, or when 813 // they are entirely covered by collapsed, non-widget span. 814 function lineIsHidden(doc, line) { 815 var sps = sawCollapsedSpans && line.markedSpans; 816 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 817 sp = sps[i]; 818 if (!sp.marker.collapsed) { continue } 819 if (sp.from == null) { return true } 820 if (sp.marker.widgetNode) { continue } 821 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 822 { return true } 823 } } 824 } 825 function lineIsHiddenInner(doc, line, span) { 826 if (span.to == null) { 827 var end = span.marker.find(1, true); 828 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) 829 } 830 if (span.marker.inclusiveRight && span.to == line.text.length) 831 { return true } 832 for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { 833 sp = line.markedSpans[i]; 834 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && 835 (sp.to == null || sp.to != span.from) && 836 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 837 lineIsHiddenInner(doc, line, sp)) { return true } 838 } 839 } 840 841 // Find the height above the given line. 842 function heightAtLine(lineObj) { 843 lineObj = visualLine(lineObj); 844 845 var h = 0, chunk = lineObj.parent; 846 for (var i = 0; i < chunk.lines.length; ++i) { 847 var line = chunk.lines[i]; 848 if (line == lineObj) { break } 849 else { h += line.height; } 850 } 851 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 852 for (var i$1 = 0; i$1 < p.children.length; ++i$1) { 853 var cur = p.children[i$1]; 854 if (cur == chunk) { break } 855 else { h += cur.height; } 856 } 857 } 858 return h 859 } 860 861 // Compute the character length of a line, taking into account 862 // collapsed ranges (see markText) that might hide parts, and join 863 // other lines onto it. 864 function lineLength(line) { 865 if (line.height == 0) { return 0 } 866 var len = line.text.length, merged, cur = line; 867 while (merged = collapsedSpanAtStart(cur)) { 868 var found = merged.find(0, true); 869 cur = found.from.line; 870 len += found.from.ch - found.to.ch; 871 } 872 cur = line; 873 while (merged = collapsedSpanAtEnd(cur)) { 874 var found$1 = merged.find(0, true); 875 len -= cur.text.length - found$1.from.ch; 876 cur = found$1.to.line; 877 len += cur.text.length - found$1.to.ch; 878 } 879 return len 880 } 881 882 // Find the longest line in the document. 883 function findMaxLine(cm) { 884 var d = cm.display, doc = cm.doc; 885 d.maxLine = getLine(doc, doc.first); 886 d.maxLineLength = lineLength(d.maxLine); 887 d.maxLineChanged = true; 888 doc.iter(function (line) { 889 var len = lineLength(line); 890 if (len > d.maxLineLength) { 891 d.maxLineLength = len; 892 d.maxLine = line; 893 } 894 }); 895 } 896 897 // BIDI HELPERS 898 899 function iterateBidiSections(order, from, to, f) { 900 if (!order) { return f(from, to, "ltr") } 901 var found = false; 902 for (var i = 0; i < order.length; ++i) { 903 var part = order[i]; 904 if (part.from < to && part.to > from || from == to && part.to == from) { 905 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); 906 found = true; 907 } 908 } 909 if (!found) { f(from, to, "ltr"); } 910 } 911 912 var bidiOther = null; 913 function getBidiPartAt(order, ch, sticky) { 914 var found; 915 bidiOther = null; 916 for (var i = 0; i < order.length; ++i) { 917 var cur = order[i]; 918 if (cur.from < ch && cur.to > ch) { return i } 919 if (cur.to == ch) { 920 if (cur.from != cur.to && sticky == "before") { found = i; } 921 else { bidiOther = i; } 922 } 923 if (cur.from == ch) { 924 if (cur.from != cur.to && sticky != "before") { found = i; } 925 else { bidiOther = i; } 926 } 927 } 928 return found != null ? found : bidiOther 929 } 930 931 // Bidirectional ordering algorithm 932 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 933 // that this (partially) implements. 934 935 // One-char codes used for character types: 936 // L (L): Left-to-Right 937 // R (R): Right-to-Left 938 // r (AL): Right-to-Left Arabic 939 // 1 (EN): European Number 940 // + (ES): European Number Separator 941 // % (ET): European Number Terminator 942 // n (AN): Arabic Number 943 // , (CS): Common Number Separator 944 // m (NSM): Non-Spacing Mark 945 // b (BN): Boundary Neutral 946 // s (B): Paragraph Separator 947 // t (S): Segment Separator 948 // w (WS): Whitespace 949 // N (ON): Other Neutrals 950 951 // Returns null if characters are ordered as they appear 952 // (left-to-right), or an array of sections ({from, to, level} 953 // objects) in the order in which they occur visually. 954 var bidiOrdering = (function() { 955 // Character types for codepoints 0 to 0xff 956 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; 957 // Character types for codepoints 0x600 to 0x6f9 958 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; 959 function charType(code) { 960 if (code <= 0xf7) { return lowTypes.charAt(code) } 961 else if (0x590 <= code && code <= 0x5f4) { return "R" } 962 else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } 963 else if (0x6ee <= code && code <= 0x8ac) { return "r" } 964 else if (0x2000 <= code && code <= 0x200b) { return "w" } 965 else if (code == 0x200c) { return "b" } 966 else { return "L" } 967 } 968 969 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 970 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 971 972 function BidiSpan(level, from, to) { 973 this.level = level; 974 this.from = from; this.to = to; 975 } 976 977 return function(str, direction) { 978 var outerType = direction == "ltr" ? "L" : "R"; 979 980 if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } 981 var len = str.length, types = []; 982 for (var i = 0; i < len; ++i) 983 { types.push(charType(str.charCodeAt(i))); } 984 985 // W1. Examine each non-spacing mark (NSM) in the level run, and 986 // change the type of the NSM to the type of the previous 987 // character. If the NSM is at the start of the level run, it will 988 // get the type of sor. 989 for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { 990 var type = types[i$1]; 991 if (type == "m") { types[i$1] = prev; } 992 else { prev = type; } 993 } 994 995 // W2. Search backwards from each instance of a European number 996 // until the first strong type (R, L, AL, or sor) is found. If an 997 // AL is found, change the type of the European number to Arabic 998 // number. 999 // W3. Change all ALs to R. 1000 for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { 1001 var type$1 = types[i$2]; 1002 if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } 1003 else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } 1004 } 1005 1006 // W4. A single European separator between two European numbers 1007 // changes to a European number. A single common separator between 1008 // two numbers of the same type changes to that type. 1009 for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { 1010 var type$2 = types[i$3]; 1011 if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } 1012 else if (type$2 == "," && prev$1 == types[i$3+1] && 1013 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } 1014 prev$1 = type$2; 1015 } 1016 1017 // W5. A sequence of European terminators adjacent to European 1018 // numbers changes to all European numbers. 1019 // W6. Otherwise, separators and terminators change to Other 1020 // Neutral. 1021 for (var i$4 = 0; i$4 < len; ++i$4) { 1022 var type$3 = types[i$4]; 1023 if (type$3 == ",") { types[i$4] = "N"; } 1024 else if (type$3 == "%") { 1025 var end = (void 0); 1026 for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} 1027 var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; 1028 for (var j = i$4; j < end; ++j) { types[j] = replace; } 1029 i$4 = end - 1; 1030 } 1031 } 1032 1033 // W7. Search backwards from each instance of a European number 1034 // until the first strong type (R, L, or sor) is found. If an L is 1035 // found, then change the type of the European number to L. 1036 for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { 1037 var type$4 = types[i$5]; 1038 if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } 1039 else if (isStrong.test(type$4)) { cur$1 = type$4; } 1040 } 1041 1042 // N1. A sequence of neutrals takes the direction of the 1043 // surrounding strong text if the text on both sides has the same 1044 // direction. European and Arabic numbers act as if they were R in 1045 // terms of their influence on neutrals. Start-of-level-run (sor) 1046 // and end-of-level-run (eor) are used at level run boundaries. 1047 // N2. Any remaining neutrals take the embedding direction. 1048 for (var i$6 = 0; i$6 < len; ++i$6) { 1049 if (isNeutral.test(types[i$6])) { 1050 var end$1 = (void 0); 1051 for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} 1052 var before = (i$6 ? types[i$6-1] : outerType) == "L"; 1053 var after = (end$1 < len ? types[end$1] : outerType) == "L"; 1054 var replace$1 = before == after ? (before ? "L" : "R") : outerType; 1055 for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } 1056 i$6 = end$1 - 1; 1057 } 1058 } 1059 1060 // Here we depart from the documented algorithm, in order to avoid 1061 // building up an actual levels array. Since there are only three 1062 // levels (0, 1, 2) in an implementation that doesn't take 1063 // explicit embedding into account, we can build up the order on 1064 // the fly, without following the level-based algorithm. 1065 var order = [], m; 1066 for (var i$7 = 0; i$7 < len;) { 1067 if (countsAsLeft.test(types[i$7])) { 1068 var start = i$7; 1069 for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} 1070 order.push(new BidiSpan(0, start, i$7)); 1071 } else { 1072 var pos = i$7, at = order.length; 1073 for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} 1074 for (var j$2 = pos; j$2 < i$7;) { 1075 if (countsAsNum.test(types[j$2])) { 1076 if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } 1077 var nstart = j$2; 1078 for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} 1079 order.splice(at, 0, new BidiSpan(2, nstart, j$2)); 1080 pos = j$2; 1081 } else { ++j$2; } 1082 } 1083 if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } 1084 } 1085 } 1086 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 1087 order[0].from = m[0].length; 1088 order.unshift(new BidiSpan(0, 0, m[0].length)); 1089 } 1090 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 1091 lst(order).to -= m[0].length; 1092 order.push(new BidiSpan(0, len - m[0].length, len)); 1093 } 1094 1095 return direction == "rtl" ? order.reverse() : order 1096 } 1097 })(); 1098 1099 // Get the bidi ordering for the given line (and cache it). Returns 1100 // false for lines that are fully left-to-right, and an array of 1101 // BidiSpan objects otherwise. 1102 function getOrder(line, direction) { 1103 var order = line.order; 1104 if (order == null) { order = line.order = bidiOrdering(line.text, direction); } 1105 return order 1106 } 1107 1108 function moveCharLogically(line, ch, dir) { 1109 var target = skipExtendingChars(line.text, ch + dir, dir); 1110 return target < 0 || target > line.text.length ? null : target 1111 } 1112 1113 function moveLogically(line, start, dir) { 1114 var ch = moveCharLogically(line, start.ch, dir); 1115 return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") 1116 } 1117 1118 function endOfLine(visually, cm, lineObj, lineNo, dir) { 1119 if (visually) { 1120 var order = getOrder(lineObj, cm.doc.direction); 1121 if (order) { 1122 var part = dir < 0 ? lst(order) : order[0]; 1123 var moveInStorageOrder = (dir < 0) == (part.level == 1); 1124 var sticky = moveInStorageOrder ? "after" : "before"; 1125 var ch; 1126 // With a wrapped rtl chunk (possibly spanning multiple bidi parts), 1127 // it could be that the last bidi part is not on the last visual line, 1128 // since visual lines contain content order-consecutive chunks. 1129 // Thus, in rtl, we are looking for the first (content-order) character 1130 // in the rtl chunk that is on the last line (that is, the same line 1131 // as the last (content-order) character). 1132 if (part.level > 0) { 1133 var prep = prepareMeasureForLine(cm, lineObj); 1134 ch = dir < 0 ? lineObj.text.length - 1 : 0; 1135 var targetTop = measureCharPrepared(cm, prep, ch).top; 1136 ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); 1137 if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } 1138 } else { ch = dir < 0 ? part.to : part.from; } 1139 return new Pos(lineNo, ch, sticky) 1140 } 1141 } 1142 return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") 1143 } 1144 1145 function moveVisually(cm, line, start, dir) { 1146 var bidi = getOrder(line, cm.doc.direction); 1147 if (!bidi) { return moveLogically(line, start, dir) } 1148 if (start.ch >= line.text.length) { 1149 start.ch = line.text.length; 1150 start.sticky = "before"; 1151 } else if (start.ch <= 0) { 1152 start.ch = 0; 1153 start.sticky = "after"; 1154 } 1155 var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; 1156 if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { 1157 // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, 1158 // nothing interesting happens. 1159 return moveLogically(line, start, dir) 1160 } 1161 1162 var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; 1163 var prep; 1164 var getWrappedLineExtent = function (ch) { 1165 if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } 1166 prep = prep || prepareMeasureForLine(cm, line); 1167 return wrappedLineExtentChar(cm, line, prep, ch) 1168 }; 1169 var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); 1170 1171 if (cm.doc.direction == "rtl" || part.level == 1) { 1172 var moveInStorageOrder = (part.level == 1) == (dir < 0); 1173 var ch = mv(start, moveInStorageOrder ? 1 : -1); 1174 if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { 1175 // Case 2: We move within an rtl part or in an rtl editor on the same visual line 1176 var sticky = moveInStorageOrder ? "before" : "after"; 1177 return new Pos(start.line, ch, sticky) 1178 } 1179 } 1180 1181 // Case 3: Could not move within this bidi part in this visual line, so leave 1182 // the current bidi part 1183 1184 var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { 1185 var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder 1186 ? new Pos(start.line, mv(ch, 1), "before") 1187 : new Pos(start.line, ch, "after"); }; 1188 1189 for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { 1190 var part = bidi[partPos]; 1191 var moveInStorageOrder = (dir > 0) == (part.level != 1); 1192 var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); 1193 if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } 1194 ch = moveInStorageOrder ? part.from : mv(part.to, -1); 1195 if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } 1196 } 1197 }; 1198 1199 // Case 3a: Look for other bidi parts on the same visual line 1200 var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); 1201 if (res) { return res } 1202 1203 // Case 3b: Look for other bidi parts on the next visual line 1204 var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); 1205 if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { 1206 res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); 1207 if (res) { return res } 1208 } 1209 1210 // Case 4: Nowhere to move 1211 return null 1212 } 1213 1214 // EVENT HANDLING 1215 1216 // Lightweight event framework. on/off also work on DOM nodes, 1217 // registering native DOM handlers. 1218 1219 var noHandlers = []; 1220 1221 var on = function(emitter, type, f) { 1222 if (emitter.addEventListener) { 1223 emitter.addEventListener(type, f, false); 1224 } else if (emitter.attachEvent) { 1225 emitter.attachEvent("on" + type, f); 1226 } else { 1227 var map$$1 = emitter._handlers || (emitter._handlers = {}); 1228 map$$1[type] = (map$$1[type] || noHandlers).concat(f); 1229 } 1230 }; 1231 1232 function getHandlers(emitter, type) { 1233 return emitter._handlers && emitter._handlers[type] || noHandlers 1234 } 1235 1236 function off(emitter, type, f) { 1237 if (emitter.removeEventListener) { 1238 emitter.removeEventListener(type, f, false); 1239 } else if (emitter.detachEvent) { 1240 emitter.detachEvent("on" + type, f); 1241 } else { 1242 var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; 1243 if (arr) { 1244 var index = indexOf(arr, f); 1245 if (index > -1) 1246 { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } 1247 } 1248 } 1249 } 1250 1251 function signal(emitter, type /*, values...*/) { 1252 var handlers = getHandlers(emitter, type); 1253 if (!handlers.length) { return } 1254 var args = Array.prototype.slice.call(arguments, 2); 1255 for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } 1256 } 1257 1258 // The DOM events that CodeMirror handles can be overridden by 1259 // registering a (non-DOM) handler on the editor for the event name, 1260 // and preventDefault-ing the event in that handler. 1261 function signalDOMEvent(cm, e, override) { 1262 if (typeof e == "string") 1263 { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } 1264 signal(cm, override || e.type, cm, e); 1265 return e_defaultPrevented(e) || e.codemirrorIgnore 1266 } 1267 1268 function signalCursorActivity(cm) { 1269 var arr = cm._handlers && cm._handlers.cursorActivity; 1270 if (!arr) { return } 1271 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); 1272 for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) 1273 { set.push(arr[i]); } } 1274 } 1275 1276 function hasHandler(emitter, type) { 1277 return getHandlers(emitter, type).length > 0 1278 } 1279 1280 // Add on and off methods to a constructor's prototype, to make 1281 // registering events on such objects more convenient. 1282 function eventMixin(ctor) { 1283 ctor.prototype.on = function(type, f) {on(this, type, f);}; 1284 ctor.prototype.off = function(type, f) {off(this, type, f);}; 1285 } 1286 1287 // Due to the fact that we still support jurassic IE versions, some 1288 // compatibility wrappers are needed. 1289 1290 function e_preventDefault(e) { 1291 if (e.preventDefault) { e.preventDefault(); } 1292 else { e.returnValue = false; } 1293 } 1294 function e_stopPropagation(e) { 1295 if (e.stopPropagation) { e.stopPropagation(); } 1296 else { e.cancelBubble = true; } 1297 } 1298 function e_defaultPrevented(e) { 1299 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false 1300 } 1301 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} 1302 1303 function e_target(e) {return e.target || e.srcElement} 1304 function e_button(e) { 1305 var b = e.which; 1306 if (b == null) { 1307 if (e.button & 1) { b = 1; } 1308 else if (e.button & 2) { b = 3; } 1309 else if (e.button & 4) { b = 2; } 1310 } 1311 if (mac && e.ctrlKey && b == 1) { b = 3; } 1312 return b 1313 } 1314 1315 // Detect drag-and-drop 1316 var dragAndDrop = function() { 1317 // There is *some* kind of drag-and-drop support in IE6-8, but I 1318 // couldn't get it to work yet. 1319 if (ie && ie_version < 9) { return false } 1320 var div = elt('div'); 1321 return "draggable" in div || "dragDrop" in div 1322 }(); 1323 1324 var zwspSupported; 1325 function zeroWidthElement(measure) { 1326 if (zwspSupported == null) { 1327 var test = elt("span", "\u200b"); 1328 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 1329 if (measure.firstChild.offsetHeight != 0) 1330 { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } 1331 } 1332 var node = zwspSupported ? elt("span", "\u200b") : 1333 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 1334 node.setAttribute("cm-text", ""); 1335 return node 1336 } 1337 1338 // Feature-detect IE's crummy client rect reporting for bidi text 1339 var badBidiRects; 1340 function hasBadBidiRects(measure) { 1341 if (badBidiRects != null) { return badBidiRects } 1342 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); 1343 var r0 = range(txt, 0, 1).getBoundingClientRect(); 1344 var r1 = range(txt, 1, 2).getBoundingClientRect(); 1345 removeChildren(measure); 1346 if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) 1347 return badBidiRects = (r1.right - r0.right < 3) 1348 } 1349 1350 // See if "".split is the broken IE version, if so, provide an 1351 // alternative way to split lines. 1352 var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { 1353 var pos = 0, result = [], l = string.length; 1354 while (pos <= l) { 1355 var nl = string.indexOf("\n", pos); 1356 if (nl == -1) { nl = string.length; } 1357 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 1358 var rt = line.indexOf("\r"); 1359 if (rt != -1) { 1360 result.push(line.slice(0, rt)); 1361 pos += rt + 1; 1362 } else { 1363 result.push(line); 1364 pos = nl + 1; 1365 } 1366 } 1367 return result 1368 } : function (string) { return string.split(/\r\n?|\n/); }; 1369 1370 var hasSelection = window.getSelection ? function (te) { 1371 try { return te.selectionStart != te.selectionEnd } 1372 catch(e) { return false } 1373 } : function (te) { 1374 var range$$1; 1375 try {range$$1 = te.ownerDocument.selection.createRange();} 1376 catch(e) {} 1377 if (!range$$1 || range$$1.parentElement() != te) { return false } 1378 return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 1379 }; 1380 1381 var hasCopyEvent = (function () { 1382 var e = elt("div"); 1383 if ("oncopy" in e) { return true } 1384 e.setAttribute("oncopy", "return;"); 1385 return typeof e.oncopy == "function" 1386 })(); 1387 1388 var badZoomedRects = null; 1389 function hasBadZoomedRects(measure) { 1390 if (badZoomedRects != null) { return badZoomedRects } 1391 var node = removeChildrenAndAdd(measure, elt("span", "x")); 1392 var normal = node.getBoundingClientRect(); 1393 var fromRange = range(node, 0, 1).getBoundingClientRect(); 1394 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 1395 } 1396 1397 // Known modes, by name and by MIME 1398 var modes = {}; 1399 var mimeModes = {}; 1400 1401 // Extra arguments are stored as the mode's dependencies, which is 1402 // used by (legacy) mechanisms like loadmode.js to automatically 1403 // load a mode. (Preferred mechanism is the require/define calls.) 1404 function defineMode(name, mode) { 1405 if (arguments.length > 2) 1406 { mode.dependencies = Array.prototype.slice.call(arguments, 2); } 1407 modes[name] = mode; 1408 } 1409 1410 function defineMIME(mime, spec) { 1411 mimeModes[mime] = spec; 1412 } 1413 1414 // Given a MIME type, a {name, ...options} config object, or a name 1415 // string, return a mode config object. 1416 function resolveMode(spec) { 1417 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { 1418 spec = mimeModes[spec]; 1419 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { 1420 var found = mimeModes[spec.name]; 1421 if (typeof found == "string") { found = {name: found}; } 1422 spec = createObj(found, spec); 1423 spec.name = found.name; 1424 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { 1425 return resolveMode("application/xml") 1426 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { 1427 return resolveMode("application/json") 1428 } 1429 if (typeof spec == "string") { return {name: spec} } 1430 else { return spec || {name: "null"} } 1431 } 1432 1433 // Given a mode spec (anything that resolveMode accepts), find and 1434 // initialize an actual mode object. 1435 function getMode(options, spec) { 1436 spec = resolveMode(spec); 1437 var mfactory = modes[spec.name]; 1438 if (!mfactory) { return getMode(options, "text/plain") } 1439 var modeObj = mfactory(options, spec); 1440 if (modeExtensions.hasOwnProperty(spec.name)) { 1441 var exts = modeExtensions[spec.name]; 1442 for (var prop in exts) { 1443 if (!exts.hasOwnProperty(prop)) { continue } 1444 if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } 1445 modeObj[prop] = exts[prop]; 1446 } 1447 } 1448 modeObj.name = spec.name; 1449 if (spec.helperType) { modeObj.helperType = spec.helperType; } 1450 if (spec.modeProps) { for (var prop$1 in spec.modeProps) 1451 { modeObj[prop$1] = spec.modeProps[prop$1]; } } 1452 1453 return modeObj 1454 } 1455 1456 // This can be used to attach properties to mode objects from 1457 // outside the actual mode definition. 1458 var modeExtensions = {}; 1459 function extendMode(mode, properties) { 1460 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 1461 copyObj(properties, exts); 1462 } 1463 1464 function copyState(mode, state) { 1465 if (state === true) { return state } 1466 if (mode.copyState) { return mode.copyState(state) } 1467 var nstate = {}; 1468 for (var n in state) { 1469 var val = state[n]; 1470 if (val instanceof Array) { val = val.concat([]); } 1471 nstate[n] = val; 1472 } 1473 return nstate 1474 } 1475 1476 // Given a mode and a state (for that mode), find the inner mode and 1477 // state at the position that the state refers to. 1478 function innerMode(mode, state) { 1479 var info; 1480 while (mode.innerMode) { 1481 info = mode.innerMode(state); 1482 if (!info || info.mode == mode) { break } 1483 state = info.state; 1484 mode = info.mode; 1485 } 1486 return info || {mode: mode, state: state} 1487 } 1488 1489 function startState(mode, a1, a2) { 1490 return mode.startState ? mode.startState(a1, a2) : true 1491 } 1492 1493 // STRING STREAM 1494 1495 // Fed to the mode parsers, provides helper functions to make 1496 // parsers more succinct. 1497 1498 var StringStream = function(string, tabSize, lineOracle) { 1499 this.pos = this.start = 0; 1500 this.string = string; 1501 this.tabSize = tabSize || 8; 1502 this.lastColumnPos = this.lastColumnValue = 0; 1503 this.lineStart = 0; 1504 this.lineOracle = lineOracle; 1505 }; 1506 1507 StringStream.prototype.eol = function () {return this.pos >= this.string.length}; 1508 StringStream.prototype.sol = function () {return this.pos == this.lineStart}; 1509 StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; 1510 StringStream.prototype.next = function () { 1511 if (this.pos < this.string.length) 1512 { return this.string.charAt(this.pos++) } 1513 }; 1514 StringStream.prototype.eat = function (match) { 1515 var ch = this.string.charAt(this.pos); 1516 var ok; 1517 if (typeof match == "string") { ok = ch == match; } 1518 else { ok = ch && (match.test ? match.test(ch) : match(ch)); } 1519 if (ok) {++this.pos; return ch} 1520 }; 1521 StringStream.prototype.eatWhile = function (match) { 1522 var start = this.pos; 1523 while (this.eat(match)){} 1524 return this.pos > start 1525 }; 1526 StringStream.prototype.eatSpace = function () { 1527 var this$1 = this; 1528 1529 var start = this.pos; 1530 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } 1531 return this.pos > start 1532 }; 1533 StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; 1534 StringStream.prototype.skipTo = function (ch) { 1535 var found = this.string.indexOf(ch, this.pos); 1536 if (found > -1) {this.pos = found; return true} 1537 }; 1538 StringStream.prototype.backUp = function (n) {this.pos -= n;}; 1539 StringStream.prototype.column = function () { 1540 if (this.lastColumnPos < this.start) { 1541 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); 1542 this.lastColumnPos = this.start; 1543 } 1544 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1545 }; 1546 StringStream.prototype.indentation = function () { 1547 return countColumn(this.string, null, this.tabSize) - 1548 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1549 }; 1550 StringStream.prototype.match = function (pattern, consume, caseInsensitive) { 1551 if (typeof pattern == "string") { 1552 var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; 1553 var substr = this.string.substr(this.pos, pattern.length); 1554 if (cased(substr) == cased(pattern)) { 1555 if (consume !== false) { this.pos += pattern.length; } 1556 return true 1557 } 1558 } else { 1559 var match = this.string.slice(this.pos).match(pattern); 1560 if (match && match.index > 0) { return null } 1561 if (match && consume !== false) { this.pos += match[0].length; } 1562 return match 1563 } 1564 }; 1565 StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; 1566 StringStream.prototype.hideFirstChars = function (n, inner) { 1567 this.lineStart += n; 1568 try { return inner() } 1569 finally { this.lineStart -= n; } 1570 }; 1571 StringStream.prototype.lookAhead = function (n) { 1572 var oracle = this.lineOracle; 1573 return oracle && oracle.lookAhead(n) 1574 }; 1575 1576 var SavedContext = function(state, lookAhead) { 1577 this.state = state; 1578 this.lookAhead = lookAhead; 1579 }; 1580 1581 var Context = function(doc, state, line, lookAhead) { 1582 this.state = state; 1583 this.doc = doc; 1584 this.line = line; 1585 this.maxLookAhead = lookAhead || 0; 1586 }; 1587 1588 Context.prototype.lookAhead = function (n) { 1589 var line = this.doc.getLine(this.line + n); 1590 if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } 1591 return line 1592 }; 1593 1594 Context.prototype.nextLine = function () { 1595 this.line++; 1596 if (this.maxLookAhead > 0) { this.maxLookAhead--; } 1597 }; 1598 1599 Context.fromSaved = function (doc, saved, line) { 1600 if (saved instanceof SavedContext) 1601 { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } 1602 else 1603 { return new Context(doc, copyState(doc.mode, saved), line) } 1604 }; 1605 1606 Context.prototype.save = function (copy) { 1607 var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; 1608 return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state 1609 }; 1610 1611 1612 // Compute a style array (an array starting with a mode generation 1613 // -- for invalidation -- followed by pairs of end positions and 1614 // style strings), which is used to highlight the tokens on the 1615 // line. 1616 function highlightLine(cm, line, context, forceToEnd) { 1617 // A styles array always starts with a number identifying the 1618 // mode/overlays that it is based on (for easy invalidation). 1619 var st = [cm.state.modeGen], lineClasses = {}; 1620 // Compute the base array of styles 1621 runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, 1622 lineClasses, forceToEnd); 1623 var state = context.state; 1624 1625 // Run overlays, adjust style array. 1626 var loop = function ( o ) { 1627 var overlay = cm.state.overlays[o], i = 1, at = 0; 1628 context.state = true; 1629 runMode(cm, line.text, overlay.mode, context, function (end, style) { 1630 var start = i; 1631 // Ensure there's a token end at the current position, and that i points at it 1632 while (at < end) { 1633 var i_end = st[i]; 1634 if (i_end > end) 1635 { st.splice(i, 1, end, st[i+1], i_end); } 1636 i += 2; 1637 at = Math.min(end, i_end); 1638 } 1639 if (!style) { return } 1640 if (overlay.opaque) { 1641 st.splice(start, i - start, end, "overlay " + style); 1642 i = start + 2; 1643 } else { 1644 for (; start < i; start += 2) { 1645 var cur = st[start+1]; 1646 st[start+1] = (cur ? cur + " " : "") + "overlay " + style; 1647 } 1648 } 1649 }, lineClasses); 1650 }; 1651 1652 for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); 1653 context.state = state; 1654 1655 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} 1656 } 1657 1658 function getLineStyles(cm, line, updateFrontier) { 1659 if (!line.styles || line.styles[0] != cm.state.modeGen) { 1660 var context = getContextBefore(cm, lineNo(line)); 1661 var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); 1662 var result = highlightLine(cm, line, context); 1663 if (resetState) { context.state = resetState; } 1664 line.stateAfter = context.save(!resetState); 1665 line.styles = result.styles; 1666 if (result.classes) { line.styleClasses = result.classes; } 1667 else if (line.styleClasses) { line.styleClasses = null; } 1668 if (updateFrontier === cm.doc.highlightFrontier) 1669 { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } 1670 } 1671 return line.styles 1672 } 1673 1674 function getContextBefore(cm, n, precise) { 1675 var doc = cm.doc, display = cm.display; 1676 if (!doc.mode.startState) { return new Context(doc, true, n) } 1677 var start = findStartLine(cm, n, precise); 1678 var saved = start > doc.first && getLine(doc, start - 1).stateAfter; 1679 var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); 1680 1681 doc.iter(start, n, function (line) { 1682 processLine(cm, line.text, context); 1683 var pos = context.line; 1684 line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; 1685 context.nextLine(); 1686 }); 1687 if (precise) { doc.modeFrontier = context.line; } 1688 return context 1689 } 1690 1691 // Lightweight form of highlight -- proceed over this line and 1692 // update state, but don't save a style array. Used for lines that 1693 // aren't currently visible. 1694 function processLine(cm, text, context, startAt) { 1695 var mode = cm.doc.mode; 1696 var stream = new StringStream(text, cm.options.tabSize, context); 1697 stream.start = stream.pos = startAt || 0; 1698 if (text == "") { callBlankLine(mode, context.state); } 1699 while (!stream.eol()) { 1700 readToken(mode, stream, context.state); 1701 stream.start = stream.pos; 1702 } 1703 } 1704 1705 function callBlankLine(mode, state) { 1706 if (mode.blankLine) { return mode.blankLine(state) } 1707 if (!mode.innerMode) { return } 1708 var inner = innerMode(mode, state); 1709 if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } 1710 } 1711 1712 function readToken(mode, stream, state, inner) { 1713 for (var i = 0; i < 10; i++) { 1714 if (inner) { inner[0] = innerMode(mode, state).mode; } 1715 var style = mode.token(stream, state); 1716 if (stream.pos > stream.start) { return style } 1717 } 1718 throw new Error("Mode " + mode.name + " failed to advance stream.") 1719 } 1720 1721 var Token = function(stream, type, state) { 1722 this.start = stream.start; this.end = stream.pos; 1723 this.string = stream.current(); 1724 this.type = type || null; 1725 this.state = state; 1726 }; 1727 1728 // Utility for getTokenAt and getLineTokens 1729 function takeToken(cm, pos, precise, asArray) { 1730 var doc = cm.doc, mode = doc.mode, style; 1731 pos = clipPos(doc, pos); 1732 var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); 1733 var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; 1734 if (asArray) { tokens = []; } 1735 while ((asArray || stream.pos < pos.ch) && !stream.eol()) { 1736 stream.start = stream.pos; 1737 style = readToken(mode, stream, context.state); 1738 if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } 1739 } 1740 return asArray ? tokens : new Token(stream, style, context.state) 1741 } 1742 1743 function extractLineClasses(type, output) { 1744 if (type) { for (;;) { 1745 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); 1746 if (!lineClass) { break } 1747 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); 1748 var prop = lineClass[1] ? "bgClass" : "textClass"; 1749 if (output[prop] == null) 1750 { output[prop] = lineClass[2]; } 1751 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) 1752 { output[prop] += " " + lineClass[2]; } 1753 } } 1754 return type 1755 } 1756 1757 // Run the given mode's parser over a line, calling f for each token. 1758 function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { 1759 var flattenSpans = mode.flattenSpans; 1760 if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } 1761 var curStart = 0, curStyle = null; 1762 var stream = new StringStream(text, cm.options.tabSize, context), style; 1763 var inner = cm.options.addModeClass && [null]; 1764 if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } 1765 while (!stream.eol()) { 1766 if (stream.pos > cm.options.maxHighlightLength) { 1767 flattenSpans = false; 1768 if (forceToEnd) { processLine(cm, text, context, stream.pos); } 1769 stream.pos = text.length; 1770 style = null; 1771 } else { 1772 style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); 1773 } 1774 if (inner) { 1775 var mName = inner[0].name; 1776 if (mName) { style = "m-" + (style ? mName + " " + style : mName); } 1777 } 1778 if (!flattenSpans || curStyle != style) { 1779 while (curStart < stream.start) { 1780 curStart = Math.min(stream.start, curStart + 5000); 1781 f(curStart, curStyle); 1782 } 1783 curStyle = style; 1784 } 1785 stream.start = stream.pos; 1786 } 1787 while (curStart < stream.pos) { 1788 // Webkit seems to refuse to render text nodes longer than 57444 1789 // characters, and returns inaccurate measurements in nodes 1790 // starting around 5000 chars. 1791 var pos = Math.min(stream.pos, curStart + 5000); 1792 f(pos, curStyle); 1793 curStart = pos; 1794 } 1795 } 1796 1797 // Finds the line to start with when starting a parse. Tries to 1798 // find a line with a stateAfter, so that it can start with a 1799 // valid state. If that fails, it returns the line with the 1800 // smallest indentation, which tends to need the least context to 1801 // parse correctly. 1802 function findStartLine(cm, n, precise) { 1803 var minindent, minline, doc = cm.doc; 1804 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); 1805 for (var search = n; search > lim; --search) { 1806 if (search <= doc.first) { return doc.first } 1807 var line = getLine(doc, search - 1), after = line.stateAfter; 1808 if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) 1809 { return search } 1810 var indented = countColumn(line.text, null, cm.options.tabSize); 1811 if (minline == null || minindent > indented) { 1812 minline = search - 1; 1813 minindent = indented; 1814 } 1815 } 1816 return minline 1817 } 1818 1819 function retreatFrontier(doc, n) { 1820 doc.modeFrontier = Math.min(doc.modeFrontier, n); 1821 if (doc.highlightFrontier < n - 10) { return } 1822 var start = doc.first; 1823 for (var line = n - 1; line > start; line--) { 1824 var saved = getLine(doc, line).stateAfter; 1825 // change is on 3 1826 // state on line 1 looked ahead 2 -- so saw 3 1827 // test 1 + 2 < 3 should cover this 1828 if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { 1829 start = line + 1; 1830 break 1831 } 1832 } 1833 doc.highlightFrontier = Math.min(doc.highlightFrontier, start); 1834 } 1835 1836 // LINE DATA STRUCTURE 1837 1838 // Line objects. These hold state related to a line, including 1839 // highlighting info (the styles array). 1840 var Line = function(text, markedSpans, estimateHeight) { 1841 this.text = text; 1842 attachMarkedSpans(this, markedSpans); 1843 this.height = estimateHeight ? estimateHeight(this) : 1; 1844 }; 1845 1846 Line.prototype.lineNo = function () { return lineNo(this) }; 1847 eventMixin(Line); 1848 1849 // Change the content (text, markers) of a line. Automatically 1850 // invalidates cached information and tries to re-estimate the 1851 // line's height. 1852 function updateLine(line, text, markedSpans, estimateHeight) { 1853 line.text = text; 1854 if (line.stateAfter) { line.stateAfter = null; } 1855 if (line.styles) { line.styles = null; } 1856 if (line.order != null) { line.order = null; } 1857 detachMarkedSpans(line); 1858 attachMarkedSpans(line, markedSpans); 1859 var estHeight = estimateHeight ? estimateHeight(line) : 1; 1860 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 1861 } 1862 1863 // Detach a line from the document tree and its markers. 1864 function cleanUpLine(line) { 1865 line.parent = null; 1866 detachMarkedSpans(line); 1867 } 1868 1869 // Convert a style as returned by a mode (either null, or a string 1870 // containing one or more styles) to a CSS style. This is cached, 1871 // and also looks for line-wide styles. 1872 var styleToClassCache = {}; 1873 var styleToClassCacheWithMode = {}; 1874 function interpretTokenStyle(style, options) { 1875 if (!style || /^\s*$/.test(style)) { return null } 1876 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; 1877 return cache[style] || 1878 (cache[style] = style.replace(/\S+/g, "cm-$&")) 1879 } 1880 1881 // Render the DOM representation of the text of a line. Also builds 1882 // up a 'line map', which points at the DOM nodes that represent 1883 // specific stretches of text, and is used by the measuring code. 1884 // The returned object contains the DOM node, this map, and 1885 // information about line-wide styles that were set by the mode. 1886 function buildLineContent(cm, lineView) { 1887 // The padding-right forces the element to have a 'border', which 1888 // is needed on Webkit to be able to get line-level bounding 1889 // rectangles for it (in measureChar). 1890 var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); 1891 var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, 1892 col: 0, pos: 0, cm: cm, 1893 trailingSpace: false, 1894 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; 1895 lineView.measure = {}; 1896 1897 // Iterate over the logical lines that make up this visual line. 1898 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { 1899 var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); 1900 builder.pos = 0; 1901 builder.addToken = buildToken; 1902 // Optionally wire in some hacks into the token-rendering 1903 // algorithm, to deal with browser quirks. 1904 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) 1905 { builder.addToken = buildTokenBadBidi(builder.addToken, order); } 1906 builder.map = []; 1907 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); 1908 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); 1909 if (line.styleClasses) { 1910 if (line.styleClasses.bgClass) 1911 { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } 1912 if (line.styleClasses.textClass) 1913 { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } 1914 } 1915 1916 // Ensure at least a single node is present, for measuring. 1917 if (builder.map.length == 0) 1918 { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } 1919 1920 // Store the map and a cache object for the current logical line 1921 if (i == 0) { 1922 lineView.measure.map = builder.map; 1923 lineView.measure.cache = {}; 1924 } else { 1925 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) 1926 ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); 1927 } 1928 } 1929 1930 // See issue #2901 1931 if (webkit) { 1932 var last = builder.content.lastChild; 1933 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) 1934 { builder.content.className = "cm-tab-wrap-hack"; } 1935 } 1936 1937 signal(cm, "renderLine", cm, lineView.line, builder.pre); 1938 if (builder.pre.className) 1939 { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } 1940 1941 return builder 1942 } 1943 1944 function defaultSpecialCharPlaceholder(ch) { 1945 var token = elt("span", "\u2022", "cm-invalidchar"); 1946 token.title = "\\u" + ch.charCodeAt(0).toString(16); 1947 token.setAttribute("aria-label", token.title); 1948 return token 1949 } 1950 1951 // Build up the DOM representation for a single token, and add it to 1952 // the line map. Takes care to render special characters separately. 1953 function buildToken(builder, text, style, startStyle, endStyle, title, css) { 1954 if (!text) { return } 1955 var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; 1956 var special = builder.cm.state.specialChars, mustWrap = false; 1957 var content; 1958 if (!special.test(text)) { 1959 builder.col += text.length; 1960 content = document.createTextNode(displayText); 1961 builder.map.push(builder.pos, builder.pos + text.length, content); 1962 if (ie && ie_version < 9) { mustWrap = true; } 1963 builder.pos += text.length; 1964 } else { 1965 content = document.createDocumentFragment(); 1966 var pos = 0; 1967 while (true) { 1968 special.lastIndex = pos; 1969 var m = special.exec(text); 1970 var skipped = m ? m.index - pos : text.length - pos; 1971 if (skipped) { 1972 var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); 1973 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } 1974 else { content.appendChild(txt); } 1975 builder.map.push(builder.pos, builder.pos + skipped, txt); 1976 builder.col += skipped; 1977 builder.pos += skipped; 1978 } 1979 if (!m) { break } 1980 pos += skipped + 1; 1981 var txt$1 = (void 0); 1982 if (m[0] == "\t") { 1983 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 1984 txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 1985 txt$1.setAttribute("role", "presentation"); 1986 txt$1.setAttribute("cm-text", "\t"); 1987 builder.col += tabWidth; 1988 } else if (m[0] == "\r" || m[0] == "\n") { 1989 txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); 1990 txt$1.setAttribute("cm-text", m[0]); 1991 builder.col += 1; 1992 } else { 1993 txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); 1994 txt$1.setAttribute("cm-text", m[0]); 1995 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } 1996 else { content.appendChild(txt$1); } 1997 builder.col += 1; 1998 } 1999 builder.map.push(builder.pos, builder.pos + 1, txt$1); 2000 builder.pos++; 2001 } 2002 } 2003 builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; 2004 if (style || startStyle || endStyle || mustWrap || css) { 2005 var fullStyle = style || ""; 2006 if (startStyle) { fullStyle += startStyle; } 2007 if (endStyle) { fullStyle += endStyle; } 2008 var token = elt("span", [content], fullStyle, css); 2009 if (title) { token.title = title; } 2010 return builder.content.appendChild(token) 2011 } 2012 builder.content.appendChild(content); 2013 } 2014 2015 function splitSpaces(text, trailingBefore) { 2016 if (text.length > 1 && !/ /.test(text)) { return text } 2017 var spaceBefore = trailingBefore, result = ""; 2018 for (var i = 0; i < text.length; i++) { 2019 var ch = text.charAt(i); 2020 if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) 2021 { ch = "\u00a0"; } 2022 result += ch; 2023 spaceBefore = ch == " "; 2024 } 2025 return result 2026 } 2027 2028 // Work around nonsense dimensions being reported for stretches of 2029 // right-to-left text. 2030 function buildTokenBadBidi(inner, order) { 2031 return function (builder, text, style, startStyle, endStyle, title, css) { 2032 style = style ? style + " cm-force-border" : "cm-force-border"; 2033 var start = builder.pos, end = start + text.length; 2034 for (;;) { 2035 // Find the part that overlaps with the start of this text 2036 var part = (void 0); 2037 for (var i = 0; i < order.length; i++) { 2038 part = order[i]; 2039 if (part.to > start && part.from <= start) { break } 2040 } 2041 if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } 2042 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); 2043 startStyle = null; 2044 text = text.slice(part.to - start); 2045 start = part.to; 2046 } 2047 } 2048 } 2049 2050 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { 2051 var widget = !ignoreWidget && marker.widgetNode; 2052 if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } 2053 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { 2054 if (!widget) 2055 { widget = builder.content.appendChild(document.createElement("span")); } 2056 widget.setAttribute("cm-marker", marker.id); 2057 } 2058 if (widget) { 2059 builder.cm.display.input.setUneditable(widget); 2060 builder.content.appendChild(widget); 2061 } 2062 builder.pos += size; 2063 builder.trailingSpace = false; 2064 } 2065 2066 // Outputs a number of spans to make up a line, taking highlighting 2067 // and marked text into account. 2068 function insertLineContent(line, builder, styles) { 2069 var spans = line.markedSpans, allText = line.text, at = 0; 2070 if (!spans) { 2071 for (var i$1 = 1; i$1 < styles.length; i$1+=2) 2072 { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } 2073 return 2074 } 2075 2076 var len = allText.length, pos = 0, i = 1, text = "", style, css; 2077 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; 2078 for (;;) { 2079 if (nextChange == pos) { // Update current marker set 2080 spanStyle = spanEndStyle = spanStartStyle = title = css = ""; 2081 collapsed = null; nextChange = Infinity; 2082 var foundBookmarks = [], endStyles = (void 0); 2083 for (var j = 0; j < spans.length; ++j) { 2084 var sp = spans[j], m = sp.marker; 2085 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { 2086 foundBookmarks.push(m); 2087 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { 2088 if (sp.to != null && sp.to != pos && nextChange > sp.to) { 2089 nextChange = sp.to; 2090 spanEndStyle = ""; 2091 } 2092 if (m.className) { spanStyle += " " + m.className; } 2093 if (m.css) { css = (css ? css + ";" : "") + m.css; } 2094 if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } 2095 if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } 2096 if (m.title && !title) { title = m.title; } 2097 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) 2098 { collapsed = sp; } 2099 } else if (sp.from > pos && nextChange > sp.from) { 2100 nextChange = sp.from; 2101 } 2102 } 2103 if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) 2104 { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } 2105 2106 if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) 2107 { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } 2108 if (collapsed && (collapsed.from || 0) == pos) { 2109 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, 2110 collapsed.marker, collapsed.from == null); 2111 if (collapsed.to == null) { return } 2112 if (collapsed.to == pos) { collapsed = false; } 2113 } 2114 } 2115 if (pos >= len) { break } 2116 2117 var upto = Math.min(len, nextChange); 2118 while (true) { 2119 if (text) { 2120 var end = pos + text.length; 2121 if (!collapsed) { 2122 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 2123 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 2124 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); 2125 } 2126 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} 2127 pos = end; 2128 spanStartStyle = ""; 2129 } 2130 text = allText.slice(at, at = styles[i++]); 2131 style = interpretTokenStyle(styles[i++], builder.cm.options); 2132 } 2133 } 2134 } 2135 2136 2137 // These objects are used to represent the visible (currently drawn) 2138 // part of the document. A LineView may correspond to multiple 2139 // logical lines, if those are connected by collapsed ranges. 2140 function LineView(doc, line, lineN) { 2141 // The starting line 2142 this.line = line; 2143 // Continuing lines, if any 2144 this.rest = visualLineContinued(line); 2145 // Number of logical lines in this visual line 2146 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; 2147 this.node = this.text = null; 2148 this.hidden = lineIsHidden(doc, line); 2149 } 2150 2151 // Create a range of LineView objects for the given lines. 2152 function buildViewArray(cm, from, to) { 2153 var array = [], nextPos; 2154 for (var pos = from; pos < to; pos = nextPos) { 2155 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); 2156 nextPos = pos + view.size; 2157 array.push(view); 2158 } 2159 return array 2160 } 2161 2162 var operationGroup = null; 2163 2164 function pushOperation(op) { 2165 if (operationGroup) { 2166 operationGroup.ops.push(op); 2167 } else { 2168 op.ownsGroup = operationGroup = { 2169 ops: [op], 2170 delayedCallbacks: [] 2171 }; 2172 } 2173 } 2174 2175 function fireCallbacksForOps(group) { 2176 // Calls delayed callbacks and cursorActivity handlers until no 2177 // new ones appear 2178 var callbacks = group.delayedCallbacks, i = 0; 2179 do { 2180 for (; i < callbacks.length; i++) 2181 { callbacks[i].call(null); } 2182 for (var j = 0; j < group.ops.length; j++) { 2183 var op = group.ops[j]; 2184 if (op.cursorActivityHandlers) 2185 { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) 2186 { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } 2187 } 2188 } while (i < callbacks.length) 2189 } 2190 2191 function finishOperation(op, endCb) { 2192 var group = op.ownsGroup; 2193 if (!group) { return } 2194 2195 try { fireCallbacksForOps(group); } 2196 finally { 2197 operationGroup = null; 2198 endCb(group); 2199 } 2200 } 2201 2202 var orphanDelayedCallbacks = null; 2203 2204 // Often, we want to signal events at a point where we are in the 2205 // middle of some work, but don't want the handler to start calling 2206 // other methods on the editor, which might be in an inconsistent 2207 // state or simply not expect any other events to happen. 2208 // signalLater looks whether there are any handlers, and schedules 2209 // them to be executed when the last operation ends, or, if no 2210 // operation is active, when a timeout fires. 2211 function signalLater(emitter, type /*, values...*/) { 2212 var arr = getHandlers(emitter, type); 2213 if (!arr.length) { return } 2214 var args = Array.prototype.slice.call(arguments, 2), list; 2215 if (operationGroup) { 2216 list = operationGroup.delayedCallbacks; 2217 } else if (orphanDelayedCallbacks) { 2218 list = orphanDelayedCallbacks; 2219 } else { 2220 list = orphanDelayedCallbacks = []; 2221 setTimeout(fireOrphanDelayed, 0); 2222 } 2223 var loop = function ( i ) { 2224 list.push(function () { return arr[i].apply(null, args); }); 2225 }; 2226 2227 for (var i = 0; i < arr.length; ++i) 2228 loop( i ); 2229 } 2230 2231 function fireOrphanDelayed() { 2232 var delayed = orphanDelayedCallbacks; 2233 orphanDelayedCallbacks = null; 2234 for (var i = 0; i < delayed.length; ++i) { delayed[i](); } 2235 } 2236 2237 // When an aspect of a line changes, a string is added to 2238 // lineView.changes. This updates the relevant part of the line's 2239 // DOM structure. 2240 function updateLineForChanges(cm, lineView, lineN, dims) { 2241 for (var j = 0; j < lineView.changes.length; j++) { 2242 var type = lineView.changes[j]; 2243 if (type == "text") { updateLineText(cm, lineView); } 2244 else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } 2245 else if (type == "class") { updateLineClasses(cm, lineView); } 2246 else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } 2247 } 2248 lineView.changes = null; 2249 } 2250 2251 // Lines with gutter elements, widgets or a background class need to 2252 // be wrapped, and have the extra elements added to the wrapper div 2253 function ensureLineWrapped(lineView) { 2254 if (lineView.node == lineView.text) { 2255 lineView.node = elt("div", null, null, "position: relative"); 2256 if (lineView.text.parentNode) 2257 { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } 2258 lineView.node.appendChild(lineView.text); 2259 if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } 2260 } 2261 return lineView.node 2262 } 2263 2264 function updateLineBackground(cm, lineView) { 2265 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; 2266 if (cls) { cls += " CodeMirror-linebackground"; } 2267 if (lineView.background) { 2268 if (cls) { lineView.background.className = cls; } 2269 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } 2270 } else if (cls) { 2271 var wrap = ensureLineWrapped(lineView); 2272 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); 2273 cm.display.input.setUneditable(lineView.background); 2274 } 2275 } 2276 2277 // Wrapper around buildLineContent which will reuse the structure 2278 // in display.externalMeasured when possible. 2279 function getLineContent(cm, lineView) { 2280 var ext = cm.display.externalMeasured; 2281 if (ext && ext.line == lineView.line) { 2282 cm.display.externalMeasured = null; 2283 lineView.measure = ext.measure; 2284 return ext.built 2285 } 2286 return buildLineContent(cm, lineView) 2287 } 2288 2289 // Redraw the line's text. Interacts with the background and text 2290 // classes because the mode may output tokens that influence these 2291 // classes. 2292 function updateLineText(cm, lineView) { 2293 var cls = lineView.text.className; 2294 var built = getLineContent(cm, lineView); 2295 if (lineView.text == lineView.node) { lineView.node = built.pre; } 2296 lineView.text.parentNode.replaceChild(built.pre, lineView.text); 2297 lineView.text = built.pre; 2298 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { 2299 lineView.bgClass = built.bgClass; 2300 lineView.textClass = built.textClass; 2301 updateLineClasses(cm, lineView); 2302 } else if (cls) { 2303 lineView.text.className = cls; 2304 } 2305 } 2306 2307 function updateLineClasses(cm, lineView) { 2308 updateLineBackground(cm, lineView); 2309 if (lineView.line.wrapClass) 2310 { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } 2311 else if (lineView.node != lineView.text) 2312 { lineView.node.className = ""; } 2313 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; 2314 lineView.text.className = textClass || ""; 2315 } 2316 2317 function updateLineGutter(cm, lineView, lineN, dims) { 2318 if (lineView.gutter) { 2319 lineView.node.removeChild(lineView.gutter); 2320 lineView.gutter = null; 2321 } 2322 if (lineView.gutterBackground) { 2323 lineView.node.removeChild(lineView.gutterBackground); 2324 lineView.gutterBackground = null; 2325 } 2326 if (lineView.line.gutterClass) { 2327 var wrap = ensureLineWrapped(lineView); 2328 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, 2329 ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); 2330 cm.display.input.setUneditable(lineView.gutterBackground); 2331 wrap.insertBefore(lineView.gutterBackground, lineView.text); 2332 } 2333 var markers = lineView.line.gutterMarkers; 2334 if (cm.options.lineNumbers || markers) { 2335 var wrap$1 = ensureLineWrapped(lineView); 2336 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); 2337 cm.display.input.setUneditable(gutterWrap); 2338 wrap$1.insertBefore(gutterWrap, lineView.text); 2339 if (lineView.line.gutterClass) 2340 { gutterWrap.className += " " + lineView.line.gutterClass; } 2341 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 2342 { lineView.lineNumber = gutterWrap.appendChild( 2343 elt("div", lineNumberFor(cm.options, lineN), 2344 "CodeMirror-linenumber CodeMirror-gutter-elt", 2345 ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } 2346 if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { 2347 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 2348 if (found) 2349 { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", 2350 ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } 2351 } } 2352 } 2353 } 2354 2355 function updateLineWidgets(cm, lineView, dims) { 2356 if (lineView.alignable) { lineView.alignable = null; } 2357 for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { 2358 next = node.nextSibling; 2359 if (node.className == "CodeMirror-linewidget") 2360 { lineView.node.removeChild(node); } 2361 } 2362 insertLineWidgets(cm, lineView, dims); 2363 } 2364 2365 // Build a line's DOM representation from scratch 2366 function buildLineElement(cm, lineView, lineN, dims) { 2367 var built = getLineContent(cm, lineView); 2368 lineView.text = lineView.node = built.pre; 2369 if (built.bgClass) { lineView.bgClass = built.bgClass; } 2370 if (built.textClass) { lineView.textClass = built.textClass; } 2371 2372 updateLineClasses(cm, lineView); 2373 updateLineGutter(cm, lineView, lineN, dims); 2374 insertLineWidgets(cm, lineView, dims); 2375 return lineView.node 2376 } 2377 2378 // A lineView may contain multiple logical lines (when merged by 2379 // collapsed spans). The widgets for all of them need to be drawn. 2380 function insertLineWidgets(cm, lineView, dims) { 2381 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); 2382 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2383 { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } 2384 } 2385 2386 function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { 2387 if (!line.widgets) { return } 2388 var wrap = ensureLineWrapped(lineView); 2389 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 2390 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 2391 if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } 2392 positionLineWidget(widget, node, lineView, dims); 2393 cm.display.input.setUneditable(node); 2394 if (allowAbove && widget.above) 2395 { wrap.insertBefore(node, lineView.gutter || lineView.text); } 2396 else 2397 { wrap.appendChild(node); } 2398 signalLater(widget, "redraw"); 2399 } 2400 } 2401 2402 function positionLineWidget(widget, node, lineView, dims) { 2403 if (widget.noHScroll) { 2404 (lineView.alignable || (lineView.alignable = [])).push(node); 2405 var width = dims.wrapperWidth; 2406 node.style.left = dims.fixedPos + "px"; 2407 if (!widget.coverGutter) { 2408 width -= dims.gutterTotalWidth; 2409 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 2410 } 2411 node.style.width = width + "px"; 2412 } 2413 if (widget.coverGutter) { 2414 node.style.zIndex = 5; 2415 node.style.position = "relative"; 2416 if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } 2417 } 2418 } 2419 2420 function widgetHeight(widget) { 2421 if (widget.height != null) { return widget.height } 2422 var cm = widget.doc.cm; 2423 if (!cm) { return 0 } 2424 if (!contains(document.body, widget.node)) { 2425 var parentStyle = "position: relative;"; 2426 if (widget.coverGutter) 2427 { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } 2428 if (widget.noHScroll) 2429 { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } 2430 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); 2431 } 2432 return widget.height = widget.node.parentNode.offsetHeight 2433 } 2434 2435 // Return true when the given mouse event happened in a widget 2436 function eventInWidget(display, e) { 2437 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 2438 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || 2439 (n.parentNode == display.sizer && n != display.mover)) 2440 { return true } 2441 } 2442 } 2443 2444 // POSITION MEASUREMENT 2445 2446 function paddingTop(display) {return display.lineSpace.offsetTop} 2447 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} 2448 function paddingH(display) { 2449 if (display.cachedPaddingH) { return display.cachedPaddingH } 2450 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); 2451 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; 2452 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; 2453 if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } 2454 return data 2455 } 2456 2457 function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } 2458 function displayWidth(cm) { 2459 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth 2460 } 2461 function displayHeight(cm) { 2462 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight 2463 } 2464 2465 // Ensure the lineView.wrapping.heights array is populated. This is 2466 // an array of bottom offsets for the lines that make up a drawn 2467 // line. When lineWrapping is on, there might be more than one 2468 // height. 2469 function ensureLineHeights(cm, lineView, rect) { 2470 var wrapping = cm.options.lineWrapping; 2471 var curWidth = wrapping && displayWidth(cm); 2472 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { 2473 var heights = lineView.measure.heights = []; 2474 if (wrapping) { 2475 lineView.measure.width = curWidth; 2476 var rects = lineView.text.firstChild.getClientRects(); 2477 for (var i = 0; i < rects.length - 1; i++) { 2478 var cur = rects[i], next = rects[i + 1]; 2479 if (Math.abs(cur.bottom - next.bottom) > 2) 2480 { heights.push((cur.bottom + next.top) / 2 - rect.top); } 2481 } 2482 } 2483 heights.push(rect.bottom - rect.top); 2484 } 2485 } 2486 2487 // Find a line map (mapping character offsets to text nodes) and a 2488 // measurement cache for the given line number. (A line view might 2489 // contain multiple lines when collapsed ranges are present.) 2490 function mapFromLineView(lineView, line, lineN) { 2491 if (lineView.line == line) 2492 { return {map: lineView.measure.map, cache: lineView.measure.cache} } 2493 for (var i = 0; i < lineView.rest.length; i++) 2494 { if (lineView.rest[i] == line) 2495 { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } 2496 for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) 2497 { if (lineNo(lineView.rest[i$1]) > lineN) 2498 { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } 2499 } 2500 2501 // Render a line into the hidden node display.externalMeasured. Used 2502 // when measurement is needed for a line that's not in the viewport. 2503 function updateExternalMeasurement(cm, line) { 2504 line = visualLine(line); 2505 var lineN = lineNo(line); 2506 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); 2507 view.lineN = lineN; 2508 var built = view.built = buildLineContent(cm, view); 2509 view.text = built.pre; 2510 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); 2511 return view 2512 } 2513 2514 // Get a {top, bottom, left, right} box (in line-local coordinates) 2515 // for a given character. 2516 function measureChar(cm, line, ch, bias) { 2517 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) 2518 } 2519 2520 // Find a line view that corresponds to the given line number. 2521 function findViewForLine(cm, lineN) { 2522 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) 2523 { return cm.display.view[findViewIndex(cm, lineN)] } 2524 var ext = cm.display.externalMeasured; 2525 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) 2526 { return ext } 2527 } 2528 2529 // Measurement can be split in two steps, the set-up work that 2530 // applies to the whole line, and the measurement of the actual 2531 // character. Functions like coordsChar, that need to do a lot of 2532 // measurements in a row, can thus ensure that the set-up work is 2533 // only done once. 2534 function prepareMeasureForLine(cm, line) { 2535 var lineN = lineNo(line); 2536 var view = findViewForLine(cm, lineN); 2537 if (view && !view.text) { 2538 view = null; 2539 } else if (view && view.changes) { 2540 updateLineForChanges(cm, view, lineN, getDimensions(cm)); 2541 cm.curOp.forceUpdate = true; 2542 } 2543 if (!view) 2544 { view = updateExternalMeasurement(cm, line); } 2545 2546 var info = mapFromLineView(view, line, lineN); 2547 return { 2548 line: line, view: view, rect: null, 2549 map: info.map, cache: info.cache, before: info.before, 2550 hasHeights: false 2551 } 2552 } 2553 2554 // Given a prepared measurement object, measures the position of an 2555 // actual character (or fetches it from the cache). 2556 function measureCharPrepared(cm, prepared, ch, bias, varHeight) { 2557 if (prepared.before) { ch = -1; } 2558 var key = ch + (bias || ""), found; 2559 if (prepared.cache.hasOwnProperty(key)) { 2560 found = prepared.cache[key]; 2561 } else { 2562 if (!prepared.rect) 2563 { prepared.rect = prepared.view.text.getBoundingClientRect(); } 2564 if (!prepared.hasHeights) { 2565 ensureLineHeights(cm, prepared.view, prepared.rect); 2566 prepared.hasHeights = true; 2567 } 2568 found = measureCharInner(cm, prepared, ch, bias); 2569 if (!found.bogus) { prepared.cache[key] = found; } 2570 } 2571 return {left: found.left, right: found.right, 2572 top: varHeight ? found.rtop : found.top, 2573 bottom: varHeight ? found.rbottom : found.bottom} 2574 } 2575 2576 var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; 2577 2578 function nodeAndOffsetInLineMap(map$$1, ch, bias) { 2579 var node, start, end, collapse, mStart, mEnd; 2580 // First, search the line map for the text node corresponding to, 2581 // or closest to, the target character. 2582 for (var i = 0; i < map$$1.length; i += 3) { 2583 mStart = map$$1[i]; 2584 mEnd = map$$1[i + 1]; 2585 if (ch < mStart) { 2586 start = 0; end = 1; 2587 collapse = "left"; 2588 } else if (ch < mEnd) { 2589 start = ch - mStart; 2590 end = start + 1; 2591 } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { 2592 end = mEnd - mStart; 2593 start = end - 1; 2594 if (ch >= mEnd) { collapse = "right"; } 2595 } 2596 if (start != null) { 2597 node = map$$1[i + 2]; 2598 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) 2599 { collapse = bias; } 2600 if (bias == "left" && start == 0) 2601 { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { 2602 node = map$$1[(i -= 3) + 2]; 2603 collapse = "left"; 2604 } } 2605 if (bias == "right" && start == mEnd - mStart) 2606 { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { 2607 node = map$$1[(i += 3) + 2]; 2608 collapse = "right"; 2609 } } 2610 break 2611 } 2612 } 2613 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} 2614 } 2615 2616 function getUsefulRect(rects, bias) { 2617 var rect = nullRect; 2618 if (bias == "left") { for (var i = 0; i < rects.length; i++) { 2619 if ((rect = rects[i]).left != rect.right) { break } 2620 } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { 2621 if ((rect = rects[i$1]).left != rect.right) { break } 2622 } } 2623 return rect 2624 } 2625 2626 function measureCharInner(cm, prepared, ch, bias) { 2627 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); 2628 var node = place.node, start = place.start, end = place.end, collapse = place.collapse; 2629 2630 var rect; 2631 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. 2632 for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned 2633 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } 2634 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } 2635 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) 2636 { rect = node.parentNode.getBoundingClientRect(); } 2637 else 2638 { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } 2639 if (rect.left || rect.right || start == 0) { break } 2640 end = start; 2641 start = start - 1; 2642 collapse = "right"; 2643 } 2644 if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } 2645 } else { // If it is a widget, simply get the box for the whole widget. 2646 if (start > 0) { collapse = bias = "right"; } 2647 var rects; 2648 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) 2649 { rect = rects[bias == "right" ? rects.length - 1 : 0]; } 2650 else 2651 { rect = node.getBoundingClientRect(); } 2652 } 2653 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { 2654 var rSpan = node.parentNode.getClientRects()[0]; 2655 if (rSpan) 2656 { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } 2657 else 2658 { rect = nullRect; } 2659 } 2660 2661 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; 2662 var mid = (rtop + rbot) / 2; 2663 var heights = prepared.view.measure.heights; 2664 var i = 0; 2665 for (; i < heights.length - 1; i++) 2666 { if (mid < heights[i]) { break } } 2667 var top = i ? heights[i - 1] : 0, bot = heights[i]; 2668 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, 2669 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, 2670 top: top, bottom: bot}; 2671 if (!rect.left && !rect.right) { result.bogus = true; } 2672 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } 2673 2674 return result 2675 } 2676 2677 // Work around problem with bounding client rects on ranges being 2678 // returned incorrectly when zoomed on IE10 and below. 2679 function maybeUpdateRectForZooming(measure, rect) { 2680 if (!window.screen || screen.logicalXDPI == null || 2681 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) 2682 { return rect } 2683 var scaleX = screen.logicalXDPI / screen.deviceXDPI; 2684 var scaleY = screen.logicalYDPI / screen.deviceYDPI; 2685 return {left: rect.left * scaleX, right: rect.right * scaleX, 2686 top: rect.top * scaleY, bottom: rect.bottom * scaleY} 2687 } 2688 2689 function clearLineMeasurementCacheFor(lineView) { 2690 if (lineView.measure) { 2691 lineView.measure.cache = {}; 2692 lineView.measure.heights = null; 2693 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2694 { lineView.measure.caches[i] = {}; } } 2695 } 2696 } 2697 2698 function clearLineMeasurementCache(cm) { 2699 cm.display.externalMeasure = null; 2700 removeChildren(cm.display.lineMeasure); 2701 for (var i = 0; i < cm.display.view.length; i++) 2702 { clearLineMeasurementCacheFor(cm.display.view[i]); } 2703 } 2704 2705 function clearCaches(cm) { 2706 clearLineMeasurementCache(cm); 2707 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; 2708 if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } 2709 cm.display.lineNumChars = null; 2710 } 2711 2712 function pageScrollX() { 2713 // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 2714 // which causes page_Offset and bounding client rects to use 2715 // different reference viewports and invalidate our calculations. 2716 if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } 2717 return window.pageXOffset || (document.documentElement || document.body).scrollLeft 2718 } 2719 function pageScrollY() { 2720 if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } 2721 return window.pageYOffset || (document.documentElement || document.body).scrollTop 2722 } 2723 2724 // Converts a {top, bottom, left, right} box from line-local 2725 // coordinates into another coordinate system. Context may be one of 2726 // "line", "div" (display.lineDiv), "local"./null (editor), "window", 2727 // or "page". 2728 function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { 2729 if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { 2730 var size = widgetHeight(lineObj.widgets[i]); 2731 rect.top += size; rect.bottom += size; 2732 } } } 2733 if (context == "line") { return rect } 2734 if (!context) { context = "local"; } 2735 var yOff = heightAtLine(lineObj); 2736 if (context == "local") { yOff += paddingTop(cm.display); } 2737 else { yOff -= cm.display.viewOffset; } 2738 if (context == "page" || context == "window") { 2739 var lOff = cm.display.lineSpace.getBoundingClientRect(); 2740 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); 2741 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); 2742 rect.left += xOff; rect.right += xOff; 2743 } 2744 rect.top += yOff; rect.bottom += yOff; 2745 return rect 2746 } 2747 2748 // Coverts a box from "div" coords to another coordinate system. 2749 // Context may be "window", "page", "div", or "local"./null. 2750 function fromCoordSystem(cm, coords, context) { 2751 if (context == "div") { return coords } 2752 var left = coords.left, top = coords.top; 2753 // First move into "page" coordinate system 2754 if (context == "page") { 2755 left -= pageScrollX(); 2756 top -= pageScrollY(); 2757 } else if (context == "local" || !context) { 2758 var localBox = cm.display.sizer.getBoundingClientRect(); 2759 left += localBox.left; 2760 top += localBox.top; 2761 } 2762 2763 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); 2764 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} 2765 } 2766 2767 function charCoords(cm, pos, context, lineObj, bias) { 2768 if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } 2769 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) 2770 } 2771 2772 // Returns a box for a given cursor position, which may have an 2773 // 'other' property containing the position of the secondary cursor 2774 // on a bidi boundary. 2775 // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` 2776 // and after `char - 1` in writing order of `char - 1` 2777 // A cursor Pos(line, char, "after") is on the same visual line as `char` 2778 // and before `char` in writing order of `char` 2779 // Examples (upper-case letters are RTL, lower-case are LTR): 2780 // Pos(0, 1, ...) 2781 // before after 2782 // ab a|b a|b 2783 // aB a|B aB| 2784 // Ab |Ab A|b 2785 // AB B|A B|A 2786 // Every position after the last character on a line is considered to stick 2787 // to the last character on the line. 2788 function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { 2789 lineObj = lineObj || getLine(cm.doc, pos.line); 2790 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } 2791 function get(ch, right) { 2792 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); 2793 if (right) { m.left = m.right; } else { m.right = m.left; } 2794 return intoCoordSystem(cm, lineObj, m, context) 2795 } 2796 var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; 2797 if (ch >= lineObj.text.length) { 2798 ch = lineObj.text.length; 2799 sticky = "before"; 2800 } else if (ch <= 0) { 2801 ch = 0; 2802 sticky = "after"; 2803 } 2804 if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } 2805 2806 function getBidi(ch, partPos, invert) { 2807 var part = order[partPos], right = (part.level % 2) != 0; 2808 return get(invert ? ch - 1 : ch, right != invert) 2809 } 2810 var partPos = getBidiPartAt(order, ch, sticky); 2811 var other = bidiOther; 2812 var val = getBidi(ch, partPos, sticky == "before"); 2813 if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } 2814 return val 2815 } 2816 2817 // Used to cheaply estimate the coordinates for a position. Used for 2818 // intermediate scroll updates. 2819 function estimateCoords(cm, pos) { 2820 var left = 0; 2821 pos = clipPos(cm.doc, pos); 2822 if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } 2823 var lineObj = getLine(cm.doc, pos.line); 2824 var top = heightAtLine(lineObj) + paddingTop(cm.display); 2825 return {left: left, right: left, top: top, bottom: top + lineObj.height} 2826 } 2827 2828 // Positions returned by coordsChar contain some extra information. 2829 // xRel is the relative x position of the input coordinates compared 2830 // to the found position (so xRel > 0 means the coordinates are to 2831 // the right of the character position, for example). When outside 2832 // is true, that means the coordinates lie outside the line's 2833 // vertical range. 2834 function PosWithInfo(line, ch, sticky, outside, xRel) { 2835 var pos = Pos(line, ch, sticky); 2836 pos.xRel = xRel; 2837 if (outside) { pos.outside = true; } 2838 return pos 2839 } 2840 2841 // Compute the character position closest to the given coordinates. 2842 // Input must be lineSpace-local ("div" coordinate system). 2843 function coordsChar(cm, x, y) { 2844 var doc = cm.doc; 2845 y += cm.display.viewOffset; 2846 if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } 2847 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 2848 if (lineN > last) 2849 { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } 2850 if (x < 0) { x = 0; } 2851 2852 var lineObj = getLine(doc, lineN); 2853 for (;;) { 2854 var found = coordsCharInner(cm, lineObj, lineN, x, y); 2855 var merged = collapsedSpanAtEnd(lineObj); 2856 var mergedPos = merged && merged.find(0, true); 2857 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) 2858 { lineN = lineNo(lineObj = mergedPos.to.line); } 2859 else 2860 { return found } 2861 } 2862 } 2863 2864 function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { 2865 var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }; 2866 var end = lineObj.text.length; 2867 var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0); 2868 end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end); 2869 return {begin: begin, end: end} 2870 } 2871 2872 function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { 2873 var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; 2874 return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) 2875 } 2876 2877 function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { 2878 y -= heightAtLine(lineObj); 2879 var begin = 0, end = lineObj.text.length; 2880 var preparedMeasure = prepareMeasureForLine(cm, lineObj); 2881 var pos; 2882 var order = getOrder(lineObj, cm.doc.direction); 2883 if (order) { 2884 if (cm.options.lineWrapping) { 2885 var assign; 2886 ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign)); 2887 } 2888 pos = new Pos(lineNo$$1, Math.floor(begin + (end - begin) / 2)); 2889 var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left; 2890 var dir = beginLeft < x ? 1 : -1; 2891 var prevDiff, diff = beginLeft - x, prevPos; 2892 var steps = Math.ceil((end - begin) / 4); 2893 outer: do { 2894 prevDiff = diff; 2895 prevPos = pos; 2896 var i = 0; 2897 for (; i < steps; ++i) { 2898 var prevPos$1 = pos; 2899 pos = moveVisually(cm, lineObj, pos, dir); 2900 if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) { 2901 pos = prevPos$1; 2902 break outer 2903 } 2904 } 2905 diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x; 2906 if (steps > 1) { 2907 var diff_change_per_step = Math.abs(diff - prevDiff) / steps; 2908 steps = Math.min(steps, Math.ceil(Math.abs(diff) / diff_change_per_step)); 2909 dir = diff < 0 ? 1 : -1; 2910 } 2911 } while (diff != 0 && (steps > 1 || ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff))))) 2912 if (Math.abs(diff) > Math.abs(prevDiff)) { 2913 if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") } 2914 pos = prevPos; 2915 } 2916 } else { 2917 var ch = findFirst(function (ch) { 2918 var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); 2919 if (box.top > y) { 2920 // For the cursor stickiness 2921 end = Math.min(ch, end); 2922 return true 2923 } 2924 else if (box.bottom <= y) { return false } 2925 else if (box.left > x) { return true } 2926 else if (box.right < x) { return false } 2927 else { return (x - box.left < box.right - x) } 2928 }, begin, end); 2929 ch = skipExtendingChars(lineObj.text, ch, 1); 2930 pos = new Pos(lineNo$$1, ch, ch == end ? "before" : "after"); 2931 } 2932 var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure); 2933 if (y < coords.top || coords.bottom < y) { pos.outside = true; } 2934 pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0); 2935 return pos 2936 } 2937 2938 var measureText; 2939 // Compute the default text height. 2940 function textHeight(display) { 2941 if (display.cachedTextHeight != null) { return display.cachedTextHeight } 2942 if (measureText == null) { 2943 measureText = elt("pre"); 2944 // Measure a bunch of lines, for browsers that compute 2945 // fractional heights. 2946 for (var i = 0; i < 49; ++i) { 2947 measureText.appendChild(document.createTextNode("x")); 2948 measureText.appendChild(elt("br")); 2949 } 2950 measureText.appendChild(document.createTextNode("x")); 2951 } 2952 removeChildrenAndAdd(display.measure, measureText); 2953 var height = measureText.offsetHeight / 50; 2954 if (height > 3) { display.cachedTextHeight = height; } 2955 removeChildren(display.measure); 2956 return height || 1 2957 } 2958 2959 // Compute the default character width. 2960 function charWidth(display) { 2961 if (display.cachedCharWidth != null) { return display.cachedCharWidth } 2962 var anchor = elt("span", "xxxxxxxxxx"); 2963 var pre = elt("pre", [anchor]); 2964 removeChildrenAndAdd(display.measure, pre); 2965 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; 2966 if (width > 2) { display.cachedCharWidth = width; } 2967 return width || 10 2968 } 2969 2970 // Do a bulk-read of the DOM positions and sizes needed to draw the 2971 // view, so that we don't interleave reading and writing to the DOM. 2972 function getDimensions(cm) { 2973 var d = cm.display, left = {}, width = {}; 2974 var gutterLeft = d.gutters.clientLeft; 2975 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 2976 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; 2977 width[cm.options.gutters[i]] = n.clientWidth; 2978 } 2979 return {fixedPos: compensateForHScroll(d), 2980 gutterTotalWidth: d.gutters.offsetWidth, 2981 gutterLeft: left, 2982 gutterWidth: width, 2983 wrapperWidth: d.wrapper.clientWidth} 2984 } 2985 2986 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, 2987 // but using getBoundingClientRect to get a sub-pixel-accurate 2988 // result. 2989 function compensateForHScroll(display) { 2990 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left 2991 } 2992 2993 // Returns a function that estimates the height of a line, to use as 2994 // first approximation until the line becomes visible (and is thus 2995 // properly measurable). 2996 function estimateHeight(cm) { 2997 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; 2998 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); 2999 return function (line) { 3000 if (lineIsHidden(cm.doc, line)) { return 0 } 3001 3002 var widgetsHeight = 0; 3003 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { 3004 if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } 3005 } } 3006 3007 if (wrapping) 3008 { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } 3009 else 3010 { return widgetsHeight + th } 3011 } 3012 } 3013 3014 function estimateLineHeights(cm) { 3015 var doc = cm.doc, est = estimateHeight(cm); 3016 doc.iter(function (line) { 3017 var estHeight = est(line); 3018 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 3019 }); 3020 } 3021 3022 // Given a mouse event, find the corresponding position. If liberal 3023 // is false, it checks whether a gutter or scrollbar was clicked, 3024 // and returns null if it was. forRect is used by rectangular 3025 // selections, and tries to estimate a character position even for 3026 // coordinates beyond the right of the text. 3027 function posFromMouse(cm, e, liberal, forRect) { 3028 var display = cm.display; 3029 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } 3030 3031 var x, y, space = display.lineSpace.getBoundingClientRect(); 3032 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 3033 try { x = e.clientX - space.left; y = e.clientY - space.top; } 3034 catch (e) { return null } 3035 var coords = coordsChar(cm, x, y), line; 3036 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { 3037 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; 3038 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); 3039 } 3040 return coords 3041 } 3042 3043 // Find the view element corresponding to a given line. Return null 3044 // when the line isn't visible. 3045 function findViewIndex(cm, n) { 3046 if (n >= cm.display.viewTo) { return null } 3047 n -= cm.display.viewFrom; 3048 if (n < 0) { return null } 3049 var view = cm.display.view; 3050 for (var i = 0; i < view.length; i++) { 3051 n -= view[i].size; 3052 if (n < 0) { return i } 3053 } 3054 } 3055 3056 function updateSelection(cm) { 3057 cm.display.input.showSelection(cm.display.input.prepareSelection()); 3058 } 3059 3060 function prepareSelection(cm, primary) { 3061 var doc = cm.doc, result = {}; 3062 var curFragment = result.cursors = document.createDocumentFragment(); 3063 var selFragment = result.selection = document.createDocumentFragment(); 3064 3065 for (var i = 0; i < doc.sel.ranges.length; i++) { 3066 if (primary === false && i == doc.sel.primIndex) { continue } 3067 var range$$1 = doc.sel.ranges[i]; 3068 if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } 3069 var collapsed = range$$1.empty(); 3070 if (collapsed || cm.options.showCursorWhenSelecting) 3071 { drawSelectionCursor(cm, range$$1.head, curFragment); } 3072 if (!collapsed) 3073 { drawSelectionRange(cm, range$$1, selFragment); } 3074 } 3075 return result 3076 } 3077 3078 // Draws a cursor for the given range 3079 function drawSelectionCursor(cm, head, output) { 3080 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); 3081 3082 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); 3083 cursor.style.left = pos.left + "px"; 3084 cursor.style.top = pos.top + "px"; 3085 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 3086 3087 if (pos.other) { 3088 // Secondary cursor, shown when on a 'jump' in bi-directional text 3089 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); 3090 otherCursor.style.display = ""; 3091 otherCursor.style.left = pos.other.left + "px"; 3092 otherCursor.style.top = pos.other.top + "px"; 3093 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 3094 } 3095 } 3096 3097 // Draws the given range as a highlighted selection 3098 function drawSelectionRange(cm, range$$1, output) { 3099 var display = cm.display, doc = cm.doc; 3100 var fragment = document.createDocumentFragment(); 3101 var padding = paddingH(cm.display), leftSide = padding.left; 3102 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; 3103 3104 function add(left, top, width, bottom) { 3105 if (top < 0) { top = 0; } 3106 top = Math.round(top); 3107 bottom = Math.round(bottom); 3108 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"))); 3109 } 3110 3111 function drawForLine(line, fromArg, toArg) { 3112 var lineObj = getLine(doc, line); 3113 var lineLen = lineObj.text.length; 3114 var start, end; 3115 function coords(ch, bias) { 3116 return charCoords(cm, Pos(line, ch), "div", lineObj, bias) 3117 } 3118 3119 iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { 3120 var leftPos = coords(from, "left"), rightPos, left, right; 3121 if (from == to) { 3122 rightPos = leftPos; 3123 left = right = leftPos.left; 3124 } else { 3125 rightPos = coords(to - 1, "right"); 3126 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } 3127 left = leftPos.left; 3128 right = rightPos.right; 3129 } 3130 if (fromArg == null && from == 0) { left = leftSide; } 3131 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part 3132 add(left, leftPos.top, null, leftPos.bottom); 3133 left = leftSide; 3134 if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top); } 3135 } 3136 if (toArg == null && to == lineLen) { right = rightSide; } 3137 if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) 3138 { start = leftPos; } 3139 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) 3140 { end = rightPos; } 3141 if (left < leftSide + 1) { left = leftSide; } 3142 add(left, rightPos.top, right - left, rightPos.bottom); 3143 }); 3144 return {start: start, end: end} 3145 } 3146 3147 var sFrom = range$$1.from(), sTo = range$$1.to(); 3148 if (sFrom.line == sTo.line) { 3149 drawForLine(sFrom.line, sFrom.ch, sTo.ch); 3150 } else { 3151 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); 3152 var singleVLine = visualLine(fromLine) == visualLine(toLine); 3153 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; 3154 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; 3155 if (singleVLine) { 3156 if (leftEnd.top < rightStart.top - 2) { 3157 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); 3158 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); 3159 } else { 3160 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); 3161 } 3162 } 3163 if (leftEnd.bottom < rightStart.top) 3164 { add(leftSide, leftEnd.bottom, null, rightStart.top); } 3165 } 3166 3167 output.appendChild(fragment); 3168 } 3169 3170 // Cursor-blinking 3171 function restartBlink(cm) { 3172 if (!cm.state.focused) { return } 3173 var display = cm.display; 3174 clearInterval(display.blinker); 3175 var on = true; 3176 display.cursorDiv.style.visibility = ""; 3177 if (cm.options.cursorBlinkRate > 0) 3178 { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, 3179 cm.options.cursorBlinkRate); } 3180 else if (cm.options.cursorBlinkRate < 0) 3181 { display.cursorDiv.style.visibility = "hidden"; } 3182 } 3183 3184 function ensureFocus(cm) { 3185 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } 3186 } 3187 3188 function delayBlurEvent(cm) { 3189 cm.state.delayingBlurEvent = true; 3190 setTimeout(function () { if (cm.state.delayingBlurEvent) { 3191 cm.state.delayingBlurEvent = false; 3192 onBlur(cm); 3193 } }, 100); 3194 } 3195 3196 function onFocus(cm, e) { 3197 if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } 3198 3199 if (cm.options.readOnly == "nocursor") { return } 3200 if (!cm.state.focused) { 3201 signal(cm, "focus", cm, e); 3202 cm.state.focused = true; 3203 addClass(cm.display.wrapper, "CodeMirror-focused"); 3204 // This test prevents this from firing when a context 3205 // menu is closed (since the input reset would kill the 3206 // select-all detection hack) 3207 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { 3208 cm.display.input.reset(); 3209 if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 3210 } 3211 cm.display.input.receivedFocus(); 3212 } 3213 restartBlink(cm); 3214 } 3215 function onBlur(cm, e) { 3216 if (cm.state.delayingBlurEvent) { return } 3217 3218 if (cm.state.focused) { 3219 signal(cm, "blur", cm, e); 3220 cm.state.focused = false; 3221 rmClass(cm.display.wrapper, "CodeMirror-focused"); 3222 } 3223 clearInterval(cm.display.blinker); 3224 setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); 3225 } 3226 3227 // Read the actual heights of the rendered lines, and update their 3228 // stored heights to match. 3229 function updateHeightsInViewport(cm) { 3230 var display = cm.display; 3231 var prevBottom = display.lineDiv.offsetTop; 3232 for (var i = 0; i < display.view.length; i++) { 3233 var cur = display.view[i], height = (void 0); 3234 if (cur.hidden) { continue } 3235 if (ie && ie_version < 8) { 3236 var bot = cur.node.offsetTop + cur.node.offsetHeight; 3237 height = bot - prevBottom; 3238 prevBottom = bot; 3239 } else { 3240 var box = cur.node.getBoundingClientRect(); 3241 height = box.bottom - box.top; 3242 } 3243 var diff = cur.line.height - height; 3244 if (height < 2) { height = textHeight(display); } 3245 if (diff > .005 || diff < -.005) { 3246 updateLineHeight(cur.line, height); 3247 updateWidgetHeight(cur.line); 3248 if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) 3249 { updateWidgetHeight(cur.rest[j]); } } 3250 } 3251 } 3252 } 3253 3254 // Read and store the height of line widgets associated with the 3255 // given line. 3256 function updateWidgetHeight(line) { 3257 if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) 3258 { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } } 3259 } 3260 3261 // Compute the lines that are visible in a given viewport (defaults 3262 // the the current scroll position). viewport may contain top, 3263 // height, and ensure (see op.scrollToPos) properties. 3264 function visibleLines(display, doc, viewport) { 3265 var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; 3266 top = Math.floor(top - paddingTop(display)); 3267 var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; 3268 3269 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); 3270 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and 3271 // forces those lines into the viewport (if possible). 3272 if (viewport && viewport.ensure) { 3273 var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; 3274 if (ensureFrom < from) { 3275 from = ensureFrom; 3276 to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); 3277 } else if (Math.min(ensureTo, doc.lastLine()) >= to) { 3278 from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); 3279 to = ensureTo; 3280 } 3281 } 3282 return {from: from, to: Math.max(to, from + 1)} 3283 } 3284 3285 // Re-align line numbers and gutter marks to compensate for 3286 // horizontal scrolling. 3287 function alignHorizontally(cm) { 3288 var display = cm.display, view = display.view; 3289 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } 3290 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; 3291 var gutterW = display.gutters.offsetWidth, left = comp + "px"; 3292 for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { 3293 if (cm.options.fixedGutter) { 3294 if (view[i].gutter) 3295 { view[i].gutter.style.left = left; } 3296 if (view[i].gutterBackground) 3297 { view[i].gutterBackground.style.left = left; } 3298 } 3299 var align = view[i].alignable; 3300 if (align) { for (var j = 0; j < align.length; j++) 3301 { align[j].style.left = left; } } 3302 } } 3303 if (cm.options.fixedGutter) 3304 { display.gutters.style.left = (comp + gutterW) + "px"; } 3305 } 3306 3307 // Used to ensure that the line number gutter is still the right 3308 // size for the current document size. Returns true when an update 3309 // is needed. 3310 function maybeUpdateLineNumberWidth(cm) { 3311 if (!cm.options.lineNumbers) { return false } 3312 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 3313 if (last.length != display.lineNumChars) { 3314 var test = display.measure.appendChild(elt("div", [elt("div", last)], 3315 "CodeMirror-linenumber CodeMirror-gutter-elt")); 3316 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 3317 display.lineGutter.style.width = ""; 3318 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; 3319 display.lineNumWidth = display.lineNumInnerWidth + padding; 3320 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 3321 display.lineGutter.style.width = display.lineNumWidth + "px"; 3322 updateGutterSpace(cm); 3323 return true 3324 } 3325 return false 3326 } 3327 3328 // SCROLLING THINGS INTO VIEW 3329 3330 // If an editor sits on the top or bottom of the window, partially 3331 // scrolled out of view, this ensures that the cursor is visible. 3332 function maybeScrollWindow(cm, rect) { 3333 if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } 3334 3335 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; 3336 if (rect.top + box.top < 0) { doScroll = true; } 3337 else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } 3338 if (doScroll != null && !phantom) { 3339 var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); 3340 cm.display.lineSpace.appendChild(scrollNode); 3341 scrollNode.scrollIntoView(doScroll); 3342 cm.display.lineSpace.removeChild(scrollNode); 3343 } 3344 } 3345 3346 // Scroll a given position into view (immediately), verifying that 3347 // it actually became visible (as line heights are accurately 3348 // measured, the position of something may 'drift' during drawing). 3349 function scrollPosIntoView(cm, pos, end, margin) { 3350 if (margin == null) { margin = 0; } 3351 var rect; 3352 if (!cm.options.lineWrapping && pos == end) { 3353 // Set pos and end to the cursor positions around the character pos sticks to 3354 // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch 3355 // If pos == Pos(_, 0, "before"), pos and end are unchanged 3356 pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; 3357 end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; 3358 } 3359 for (var limit = 0; limit < 5; limit++) { 3360 var changed = false; 3361 var coords = cursorCoords(cm, pos); 3362 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); 3363 rect = {left: Math.min(coords.left, endCoords.left), 3364 top: Math.min(coords.top, endCoords.top) - margin, 3365 right: Math.max(coords.left, endCoords.left), 3366 bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; 3367 var scrollPos = calculateScrollPos(cm, rect); 3368 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 3369 if (scrollPos.scrollTop != null) { 3370 updateScrollTop(cm, scrollPos.scrollTop); 3371 if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } 3372 } 3373 if (scrollPos.scrollLeft != null) { 3374 setScrollLeft(cm, scrollPos.scrollLeft); 3375 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } 3376 } 3377 if (!changed) { break } 3378 } 3379 return rect 3380 } 3381 3382 // Scroll a given set of coordinates into view (immediately). 3383 function scrollIntoView(cm, rect) { 3384 var scrollPos = calculateScrollPos(cm, rect); 3385 if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } 3386 if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } 3387 } 3388 3389 // Calculate a new scroll position needed to scroll the given 3390 // rectangle into view. Returns an object with scrollTop and 3391 // scrollLeft properties. When these are undefined, the 3392 // vertical/horizontal position does not need to be adjusted. 3393 function calculateScrollPos(cm, rect) { 3394 var display = cm.display, snapMargin = textHeight(cm.display); 3395 if (rect.top < 0) { rect.top = 0; } 3396 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; 3397 var screen = displayHeight(cm), result = {}; 3398 if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } 3399 var docBottom = cm.doc.height + paddingVert(display); 3400 var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; 3401 if (rect.top < screentop) { 3402 result.scrollTop = atTop ? 0 : rect.top; 3403 } else if (rect.bottom > screentop + screen) { 3404 var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); 3405 if (newTop != screentop) { result.scrollTop = newTop; } 3406 } 3407 3408 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; 3409 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); 3410 var tooWide = rect.right - rect.left > screenw; 3411 if (tooWide) { rect.right = rect.left + screenw; } 3412 if (rect.left < 10) 3413 { result.scrollLeft = 0; } 3414 else if (rect.left < screenleft) 3415 { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } 3416 else if (rect.right > screenw + screenleft - 3) 3417 { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } 3418 return result 3419 } 3420 3421 // Store a relative adjustment to the scroll position in the current 3422 // operation (to be applied when the operation finishes). 3423 function addToScrollTop(cm, top) { 3424 if (top == null) { return } 3425 resolveScrollToPos(cm); 3426 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; 3427 } 3428 3429 // Make sure that at the end of the operation the current cursor is 3430 // shown. 3431 function ensureCursorVisible(cm) { 3432 resolveScrollToPos(cm); 3433 var cur = cm.getCursor(); 3434 cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; 3435 } 3436 3437 function scrollToCoords(cm, x, y) { 3438 if (x != null || y != null) { resolveScrollToPos(cm); } 3439 if (x != null) { cm.curOp.scrollLeft = x; } 3440 if (y != null) { cm.curOp.scrollTop = y; } 3441 } 3442 3443 function scrollToRange(cm, range$$1) { 3444 resolveScrollToPos(cm); 3445 cm.curOp.scrollToPos = range$$1; 3446 } 3447 3448 // When an operation has its scrollToPos property set, and another 3449 // scroll action is applied before the end of the operation, this 3450 // 'simulates' scrolling that position into view in a cheap way, so 3451 // that the effect of intermediate scroll commands is not ignored. 3452 function resolveScrollToPos(cm) { 3453 var range$$1 = cm.curOp.scrollToPos; 3454 if (range$$1) { 3455 cm.curOp.scrollToPos = null; 3456 var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); 3457 scrollToCoordsRange(cm, from, to, range$$1.margin); 3458 } 3459 } 3460 3461 function scrollToCoordsRange(cm, from, to, margin) { 3462 var sPos = calculateScrollPos(cm, { 3463 left: Math.min(from.left, to.left), 3464 top: Math.min(from.top, to.top) - margin, 3465 right: Math.max(from.right, to.right), 3466 bottom: Math.max(from.bottom, to.bottom) + margin 3467 }); 3468 scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); 3469 } 3470 3471 // Sync the scrollable area and scrollbars, ensure the viewport 3472 // covers the visible area. 3473 function updateScrollTop(cm, val) { 3474 if (Math.abs(cm.doc.scrollTop - val) < 2) { return } 3475 if (!gecko) { updateDisplaySimple(cm, {top: val}); } 3476 setScrollTop(cm, val, true); 3477 if (gecko) { updateDisplaySimple(cm); } 3478 startWorker(cm, 100); 3479 } 3480 3481 function setScrollTop(cm, val, forceScroll) { 3482 val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); 3483 if (cm.display.scroller.scrollTop == val && !forceScroll) { return } 3484 cm.doc.scrollTop = val; 3485 cm.display.scrollbars.setScrollTop(val); 3486 if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } 3487 } 3488 3489 // Sync scroller and scrollbar, ensure the gutter elements are 3490 // aligned. 3491 function setScrollLeft(cm, val, isScroller, forceScroll) { 3492 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 3493 if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } 3494 cm.doc.scrollLeft = val; 3495 alignHorizontally(cm); 3496 if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } 3497 cm.display.scrollbars.setScrollLeft(val); 3498 } 3499 3500 // SCROLLBARS 3501 3502 // Prepare DOM reads needed to update the scrollbars. Done in one 3503 // shot to minimize update/measure roundtrips. 3504 function measureForScrollbars(cm) { 3505 var d = cm.display, gutterW = d.gutters.offsetWidth; 3506 var docH = Math.round(cm.doc.height + paddingVert(cm.display)); 3507 return { 3508 clientHeight: d.scroller.clientHeight, 3509 viewHeight: d.wrapper.clientHeight, 3510 scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, 3511 viewWidth: d.wrapper.clientWidth, 3512 barLeft: cm.options.fixedGutter ? gutterW : 0, 3513 docHeight: docH, 3514 scrollHeight: docH + scrollGap(cm) + d.barHeight, 3515 nativeBarWidth: d.nativeBarWidth, 3516 gutterWidth: gutterW 3517 } 3518 } 3519 3520 var NativeScrollbars = function(place, scroll, cm) { 3521 this.cm = cm; 3522 var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); 3523 var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); 3524 place(vert); place(horiz); 3525 3526 on(vert, "scroll", function () { 3527 if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } 3528 }); 3529 on(horiz, "scroll", function () { 3530 if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } 3531 }); 3532 3533 this.checkedZeroWidth = false; 3534 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). 3535 if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } 3536 }; 3537 3538 NativeScrollbars.prototype.update = function (measure) { 3539 var needsH = measure.scrollWidth > measure.clientWidth + 1; 3540 var needsV = measure.scrollHeight > measure.clientHeight + 1; 3541 var sWidth = measure.nativeBarWidth; 3542 3543 if (needsV) { 3544 this.vert.style.display = "block"; 3545 this.vert.style.bottom = needsH ? sWidth + "px" : "0"; 3546 var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); 3547 // A bug in IE8 can cause this value to be negative, so guard it. 3548 this.vert.firstChild.style.height = 3549 Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; 3550 } else { 3551 this.vert.style.display = ""; 3552 this.vert.firstChild.style.height = "0"; 3553 } 3554 3555 if (needsH) { 3556 this.horiz.style.display = "block"; 3557 this.horiz.style.right = needsV ? sWidth + "px" : "0"; 3558 this.horiz.style.left = measure.barLeft + "px"; 3559 var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); 3560 this.horiz.firstChild.style.width = 3561 Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; 3562 } else { 3563 this.horiz.style.display = ""; 3564 this.horiz.firstChild.style.width = "0"; 3565 } 3566 3567 if (!this.checkedZeroWidth && measure.clientHeight > 0) { 3568 if (sWidth == 0) { this.zeroWidthHack(); } 3569 this.checkedZeroWidth = true; 3570 } 3571 3572 return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} 3573 }; 3574 3575 NativeScrollbars.prototype.setScrollLeft = function (pos) { 3576 if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } 3577 if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } 3578 }; 3579 3580 NativeScrollbars.prototype.setScrollTop = function (pos) { 3581 if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } 3582 if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } 3583 }; 3584 3585 NativeScrollbars.prototype.zeroWidthHack = function () { 3586 var w = mac && !mac_geMountainLion ? "12px" : "18px"; 3587 this.horiz.style.height = this.vert.style.width = w; 3588 this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; 3589 this.disableHoriz = new Delayed; 3590 this.disableVert = new Delayed; 3591 }; 3592 3593 NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { 3594 bar.style.pointerEvents = "auto"; 3595 function maybeDisable() { 3596 // To find out whether the scrollbar is still visible, we 3597 // check whether the element under the pixel in the bottom 3598 // right corner of the scrollbar box is the scrollbar box 3599 // itself (when the bar is still visible) or its filler child 3600 // (when the bar is hidden). If it is still visible, we keep 3601 // it enabled, if it's hidden, we disable pointer events. 3602 var box = bar.getBoundingClientRect(); 3603 var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) 3604 : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); 3605 if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } 3606 else { delay.set(1000, maybeDisable); } 3607 } 3608 delay.set(1000, maybeDisable); 3609 }; 3610 3611 NativeScrollbars.prototype.clear = function () { 3612 var parent = this.horiz.parentNode; 3613 parent.removeChild(this.horiz); 3614 parent.removeChild(this.vert); 3615 }; 3616 3617 var NullScrollbars = function () {}; 3618 3619 NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; 3620 NullScrollbars.prototype.setScrollLeft = function () {}; 3621 NullScrollbars.prototype.setScrollTop = function () {}; 3622 NullScrollbars.prototype.clear = function () {}; 3623 3624 function updateScrollbars(cm, measure) { 3625 if (!measure) { measure = measureForScrollbars(cm); } 3626 var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; 3627 updateScrollbarsInner(cm, measure); 3628 for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { 3629 if (startWidth != cm.display.barWidth && cm.options.lineWrapping) 3630 { updateHeightsInViewport(cm); } 3631 updateScrollbarsInner(cm, measureForScrollbars(cm)); 3632 startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; 3633 } 3634 } 3635 3636 // Re-synchronize the fake scrollbars with the actual size of the 3637 // content. 3638 function updateScrollbarsInner(cm, measure) { 3639 var d = cm.display; 3640 var sizes = d.scrollbars.update(measure); 3641 3642 d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; 3643 d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; 3644 d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; 3645 3646 if (sizes.right && sizes.bottom) { 3647 d.scrollbarFiller.style.display = "block"; 3648 d.scrollbarFiller.style.height = sizes.bottom + "px"; 3649 d.scrollbarFiller.style.width = sizes.right + "px"; 3650 } else { d.scrollbarFiller.style.display = ""; } 3651 if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { 3652 d.gutterFiller.style.display = "block"; 3653 d.gutterFiller.style.height = sizes.bottom + "px"; 3654 d.gutterFiller.style.width = measure.gutterWidth + "px"; 3655 } else { d.gutterFiller.style.display = ""; } 3656 } 3657 3658 var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; 3659 3660 function initScrollbars(cm) { 3661 if (cm.display.scrollbars) { 3662 cm.display.scrollbars.clear(); 3663 if (cm.display.scrollbars.addClass) 3664 { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3665 } 3666 3667 cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { 3668 cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); 3669 // Prevent clicks in the scrollbars from killing focus 3670 on(node, "mousedown", function () { 3671 if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } 3672 }); 3673 node.setAttribute("cm-not-content", "true"); 3674 }, function (pos, axis) { 3675 if (axis == "horizontal") { setScrollLeft(cm, pos); } 3676 else { updateScrollTop(cm, pos); } 3677 }, cm); 3678 if (cm.display.scrollbars.addClass) 3679 { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3680 } 3681 3682 // Operations are used to wrap a series of changes to the editor 3683 // state in such a way that each change won't have to update the 3684 // cursor and display (which would be awkward, slow, and 3685 // error-prone). Instead, display updates are batched and then all 3686 // combined and executed at once. 3687 3688 var nextOpId = 0; 3689 // Start a new operation. 3690 function startOperation(cm) { 3691 cm.curOp = { 3692 cm: cm, 3693 viewChanged: false, // Flag that indicates that lines might need to be redrawn 3694 startHeight: cm.doc.height, // Used to detect need to update scrollbar 3695 forceUpdate: false, // Used to force a redraw 3696 updateInput: null, // Whether to reset the input textarea 3697 typing: false, // Whether this reset should be careful to leave existing text (for compositing) 3698 changeObjs: null, // Accumulated changes, for firing change events 3699 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on 3700 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already 3701 selectionChanged: false, // Whether the selection needs to be redrawn 3702 updateMaxLine: false, // Set when the widest line needs to be determined anew 3703 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet 3704 scrollToPos: null, // Used to scroll to a specific position 3705 focus: false, 3706 id: ++nextOpId // Unique ID 3707 }; 3708 pushOperation(cm.curOp); 3709 } 3710 3711 // Finish an operation, updating the display and signalling delayed events 3712 function endOperation(cm) { 3713 var op = cm.curOp; 3714 finishOperation(op, function (group) { 3715 for (var i = 0; i < group.ops.length; i++) 3716 { group.ops[i].cm.curOp = null; } 3717 endOperations(group); 3718 }); 3719 } 3720 3721 // The DOM updates done when an operation finishes are batched so 3722 // that the minimum number of relayouts are required. 3723 function endOperations(group) { 3724 var ops = group.ops; 3725 for (var i = 0; i < ops.length; i++) // Read DOM 3726 { endOperation_R1(ops[i]); } 3727 for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) 3728 { endOperation_W1(ops[i$1]); } 3729 for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM 3730 { endOperation_R2(ops[i$2]); } 3731 for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) 3732 { endOperation_W2(ops[i$3]); } 3733 for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM 3734 { endOperation_finish(ops[i$4]); } 3735 } 3736 3737 function endOperation_R1(op) { 3738 var cm = op.cm, display = cm.display; 3739 maybeClipScrollbars(cm); 3740 if (op.updateMaxLine) { findMaxLine(cm); } 3741 3742 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || 3743 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || 3744 op.scrollToPos.to.line >= display.viewTo) || 3745 display.maxLineChanged && cm.options.lineWrapping; 3746 op.update = op.mustUpdate && 3747 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); 3748 } 3749 3750 function endOperation_W1(op) { 3751 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); 3752 } 3753 3754 function endOperation_R2(op) { 3755 var cm = op.cm, display = cm.display; 3756 if (op.updatedDisplay) { updateHeightsInViewport(cm); } 3757 3758 op.barMeasure = measureForScrollbars(cm); 3759 3760 // If the max line changed since it was last measured, measure it, 3761 // and ensure the document's width matches it. 3762 // updateDisplay_W2 will use these properties to do the actual resizing 3763 if (display.maxLineChanged && !cm.options.lineWrapping) { 3764 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; 3765 cm.display.sizerWidth = op.adjustWidthTo; 3766 op.barMeasure.scrollWidth = 3767 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); 3768 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); 3769 } 3770 3771 if (op.updatedDisplay || op.selectionChanged) 3772 { op.preparedSelection = display.input.prepareSelection(op.focus); } 3773 } 3774 3775 function endOperation_W2(op) { 3776 var cm = op.cm; 3777 3778 if (op.adjustWidthTo != null) { 3779 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; 3780 if (op.maxScrollLeft < cm.doc.scrollLeft) 3781 { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } 3782 cm.display.maxLineChanged = false; 3783 } 3784 3785 var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()); 3786 if (op.preparedSelection) 3787 { cm.display.input.showSelection(op.preparedSelection, takeFocus); } 3788 if (op.updatedDisplay || op.startHeight != cm.doc.height) 3789 { updateScrollbars(cm, op.barMeasure); } 3790 if (op.updatedDisplay) 3791 { setDocumentHeight(cm, op.barMeasure); } 3792 3793 if (op.selectionChanged) { restartBlink(cm); } 3794 3795 if (cm.state.focused && op.updateInput) 3796 { cm.display.input.reset(op.typing); } 3797 if (takeFocus) { ensureFocus(op.cm); } 3798 } 3799 3800 function endOperation_finish(op) { 3801 var cm = op.cm, display = cm.display, doc = cm.doc; 3802 3803 if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } 3804 3805 // Abort mouse wheel delta measurement, when scrolling explicitly 3806 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) 3807 { display.wheelStartX = display.wheelStartY = null; } 3808 3809 // Propagate the scroll position to the actual DOM scroller 3810 if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } 3811 3812 if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } 3813 // If we need to scroll a specific position into view, do so. 3814 if (op.scrollToPos) { 3815 var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), 3816 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); 3817 maybeScrollWindow(cm, rect); 3818 } 3819 3820 // Fire events for markers that are hidden/unidden by editing or 3821 // undoing 3822 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 3823 if (hidden) { for (var i = 0; i < hidden.length; ++i) 3824 { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } 3825 if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) 3826 { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } 3827 3828 if (display.wrapper.offsetHeight) 3829 { doc.scrollTop = cm.display.scroller.scrollTop; } 3830 3831 // Fire change events, and delayed event handlers 3832 if (op.changeObjs) 3833 { signal(cm, "changes", cm, op.changeObjs); } 3834 if (op.update) 3835 { op.update.finish(); } 3836 } 3837 3838 // Run the given function in an operation 3839 function runInOp(cm, f) { 3840 if (cm.curOp) { return f() } 3841 startOperation(cm); 3842 try { return f() } 3843 finally { endOperation(cm); } 3844 } 3845 // Wraps a function in an operation. Returns the wrapped function. 3846 function operation(cm, f) { 3847 return function() { 3848 if (cm.curOp) { return f.apply(cm, arguments) } 3849 startOperation(cm); 3850 try { return f.apply(cm, arguments) } 3851 finally { endOperation(cm); } 3852 } 3853 } 3854 // Used to add methods to editor and doc instances, wrapping them in 3855 // operations. 3856 function methodOp(f) { 3857 return function() { 3858 if (this.curOp) { return f.apply(this, arguments) } 3859 startOperation(this); 3860 try { return f.apply(this, arguments) } 3861 finally { endOperation(this); } 3862 } 3863 } 3864 function docMethodOp(f) { 3865 return function() { 3866 var cm = this.cm; 3867 if (!cm || cm.curOp) { return f.apply(this, arguments) } 3868 startOperation(cm); 3869 try { return f.apply(this, arguments) } 3870 finally { endOperation(cm); } 3871 } 3872 } 3873 3874 // Updates the display.view data structure for a given change to the 3875 // document. From and to are in pre-change coordinates. Lendiff is 3876 // the amount of lines added or subtracted by the change. This is 3877 // used for changes that span multiple lines, or change the way 3878 // lines are divided into visual lines. regLineChange (below) 3879 // registers single-line changes. 3880 function regChange(cm, from, to, lendiff) { 3881 if (from == null) { from = cm.doc.first; } 3882 if (to == null) { to = cm.doc.first + cm.doc.size; } 3883 if (!lendiff) { lendiff = 0; } 3884 3885 var display = cm.display; 3886 if (lendiff && to < display.viewTo && 3887 (display.updateLineNumbers == null || display.updateLineNumbers > from)) 3888 { display.updateLineNumbers = from; } 3889 3890 cm.curOp.viewChanged = true; 3891 3892 if (from >= display.viewTo) { // Change after 3893 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) 3894 { resetView(cm); } 3895 } else if (to <= display.viewFrom) { // Change before 3896 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { 3897 resetView(cm); 3898 } else { 3899 display.viewFrom += lendiff; 3900 display.viewTo += lendiff; 3901 } 3902 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap 3903 resetView(cm); 3904 } else if (from <= display.viewFrom) { // Top overlap 3905 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); 3906 if (cut) { 3907 display.view = display.view.slice(cut.index); 3908 display.viewFrom = cut.lineN; 3909 display.viewTo += lendiff; 3910 } else { 3911 resetView(cm); 3912 } 3913 } else if (to >= display.viewTo) { // Bottom overlap 3914 var cut$1 = viewCuttingPoint(cm, from, from, -1); 3915 if (cut$1) { 3916 display.view = display.view.slice(0, cut$1.index); 3917 display.viewTo = cut$1.lineN; 3918 } else { 3919 resetView(cm); 3920 } 3921 } else { // Gap in the middle 3922 var cutTop = viewCuttingPoint(cm, from, from, -1); 3923 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); 3924 if (cutTop && cutBot) { 3925 display.view = display.view.slice(0, cutTop.index) 3926 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) 3927 .concat(display.view.slice(cutBot.index)); 3928 display.viewTo += lendiff; 3929 } else { 3930 resetView(cm); 3931 } 3932 } 3933 3934 var ext = display.externalMeasured; 3935 if (ext) { 3936 if (to < ext.lineN) 3937 { ext.lineN += lendiff; } 3938 else if (from < ext.lineN + ext.size) 3939 { display.externalMeasured = null; } 3940 } 3941 } 3942 3943 // Register a change to a single line. Type must be one of "text", 3944 // "gutter", "class", "widget" 3945 function regLineChange(cm, line, type) { 3946 cm.curOp.viewChanged = true; 3947 var display = cm.display, ext = cm.display.externalMeasured; 3948 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) 3949 { display.externalMeasured = null; } 3950 3951 if (line < display.viewFrom || line >= display.viewTo) { return } 3952 var lineView = display.view[findViewIndex(cm, line)]; 3953 if (lineView.node == null) { return } 3954 var arr = lineView.changes || (lineView.changes = []); 3955 if (indexOf(arr, type) == -1) { arr.push(type); } 3956 } 3957 3958 // Clear the view. 3959 function resetView(cm) { 3960 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; 3961 cm.display.view = []; 3962 cm.display.viewOffset = 0; 3963 } 3964 3965 function viewCuttingPoint(cm, oldN, newN, dir) { 3966 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; 3967 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) 3968 { return {index: index, lineN: newN} } 3969 var n = cm.display.viewFrom; 3970 for (var i = 0; i < index; i++) 3971 { n += view[i].size; } 3972 if (n != oldN) { 3973 if (dir > 0) { 3974 if (index == view.length - 1) { return null } 3975 diff = (n + view[index].size) - oldN; 3976 index++; 3977 } else { 3978 diff = n - oldN; 3979 } 3980 oldN += diff; newN += diff; 3981 } 3982 while (visualLineNo(cm.doc, newN) != newN) { 3983 if (index == (dir < 0 ? 0 : view.length - 1)) { return null } 3984 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; 3985 index += dir; 3986 } 3987 return {index: index, lineN: newN} 3988 } 3989 3990 // Force the view to cover a given range, adding empty view element 3991 // or clipping off existing ones as needed. 3992 function adjustView(cm, from, to) { 3993 var display = cm.display, view = display.view; 3994 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { 3995 display.view = buildViewArray(cm, from, to); 3996 display.viewFrom = from; 3997 } else { 3998 if (display.viewFrom > from) 3999 { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } 4000 else if (display.viewFrom < from) 4001 { display.view = display.view.slice(findViewIndex(cm, from)); } 4002 display.viewFrom = from; 4003 if (display.viewTo < to) 4004 { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } 4005 else if (display.viewTo > to) 4006 { display.view = display.view.slice(0, findViewIndex(cm, to)); } 4007 } 4008 display.viewTo = to; 4009 } 4010 4011 // Count the number of lines in the view whose DOM representation is 4012 // out of date (or nonexistent). 4013 function countDirtyView(cm) { 4014 var view = cm.display.view, dirty = 0; 4015 for (var i = 0; i < view.length; i++) { 4016 var lineView = view[i]; 4017 if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } 4018 } 4019 return dirty 4020 } 4021 4022 // HIGHLIGHT WORKER 4023 4024 function startWorker(cm, time) { 4025 if (cm.doc.highlightFrontier < cm.display.viewTo) 4026 { cm.state.highlight.set(time, bind(highlightWorker, cm)); } 4027 } 4028 4029 function highlightWorker(cm) { 4030 var doc = cm.doc; 4031 if (doc.highlightFrontier >= cm.display.viewTo) { return } 4032 var end = +new Date + cm.options.workTime; 4033 var context = getContextBefore(cm, doc.highlightFrontier); 4034 var changedLines = []; 4035 4036 doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { 4037 if (context.line >= cm.display.viewFrom) { // Visible 4038 var oldStyles = line.styles; 4039 var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; 4040 var highlighted = highlightLine(cm, line, context, true); 4041 if (resetState) { context.state = resetState; } 4042 line.styles = highlighted.styles; 4043 var oldCls = line.styleClasses, newCls = highlighted.classes; 4044 if (newCls) { line.styleClasses = newCls; } 4045 else if (oldCls) { line.styleClasses = null; } 4046 var ischange = !oldStyles || oldStyles.length != line.styles.length || 4047 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); 4048 for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } 4049 if (ischange) { changedLines.push(context.line); } 4050 line.stateAfter = context.save(); 4051 context.nextLine(); 4052 } else { 4053 if (line.text.length <= cm.options.maxHighlightLength) 4054 { processLine(cm, line.text, context); } 4055 line.stateAfter = context.line % 5 == 0 ? context.save() : null; 4056 context.nextLine(); 4057 } 4058 if (+new Date > end) { 4059 startWorker(cm, cm.options.workDelay); 4060 return true 4061 } 4062 }); 4063 doc.highlightFrontier = context.line; 4064 doc.modeFrontier = Math.max(doc.modeFrontier, context.line); 4065 if (changedLines.length) { runInOp(cm, function () { 4066 for (var i = 0; i < changedLines.length; i++) 4067 { regLineChange(cm, changedLines[i], "text"); } 4068 }); } 4069 } 4070 4071 // DISPLAY DRAWING 4072 4073 var DisplayUpdate = function(cm, viewport, force) { 4074 var display = cm.display; 4075 4076 this.viewport = viewport; 4077 // Store some values that we'll need later (but don't want to force a relayout for) 4078 this.visible = visibleLines(display, cm.doc, viewport); 4079 this.editorIsHidden = !display.wrapper.offsetWidth; 4080 this.wrapperHeight = display.wrapper.clientHeight; 4081 this.wrapperWidth = display.wrapper.clientWidth; 4082 this.oldDisplayWidth = displayWidth(cm); 4083 this.force = force; 4084 this.dims = getDimensions(cm); 4085 this.events = []; 4086 }; 4087 4088 DisplayUpdate.prototype.signal = function (emitter, type) { 4089 if (hasHandler(emitter, type)) 4090 { this.events.push(arguments); } 4091 }; 4092 DisplayUpdate.prototype.finish = function () { 4093 var this$1 = this; 4094 4095 for (var i = 0; i < this.events.length; i++) 4096 { signal.apply(null, this$1.events[i]); } 4097 }; 4098 4099 function maybeClipScrollbars(cm) { 4100 var display = cm.display; 4101 if (!display.scrollbarsClipped && display.scroller.offsetWidth) { 4102 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; 4103 display.heightForcer.style.height = scrollGap(cm) + "px"; 4104 display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; 4105 display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; 4106 display.scrollbarsClipped = true; 4107 } 4108 } 4109 4110 function selectionSnapshot(cm) { 4111 if (cm.hasFocus()) { return null } 4112 var active = activeElt(); 4113 if (!active || !contains(cm.display.lineDiv, active)) { return null } 4114 var result = {activeElt: active}; 4115 if (window.getSelection) { 4116 var sel = window.getSelection(); 4117 if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { 4118 result.anchorNode = sel.anchorNode; 4119 result.anchorOffset = sel.anchorOffset; 4120 result.focusNode = sel.focusNode; 4121 result.focusOffset = sel.focusOffset; 4122 } 4123 } 4124 return result 4125 } 4126 4127 function restoreSelection(snapshot) { 4128 if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } 4129 snapshot.activeElt.focus(); 4130 if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { 4131 var sel = window.getSelection(), range$$1 = document.createRange(); 4132 range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); 4133 range$$1.collapse(false); 4134 sel.removeAllRanges(); 4135 sel.addRange(range$$1); 4136 sel.extend(snapshot.focusNode, snapshot.focusOffset); 4137 } 4138 } 4139 4140 // Does the actual updating of the line display. Bails out 4141 // (returning false) when there is nothing to be done and forced is 4142 // false. 4143 function updateDisplayIfNeeded(cm, update) { 4144 var display = cm.display, doc = cm.doc; 4145 4146 if (update.editorIsHidden) { 4147 resetView(cm); 4148 return false 4149 } 4150 4151 // Bail out if the visible area is already rendered and nothing changed. 4152 if (!update.force && 4153 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && 4154 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && 4155 display.renderedView == display.view && countDirtyView(cm) == 0) 4156 { return false } 4157 4158 if (maybeUpdateLineNumberWidth(cm)) { 4159 resetView(cm); 4160 update.dims = getDimensions(cm); 4161 } 4162 4163 // Compute a suitable new viewport (from & to) 4164 var end = doc.first + doc.size; 4165 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); 4166 var to = Math.min(end, update.visible.to + cm.options.viewportMargin); 4167 if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } 4168 if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } 4169 if (sawCollapsedSpans) { 4170 from = visualLineNo(cm.doc, from); 4171 to = visualLineEndNo(cm.doc, to); 4172 } 4173 4174 var different = from != display.viewFrom || to != display.viewTo || 4175 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; 4176 adjustView(cm, from, to); 4177 4178 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); 4179 // Position the mover div to align with the current scroll position 4180 cm.display.mover.style.top = display.viewOffset + "px"; 4181 4182 var toUpdate = countDirtyView(cm); 4183 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && 4184 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) 4185 { return false } 4186 4187 // For big changes, we hide the enclosing element during the 4188 // update, since that speeds up the operations on most browsers. 4189 var selSnapshot = selectionSnapshot(cm); 4190 if (toUpdate > 4) { display.lineDiv.style.display = "none"; } 4191 patchDisplay(cm, display.updateLineNumbers, update.dims); 4192 if (toUpdate > 4) { display.lineDiv.style.display = ""; } 4193 display.renderedView = display.view; 4194 // There might have been a widget with a focused element that got 4195 // hidden or updated, if so re-focus it. 4196 restoreSelection(selSnapshot); 4197 4198 // Prevent selection and cursors from interfering with the scroll 4199 // width and height. 4200 removeChildren(display.cursorDiv); 4201 removeChildren(display.selectionDiv); 4202 display.gutters.style.height = display.sizer.style.minHeight = 0; 4203 4204 if (different) { 4205 display.lastWrapHeight = update.wrapperHeight; 4206 display.lastWrapWidth = update.wrapperWidth; 4207 startWorker(cm, 400); 4208 } 4209 4210 display.updateLineNumbers = null; 4211 4212 return true 4213 } 4214 4215 function postUpdateDisplay(cm, update) { 4216 var viewport = update.viewport; 4217 4218 for (var first = true;; first = false) { 4219 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { 4220 // Clip forced viewport to actual scrollable area. 4221 if (viewport && viewport.top != null) 4222 { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } 4223 // Updated line heights might result in the drawn area not 4224 // actually covering the viewport. Keep looping until it does. 4225 update.visible = visibleLines(cm.display, cm.doc, viewport); 4226 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) 4227 { break } 4228 } 4229 if (!updateDisplayIfNeeded(cm, update)) { break } 4230 updateHeightsInViewport(cm); 4231 var barMeasure = measureForScrollbars(cm); 4232 updateSelection(cm); 4233 updateScrollbars(cm, barMeasure); 4234 setDocumentHeight(cm, barMeasure); 4235 update.force = false; 4236 } 4237 4238 update.signal(cm, "update", cm); 4239 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { 4240 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); 4241 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; 4242 } 4243 } 4244 4245 function updateDisplaySimple(cm, viewport) { 4246 var update = new DisplayUpdate(cm, viewport); 4247 if (updateDisplayIfNeeded(cm, update)) { 4248 updateHeightsInViewport(cm); 4249 postUpdateDisplay(cm, update); 4250 var barMeasure = measureForScrollbars(cm); 4251 updateSelection(cm); 4252 updateScrollbars(cm, barMeasure); 4253 setDocumentHeight(cm, barMeasure); 4254 update.finish(); 4255 } 4256 } 4257 4258 // Sync the actual display DOM structure with display.view, removing 4259 // nodes for lines that are no longer in view, and creating the ones 4260 // that are not there yet, and updating the ones that are out of 4261 // date. 4262 function patchDisplay(cm, updateNumbersFrom, dims) { 4263 var display = cm.display, lineNumbers = cm.options.lineNumbers; 4264 var container = display.lineDiv, cur = container.firstChild; 4265 4266 function rm(node) { 4267 var next = node.nextSibling; 4268 // Works around a throw-scroll bug in OS X Webkit 4269 if (webkit && mac && cm.display.currentWheelTarget == node) 4270 { node.style.display = "none"; } 4271 else 4272 { node.parentNode.removeChild(node); } 4273 return next 4274 } 4275 4276 var view = display.view, lineN = display.viewFrom; 4277 // Loop over the elements in the view, syncing cur (the DOM nodes 4278 // in display.lineDiv) with the view as we go. 4279 for (var i = 0; i < view.length; i++) { 4280 var lineView = view[i]; 4281 if (lineView.hidden) { 4282 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet 4283 var node = buildLineElement(cm, lineView, lineN, dims); 4284 container.insertBefore(node, cur); 4285 } else { // Already drawn 4286 while (cur != lineView.node) { cur = rm(cur); } 4287 var updateNumber = lineNumbers && updateNumbersFrom != null && 4288 updateNumbersFrom <= lineN && lineView.lineNumber; 4289 if (lineView.changes) { 4290 if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } 4291 updateLineForChanges(cm, lineView, lineN, dims); 4292 } 4293 if (updateNumber) { 4294 removeChildren(lineView.lineNumber); 4295 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); 4296 } 4297 cur = lineView.node.nextSibling; 4298 } 4299 lineN += lineView.size; 4300 } 4301 while (cur) { cur = rm(cur); } 4302 } 4303 4304 function updateGutterSpace(cm) { 4305 var width = cm.display.gutters.offsetWidth; 4306 cm.display.sizer.style.marginLeft = width + "px"; 4307 } 4308 4309 function setDocumentHeight(cm, measure) { 4310 cm.display.sizer.style.minHeight = measure.docHeight + "px"; 4311 cm.display.heightForcer.style.top = measure.docHeight + "px"; 4312 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; 4313 } 4314 4315 // Rebuild the gutter elements, ensure the margin to the left of the 4316 // code matches their width. 4317 function updateGutters(cm) { 4318 var gutters = cm.display.gutters, specs = cm.options.gutters; 4319 removeChildren(gutters); 4320 var i = 0; 4321 for (; i < specs.length; ++i) { 4322 var gutterClass = specs[i]; 4323 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); 4324 if (gutterClass == "CodeMirror-linenumbers") { 4325 cm.display.lineGutter = gElt; 4326 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; 4327 } 4328 } 4329 gutters.style.display = i ? "" : "none"; 4330 updateGutterSpace(cm); 4331 } 4332 4333 // Make sure the gutters options contains the element 4334 // "CodeMirror-linenumbers" when the lineNumbers option is true. 4335 function setGuttersForLineNumbers(options) { 4336 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); 4337 if (found == -1 && options.lineNumbers) { 4338 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); 4339 } else if (found > -1 && !options.lineNumbers) { 4340 options.gutters = options.gutters.slice(0); 4341 options.gutters.splice(found, 1); 4342 } 4343 } 4344 4345 // Since the delta values reported on mouse wheel events are 4346 // unstandardized between browsers and even browser versions, and 4347 // generally horribly unpredictable, this code starts by measuring 4348 // the scroll effect that the first few mouse wheel events have, 4349 // and, from that, detects the way it can convert deltas to pixel 4350 // offsets afterwards. 4351 // 4352 // The reason we want to know the amount a wheel event will scroll 4353 // is that it gives us a chance to update the display before the 4354 // actual scrolling happens, reducing flickering. 4355 4356 var wheelSamples = 0; 4357 var wheelPixelsPerUnit = null; 4358 // Fill in a browser-detected starting value on browsers where we 4359 // know one. These don't have to be accurate -- the result of them 4360 // being wrong would just be a slight flicker on the first wheel 4361 // scroll (if it is large enough). 4362 if (ie) { wheelPixelsPerUnit = -.53; } 4363 else if (gecko) { wheelPixelsPerUnit = 15; } 4364 else if (chrome) { wheelPixelsPerUnit = -.7; } 4365 else if (safari) { wheelPixelsPerUnit = -1/3; } 4366 4367 function wheelEventDelta(e) { 4368 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 4369 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } 4370 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } 4371 else if (dy == null) { dy = e.wheelDelta; } 4372 return {x: dx, y: dy} 4373 } 4374 function wheelEventPixels(e) { 4375 var delta = wheelEventDelta(e); 4376 delta.x *= wheelPixelsPerUnit; 4377 delta.y *= wheelPixelsPerUnit; 4378 return delta 4379 } 4380 4381 function onScrollWheel(cm, e) { 4382 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; 4383 4384 var display = cm.display, scroll = display.scroller; 4385 // Quit if there's nothing to scroll here 4386 var canScrollX = scroll.scrollWidth > scroll.clientWidth; 4387 var canScrollY = scroll.scrollHeight > scroll.clientHeight; 4388 if (!(dx && canScrollX || dy && canScrollY)) { return } 4389 4390 // Webkit browsers on OS X abort momentum scrolls when the target 4391 // of the scroll event is removed from the scrollable element. 4392 // This hack (see related code in patchDisplay) makes sure the 4393 // element is kept around. 4394 if (dy && mac && webkit) { 4395 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { 4396 for (var i = 0; i < view.length; i++) { 4397 if (view[i].node == cur) { 4398 cm.display.currentWheelTarget = cur; 4399 break outer 4400 } 4401 } 4402 } 4403 } 4404 4405 // On some browsers, horizontal scrolling will cause redraws to 4406 // happen before the gutter has been realigned, causing it to 4407 // wriggle around in a most unseemly way. When we have an 4408 // estimated pixels/delta value, we just handle horizontal 4409 // scrolling entirely here. It'll be slightly off from native, but 4410 // better than glitching out. 4411 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { 4412 if (dy && canScrollY) 4413 { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } 4414 setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); 4415 // Only prevent default scrolling if vertical scrolling is 4416 // actually possible. Otherwise, it causes vertical scroll 4417 // jitter on OSX trackpads when deltaX is small and deltaY 4418 // is large (issue #3579) 4419 if (!dy || (dy && canScrollY)) 4420 { e_preventDefault(e); } 4421 display.wheelStartX = null; // Abort measurement, if in progress 4422 return 4423 } 4424 4425 // 'Project' the visible viewport to cover the area that is being 4426 // scrolled into view (if we know enough to estimate it). 4427 if (dy && wheelPixelsPerUnit != null) { 4428 var pixels = dy * wheelPixelsPerUnit; 4429 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 4430 if (pixels < 0) { top = Math.max(0, top + pixels - 50); } 4431 else { bot = Math.min(cm.doc.height, bot + pixels + 50); } 4432 updateDisplaySimple(cm, {top: top, bottom: bot}); 4433 } 4434 4435 if (wheelSamples < 20) { 4436 if (display.wheelStartX == null) { 4437 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 4438 display.wheelDX = dx; display.wheelDY = dy; 4439 setTimeout(function () { 4440 if (display.wheelStartX == null) { return } 4441 var movedX = scroll.scrollLeft - display.wheelStartX; 4442 var movedY = scroll.scrollTop - display.wheelStartY; 4443 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 4444 (movedX && display.wheelDX && movedX / display.wheelDX); 4445 display.wheelStartX = display.wheelStartY = null; 4446 if (!sample) { return } 4447 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 4448 ++wheelSamples; 4449 }, 200); 4450 } else { 4451 display.wheelDX += dx; display.wheelDY += dy; 4452 } 4453 } 4454 } 4455 4456 // Selection objects are immutable. A new one is created every time 4457 // the selection changes. A selection is one or more non-overlapping 4458 // (and non-touching) ranges, sorted, and an integer that indicates 4459 // which one is the primary selection (the one that's scrolled into 4460 // view, that getCursor returns, etc). 4461 var Selection = function(ranges, primIndex) { 4462 this.ranges = ranges; 4463 this.primIndex = primIndex; 4464 }; 4465 4466 Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; 4467 4468 Selection.prototype.equals = function (other) { 4469 var this$1 = this; 4470 4471 if (other == this) { return true } 4472 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } 4473 for (var i = 0; i < this.ranges.length; i++) { 4474 var here = this$1.ranges[i], there = other.ranges[i]; 4475 if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } 4476 } 4477 return true 4478 }; 4479 4480 Selection.prototype.deepCopy = function () { 4481 var this$1 = this; 4482 4483 var out = []; 4484 for (var i = 0; i < this.ranges.length; i++) 4485 { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } 4486 return new Selection(out, this.primIndex) 4487 }; 4488 4489 Selection.prototype.somethingSelected = function () { 4490 var this$1 = this; 4491 4492 for (var i = 0; i < this.ranges.length; i++) 4493 { if (!this$1.ranges[i].empty()) { return true } } 4494 return false 4495 }; 4496 4497 Selection.prototype.contains = function (pos, end) { 4498 var this$1 = this; 4499 4500 if (!end) { end = pos; } 4501 for (var i = 0; i < this.ranges.length; i++) { 4502 var range = this$1.ranges[i]; 4503 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) 4504 { return i } 4505 } 4506 return -1 4507 }; 4508 4509 var Range = function(anchor, head) { 4510 this.anchor = anchor; this.head = head; 4511 }; 4512 4513 Range.prototype.from = function () { return minPos(this.anchor, this.head) }; 4514 Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; 4515 Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; 4516 4517 // Take an unsorted, potentially overlapping set of ranges, and 4518 // build a selection out of it. 'Consumes' ranges array (modifying 4519 // it). 4520 function normalizeSelection(ranges, primIndex) { 4521 var prim = ranges[primIndex]; 4522 ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); 4523 primIndex = indexOf(ranges, prim); 4524 for (var i = 1; i < ranges.length; i++) { 4525 var cur = ranges[i], prev = ranges[i - 1]; 4526 if (cmp(prev.to(), cur.from()) >= 0) { 4527 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); 4528 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; 4529 if (i <= primIndex) { --primIndex; } 4530 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); 4531 } 4532 } 4533 return new Selection(ranges, primIndex) 4534 } 4535 4536 function simpleSelection(anchor, head) { 4537 return new Selection([new Range(anchor, head || anchor)], 0) 4538 } 4539 4540 // Compute the position of the end of a change (its 'to' property 4541 // refers to the pre-change end). 4542 function changeEnd(change) { 4543 if (!change.text) { return change.to } 4544 return Pos(change.from.line + change.text.length - 1, 4545 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) 4546 } 4547 4548 // Adjust a position to refer to the post-change position of the 4549 // same text, or the end of the change if the change covers it. 4550 function adjustForChange(pos, change) { 4551 if (cmp(pos, change.from) < 0) { return pos } 4552 if (cmp(pos, change.to) <= 0) { return changeEnd(change) } 4553 4554 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 4555 if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } 4556 return Pos(line, ch) 4557 } 4558 4559 function computeSelAfterChange(doc, change) { 4560 var out = []; 4561 for (var i = 0; i < doc.sel.ranges.length; i++) { 4562 var range = doc.sel.ranges[i]; 4563 out.push(new Range(adjustForChange(range.anchor, change), 4564 adjustForChange(range.head, change))); 4565 } 4566 return normalizeSelection(out, doc.sel.primIndex) 4567 } 4568 4569 function offsetPos(pos, old, nw) { 4570 if (pos.line == old.line) 4571 { return Pos(nw.line, pos.ch - old.ch + nw.ch) } 4572 else 4573 { return Pos(nw.line + (pos.line - old.line), pos.ch) } 4574 } 4575 4576 // Used by replaceSelections to allow moving the selection to the 4577 // start or around the replaced test. Hint may be "start" or "around". 4578 function computeReplacedSel(doc, changes, hint) { 4579 var out = []; 4580 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; 4581 for (var i = 0; i < changes.length; i++) { 4582 var change = changes[i]; 4583 var from = offsetPos(change.from, oldPrev, newPrev); 4584 var to = offsetPos(changeEnd(change), oldPrev, newPrev); 4585 oldPrev = change.to; 4586 newPrev = to; 4587 if (hint == "around") { 4588 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; 4589 out[i] = new Range(inv ? to : from, inv ? from : to); 4590 } else { 4591 out[i] = new Range(from, from); 4592 } 4593 } 4594 return new Selection(out, doc.sel.primIndex) 4595 } 4596 4597 // Used to get the editor into a consistent state again when options change. 4598 4599 function loadMode(cm) { 4600 cm.doc.mode = getMode(cm.options, cm.doc.modeOption); 4601 resetModeState(cm); 4602 } 4603 4604 function resetModeState(cm) { 4605 cm.doc.iter(function (line) { 4606 if (line.stateAfter) { line.stateAfter = null; } 4607 if (line.styles) { line.styles = null; } 4608 }); 4609 cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; 4610 startWorker(cm, 100); 4611 cm.state.modeGen++; 4612 if (cm.curOp) { regChange(cm); } 4613 } 4614 4615 // DOCUMENT DATA STRUCTURE 4616 4617 // By default, updates that start and end at the beginning of a line 4618 // are treated specially, in order to make the association of line 4619 // widgets and marker elements with the text behave more intuitive. 4620 function isWholeLineUpdate(doc, change) { 4621 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && 4622 (!doc.cm || doc.cm.options.wholeLineUpdateBefore) 4623 } 4624 4625 // Perform a change on the document data structure. 4626 function updateDoc(doc, change, markedSpans, estimateHeight$$1) { 4627 function spansFor(n) {return markedSpans ? markedSpans[n] : null} 4628 function update(line, text, spans) { 4629 updateLine(line, text, spans, estimateHeight$$1); 4630 signalLater(line, "change", line, change); 4631 } 4632 function linesFor(start, end) { 4633 var result = []; 4634 for (var i = start; i < end; ++i) 4635 { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } 4636 return result 4637 } 4638 4639 var from = change.from, to = change.to, text = change.text; 4640 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 4641 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 4642 4643 // Adjust the line structure 4644 if (change.full) { 4645 doc.insert(0, linesFor(0, text.length)); 4646 doc.remove(text.length, doc.size - text.length); 4647 } else if (isWholeLineUpdate(doc, change)) { 4648 // This is a whole-line replace. Treated specially to make 4649 // sure line objects move the way they are supposed to. 4650 var added = linesFor(0, text.length - 1); 4651 update(lastLine, lastLine.text, lastSpans); 4652 if (nlines) { doc.remove(from.line, nlines); } 4653 if (added.length) { doc.insert(from.line, added); } 4654 } else if (firstLine == lastLine) { 4655 if (text.length == 1) { 4656 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); 4657 } else { 4658 var added$1 = linesFor(1, text.length - 1); 4659 added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); 4660 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4661 doc.insert(from.line + 1, added$1); 4662 } 4663 } else if (text.length == 1) { 4664 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); 4665 doc.remove(from.line + 1, nlines); 4666 } else { 4667 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4668 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); 4669 var added$2 = linesFor(1, text.length - 1); 4670 if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } 4671 doc.insert(from.line + 1, added$2); 4672 } 4673 4674 signalLater(doc, "change", doc, change); 4675 } 4676 4677 // Call f for all linked documents. 4678 function linkedDocs(doc, f, sharedHistOnly) { 4679 function propagate(doc, skip, sharedHist) { 4680 if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { 4681 var rel = doc.linked[i]; 4682 if (rel.doc == skip) { continue } 4683 var shared = sharedHist && rel.sharedHist; 4684 if (sharedHistOnly && !shared) { continue } 4685 f(rel.doc, shared); 4686 propagate(rel.doc, doc, shared); 4687 } } 4688 } 4689 propagate(doc, null, true); 4690 } 4691 4692 // Attach a document to an editor. 4693 function attachDoc(cm, doc) { 4694 if (doc.cm) { throw new Error("This document is already in use.") } 4695 cm.doc = doc; 4696 doc.cm = cm; 4697 estimateLineHeights(cm); 4698 loadMode(cm); 4699 setDirectionClass(cm); 4700 if (!cm.options.lineWrapping) { findMaxLine(cm); } 4701 cm.options.mode = doc.modeOption; 4702 regChange(cm); 4703 } 4704 4705 function setDirectionClass(cm) { 4706 (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); 4707 } 4708 4709 function directionChanged(cm) { 4710 runInOp(cm, function () { 4711 setDirectionClass(cm); 4712 regChange(cm); 4713 }); 4714 } 4715 4716 function History(startGen) { 4717 // Arrays of change events and selections. Doing something adds an 4718 // event to done and clears undo. Undoing moves events from done 4719 // to undone, redoing moves them in the other direction. 4720 this.done = []; this.undone = []; 4721 this.undoDepth = Infinity; 4722 // Used to track when changes can be merged into a single undo 4723 // event 4724 this.lastModTime = this.lastSelTime = 0; 4725 this.lastOp = this.lastSelOp = null; 4726 this.lastOrigin = this.lastSelOrigin = null; 4727 // Used by the isClean() method 4728 this.generation = this.maxGeneration = startGen || 1; 4729 } 4730 4731 // Create a history change event from an updateDoc-style change 4732 // object. 4733 function historyChangeFromChange(doc, change) { 4734 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 4735 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 4736 linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); 4737 return histChange 4738 } 4739 4740 // Pop all selection events off the end of a history array. Stop at 4741 // a change event. 4742 function clearSelectionEvents(array) { 4743 while (array.length) { 4744 var last = lst(array); 4745 if (last.ranges) { array.pop(); } 4746 else { break } 4747 } 4748 } 4749 4750 // Find the top change event in the history. Pop off selection 4751 // events that are in the way. 4752 function lastChangeEvent(hist, force) { 4753 if (force) { 4754 clearSelectionEvents(hist.done); 4755 return lst(hist.done) 4756 } else if (hist.done.length && !lst(hist.done).ranges) { 4757 return lst(hist.done) 4758 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { 4759 hist.done.pop(); 4760 return lst(hist.done) 4761 } 4762 } 4763 4764 // Register a change in the history. Merges changes that are within 4765 // a single operation, or are close together with an origin that 4766 // allows merging (starting with "+") into a single event. 4767 function addChangeToHistory(doc, change, selAfter, opId) { 4768 var hist = doc.history; 4769 hist.undone.length = 0; 4770 var time = +new Date, cur; 4771 var last; 4772 4773 if ((hist.lastOp == opId || 4774 hist.lastOrigin == change.origin && change.origin && 4775 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || 4776 change.origin.charAt(0) == "*")) && 4777 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { 4778 // Merge this change into the last event 4779 last = lst(cur.changes); 4780 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { 4781 // Optimized case for simple insertion -- don't want to add 4782 // new changesets for every character typed 4783 last.to = changeEnd(change); 4784 } else { 4785 // Add new sub-event 4786 cur.changes.push(historyChangeFromChange(doc, change)); 4787 } 4788 } else { 4789 // Can not be merged, start a new event. 4790 var before = lst(hist.done); 4791 if (!before || !before.ranges) 4792 { pushSelectionToHistory(doc.sel, hist.done); } 4793 cur = {changes: [historyChangeFromChange(doc, change)], 4794 generation: hist.generation}; 4795 hist.done.push(cur); 4796 while (hist.done.length > hist.undoDepth) { 4797 hist.done.shift(); 4798 if (!hist.done[0].ranges) { hist.done.shift(); } 4799 } 4800 } 4801 hist.done.push(selAfter); 4802 hist.generation = ++hist.maxGeneration; 4803 hist.lastModTime = hist.lastSelTime = time; 4804 hist.lastOp = hist.lastSelOp = opId; 4805 hist.lastOrigin = hist.lastSelOrigin = change.origin; 4806 4807 if (!last) { signal(doc, "historyAdded"); } 4808 } 4809 4810 function selectionEventCanBeMerged(doc, origin, prev, sel) { 4811 var ch = origin.charAt(0); 4812 return ch == "*" || 4813 ch == "+" && 4814 prev.ranges.length == sel.ranges.length && 4815 prev.somethingSelected() == sel.somethingSelected() && 4816 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) 4817 } 4818 4819 // Called whenever the selection changes, sets the new selection as 4820 // the pending selection in the history, and pushes the old pending 4821 // selection into the 'done' array when it was significantly 4822 // different (in number of selected ranges, emptiness, or time). 4823 function addSelectionToHistory(doc, sel, opId, options) { 4824 var hist = doc.history, origin = options && options.origin; 4825 4826 // A new event is started when the previous origin does not match 4827 // the current, or the origins don't allow matching. Origins 4828 // starting with * are always merged, those starting with + are 4829 // merged when similar and close together in time. 4830 if (opId == hist.lastSelOp || 4831 (origin && hist.lastSelOrigin == origin && 4832 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || 4833 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) 4834 { hist.done[hist.done.length - 1] = sel; } 4835 else 4836 { pushSelectionToHistory(sel, hist.done); } 4837 4838 hist.lastSelTime = +new Date; 4839 hist.lastSelOrigin = origin; 4840 hist.lastSelOp = opId; 4841 if (options && options.clearRedo !== false) 4842 { clearSelectionEvents(hist.undone); } 4843 } 4844 4845 function pushSelectionToHistory(sel, dest) { 4846 var top = lst(dest); 4847 if (!(top && top.ranges && top.equals(sel))) 4848 { dest.push(sel); } 4849 } 4850 4851 // Used to store marked span information in the history. 4852 function attachLocalSpans(doc, change, from, to) { 4853 var existing = change["spans_" + doc.id], n = 0; 4854 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { 4855 if (line.markedSpans) 4856 { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } 4857 ++n; 4858 }); 4859 } 4860 4861 // When un/re-doing restores text containing marked spans, those 4862 // that have been explicitly cleared should not be restored. 4863 function removeClearedSpans(spans) { 4864 if (!spans) { return null } 4865 var out; 4866 for (var i = 0; i < spans.length; ++i) { 4867 if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } 4868 else if (out) { out.push(spans[i]); } 4869 } 4870 return !out ? spans : out.length ? out : null 4871 } 4872 4873 // Retrieve and filter the old marked spans stored in a change event. 4874 function getOldSpans(doc, change) { 4875 var found = change["spans_" + doc.id]; 4876 if (!found) { return null } 4877 var nw = []; 4878 for (var i = 0; i < change.text.length; ++i) 4879 { nw.push(removeClearedSpans(found[i])); } 4880 return nw 4881 } 4882 4883 // Used for un/re-doing changes from the history. Combines the 4884 // result of computing the existing spans with the set of spans that 4885 // existed in the history (so that deleting around a span and then 4886 // undoing brings back the span). 4887 function mergeOldSpans(doc, change) { 4888 var old = getOldSpans(doc, change); 4889 var stretched = stretchSpansOverChange(doc, change); 4890 if (!old) { return stretched } 4891 if (!stretched) { return old } 4892 4893 for (var i = 0; i < old.length; ++i) { 4894 var oldCur = old[i], stretchCur = stretched[i]; 4895 if (oldCur && stretchCur) { 4896 spans: for (var j = 0; j < stretchCur.length; ++j) { 4897 var span = stretchCur[j]; 4898 for (var k = 0; k < oldCur.length; ++k) 4899 { if (oldCur[k].marker == span.marker) { continue spans } } 4900 oldCur.push(span); 4901 } 4902 } else if (stretchCur) { 4903 old[i] = stretchCur; 4904 } 4905 } 4906 return old 4907 } 4908 4909 // Used both to provide a JSON-safe object in .getHistory, and, when 4910 // detaching a document, to split the history in two 4911 function copyHistoryArray(events, newGroup, instantiateSel) { 4912 var copy = []; 4913 for (var i = 0; i < events.length; ++i) { 4914 var event = events[i]; 4915 if (event.ranges) { 4916 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); 4917 continue 4918 } 4919 var changes = event.changes, newChanges = []; 4920 copy.push({changes: newChanges}); 4921 for (var j = 0; j < changes.length; ++j) { 4922 var change = changes[j], m = (void 0); 4923 newChanges.push({from: change.from, to: change.to, text: change.text}); 4924 if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { 4925 if (indexOf(newGroup, Number(m[1])) > -1) { 4926 lst(newChanges)[prop] = change[prop]; 4927 delete change[prop]; 4928 } 4929 } } } 4930 } 4931 } 4932 return copy 4933 } 4934 4935 // The 'scroll' parameter given to many of these indicated whether 4936 // the new cursor position should be scrolled into view after 4937 // modifying the selection. 4938 4939 // If shift is held or the extend flag is set, extends a range to 4940 // include a given position (and optionally a second position). 4941 // Otherwise, simply returns the range between the given positions. 4942 // Used for cursor motion and such. 4943 function extendRange(range, head, other, extend) { 4944 if (extend) { 4945 var anchor = range.anchor; 4946 if (other) { 4947 var posBefore = cmp(head, anchor) < 0; 4948 if (posBefore != (cmp(other, anchor) < 0)) { 4949 anchor = head; 4950 head = other; 4951 } else if (posBefore != (cmp(head, other) < 0)) { 4952 head = other; 4953 } 4954 } 4955 return new Range(anchor, head) 4956 } else { 4957 return new Range(other || head, head) 4958 } 4959 } 4960 4961 // Extend the primary selection range, discard the rest. 4962 function extendSelection(doc, head, other, options, extend) { 4963 if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } 4964 setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); 4965 } 4966 4967 // Extend all selections (pos is an array of selections with length 4968 // equal the number of selections) 4969 function extendSelections(doc, heads, options) { 4970 var out = []; 4971 var extend = doc.cm && (doc.cm.display.shift || doc.extend); 4972 for (var i = 0; i < doc.sel.ranges.length; i++) 4973 { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } 4974 var newSel = normalizeSelection(out, doc.sel.primIndex); 4975 setSelection(doc, newSel, options); 4976 } 4977 4978 // Updates a single range in the selection. 4979 function replaceOneSelection(doc, i, range, options) { 4980 var ranges = doc.sel.ranges.slice(0); 4981 ranges[i] = range; 4982 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); 4983 } 4984 4985 // Reset the selection to a single range. 4986 function setSimpleSelection(doc, anchor, head, options) { 4987 setSelection(doc, simpleSelection(anchor, head), options); 4988 } 4989 4990 // Give beforeSelectionChange handlers a change to influence a 4991 // selection update. 4992 function filterSelectionChange(doc, sel, options) { 4993 var obj = { 4994 ranges: sel.ranges, 4995 update: function(ranges) { 4996 var this$1 = this; 4997 4998 this.ranges = []; 4999 for (var i = 0; i < ranges.length; i++) 5000 { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), 5001 clipPos(doc, ranges[i].head)); } 5002 }, 5003 origin: options && options.origin 5004 }; 5005 signal(doc, "beforeSelectionChange", doc, obj); 5006 if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } 5007 if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } 5008 else { return sel } 5009 } 5010 5011 function setSelectionReplaceHistory(doc, sel, options) { 5012 var done = doc.history.done, last = lst(done); 5013 if (last && last.ranges) { 5014 done[done.length - 1] = sel; 5015 setSelectionNoUndo(doc, sel, options); 5016 } else { 5017 setSelection(doc, sel, options); 5018 } 5019 } 5020 5021 // Set a new selection. 5022 function setSelection(doc, sel, options) { 5023 setSelectionNoUndo(doc, sel, options); 5024 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); 5025 } 5026 5027 function setSelectionNoUndo(doc, sel, options) { 5028 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) 5029 { sel = filterSelectionChange(doc, sel, options); } 5030 5031 var bias = options && options.bias || 5032 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); 5033 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); 5034 5035 if (!(options && options.scroll === false) && doc.cm) 5036 { ensureCursorVisible(doc.cm); } 5037 } 5038 5039 function setSelectionInner(doc, sel) { 5040 if (sel.equals(doc.sel)) { return } 5041 5042 doc.sel = sel; 5043 5044 if (doc.cm) { 5045 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 5046 signalCursorActivity(doc.cm); 5047 } 5048 signalLater(doc, "cursorActivity", doc); 5049 } 5050 5051 // Verify that the selection does not partially select any atomic 5052 // marked ranges. 5053 function reCheckSelection(doc) { 5054 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); 5055 } 5056 5057 // Return a selection that does not partially select any atomic 5058 // ranges. 5059 function skipAtomicInSelection(doc, sel, bias, mayClear) { 5060 var out; 5061 for (var i = 0; i < sel.ranges.length; i++) { 5062 var range = sel.ranges[i]; 5063 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; 5064 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); 5065 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); 5066 if (out || newAnchor != range.anchor || newHead != range.head) { 5067 if (!out) { out = sel.ranges.slice(0, i); } 5068 out[i] = new Range(newAnchor, newHead); 5069 } 5070 } 5071 return out ? normalizeSelection(out, sel.primIndex) : sel 5072 } 5073 5074 function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { 5075 var line = getLine(doc, pos.line); 5076 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 5077 var sp = line.markedSpans[i], m = sp.marker; 5078 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && 5079 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { 5080 if (mayClear) { 5081 signal(m, "beforeCursorEnter"); 5082 if (m.explicitlyCleared) { 5083 if (!line.markedSpans) { break } 5084 else {--i; continue} 5085 } 5086 } 5087 if (!m.atomic) { continue } 5088 5089 if (oldPos) { 5090 var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); 5091 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) 5092 { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } 5093 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) 5094 { return skipAtomicInner(doc, near, pos, dir, mayClear) } 5095 } 5096 5097 var far = m.find(dir < 0 ? -1 : 1); 5098 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) 5099 { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } 5100 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null 5101 } 5102 } } 5103 return pos 5104 } 5105 5106 // Ensure a given position is not inside an atomic range. 5107 function skipAtomic(doc, pos, oldPos, bias, mayClear) { 5108 var dir = bias || 1; 5109 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || 5110 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || 5111 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || 5112 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); 5113 if (!found) { 5114 doc.cantEdit = true; 5115 return Pos(doc.first, 0) 5116 } 5117 return found 5118 } 5119 5120 function movePos(doc, pos, dir, line) { 5121 if (dir < 0 && pos.ch == 0) { 5122 if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } 5123 else { return null } 5124 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { 5125 if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } 5126 else { return null } 5127 } else { 5128 return new Pos(pos.line, pos.ch + dir) 5129 } 5130 } 5131 5132 function selectAll(cm) { 5133 cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); 5134 } 5135 5136 // UPDATING 5137 5138 // Allow "beforeChange" event handlers to influence a change 5139 function filterChange(doc, change, update) { 5140 var obj = { 5141 canceled: false, 5142 from: change.from, 5143 to: change.to, 5144 text: change.text, 5145 origin: change.origin, 5146 cancel: function () { return obj.canceled = true; } 5147 }; 5148 if (update) { obj.update = function (from, to, text, origin) { 5149 if (from) { obj.from = clipPos(doc, from); } 5150 if (to) { obj.to = clipPos(doc, to); } 5151 if (text) { obj.text = text; } 5152 if (origin !== undefined) { obj.origin = origin; } 5153 }; } 5154 signal(doc, "beforeChange", doc, obj); 5155 if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } 5156 5157 if (obj.canceled) { return null } 5158 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} 5159 } 5160 5161 // Apply a change to a document, and add it to the document's 5162 // history, and propagating it to all linked documents. 5163 function makeChange(doc, change, ignoreReadOnly) { 5164 if (doc.cm) { 5165 if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } 5166 if (doc.cm.state.suppressEdits) { return } 5167 } 5168 5169 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 5170 change = filterChange(doc, change, true); 5171 if (!change) { return } 5172 } 5173 5174 // Possibly split or suppress the update based on the presence 5175 // of read-only spans in its range. 5176 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 5177 if (split) { 5178 for (var i = split.length - 1; i >= 0; --i) 5179 { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); } 5180 } else { 5181 makeChangeInner(doc, change); 5182 } 5183 } 5184 5185 function makeChangeInner(doc, change) { 5186 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } 5187 var selAfter = computeSelAfterChange(doc, change); 5188 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 5189 5190 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 5191 var rebased = []; 5192 5193 linkedDocs(doc, function (doc, sharedHist) { 5194 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5195 rebaseHist(doc.history, change); 5196 rebased.push(doc.history); 5197 } 5198 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 5199 }); 5200 } 5201 5202 // Revert a change stored in a document's history. 5203 function makeChangeFromHistory(doc, type, allowSelectionOnly) { 5204 if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } 5205 5206 var hist = doc.history, event, selAfter = doc.sel; 5207 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; 5208 5209 // Verify that there is a useable event (so that ctrl-z won't 5210 // needlessly clear selection events) 5211 var i = 0; 5212 for (; i < source.length; i++) { 5213 event = source[i]; 5214 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) 5215 { break } 5216 } 5217 if (i == source.length) { return } 5218 hist.lastOrigin = hist.lastSelOrigin = null; 5219 5220 for (;;) { 5221 event = source.pop(); 5222 if (event.ranges) { 5223 pushSelectionToHistory(event, dest); 5224 if (allowSelectionOnly && !event.equals(doc.sel)) { 5225 setSelection(doc, event, {clearRedo: false}); 5226 return 5227 } 5228 selAfter = event; 5229 } 5230 else { break } 5231 } 5232 5233 // Build up a reverse change object to add to the opposite history 5234 // stack (redo when undoing, and vice versa). 5235 var antiChanges = []; 5236 pushSelectionToHistory(selAfter, dest); 5237 dest.push({changes: antiChanges, generation: hist.generation}); 5238 hist.generation = event.generation || ++hist.maxGeneration; 5239 5240 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); 5241 5242 var loop = function ( i ) { 5243 var change = event.changes[i]; 5244 change.origin = type; 5245 if (filter && !filterChange(doc, change, false)) { 5246 source.length = 0; 5247 return {} 5248 } 5249 5250 antiChanges.push(historyChangeFromChange(doc, change)); 5251 5252 var after = i ? computeSelAfterChange(doc, change) : lst(source); 5253 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 5254 if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } 5255 var rebased = []; 5256 5257 // Propagate to the linked documents 5258 linkedDocs(doc, function (doc, sharedHist) { 5259 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5260 rebaseHist(doc.history, change); 5261 rebased.push(doc.history); 5262 } 5263 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 5264 }); 5265 }; 5266 5267 for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { 5268 var returned = loop( i$1 ); 5269 5270 if ( returned ) return returned.v; 5271 } 5272 } 5273 5274 // Sub-views need their line numbers shifted when text is added 5275 // above or below them in the parent document. 5276 function shiftDoc(doc, distance) { 5277 if (distance == 0) { return } 5278 doc.first += distance; 5279 doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( 5280 Pos(range.anchor.line + distance, range.anchor.ch), 5281 Pos(range.head.line + distance, range.head.ch) 5282 ); }), doc.sel.primIndex); 5283 if (doc.cm) { 5284 regChange(doc.cm, doc.first, doc.first - distance, distance); 5285 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) 5286 { regLineChange(doc.cm, l, "gutter"); } 5287 } 5288 } 5289 5290 // More lower-level change function, handling only a single document 5291 // (not linked ones). 5292 function makeChangeSingleDoc(doc, change, selAfter, spans) { 5293 if (doc.cm && !doc.cm.curOp) 5294 { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } 5295 5296 if (change.to.line < doc.first) { 5297 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 5298 return 5299 } 5300 if (change.from.line > doc.lastLine()) { return } 5301 5302 // Clip the change to the size of this doc 5303 if (change.from.line < doc.first) { 5304 var shift = change.text.length - 1 - (doc.first - change.from.line); 5305 shiftDoc(doc, shift); 5306 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 5307 text: [lst(change.text)], origin: change.origin}; 5308 } 5309 var last = doc.lastLine(); 5310 if (change.to.line > last) { 5311 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 5312 text: [change.text[0]], origin: change.origin}; 5313 } 5314 5315 change.removed = getBetween(doc, change.from, change.to); 5316 5317 if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } 5318 if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } 5319 else { updateDoc(doc, change, spans); } 5320 setSelectionNoUndo(doc, selAfter, sel_dontScroll); 5321 } 5322 5323 // Handle the interaction of a change to a document with the editor 5324 // that this document is part of. 5325 function makeChangeSingleDocInEditor(cm, change, spans) { 5326 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 5327 5328 var recomputeMaxLength = false, checkWidthStart = from.line; 5329 if (!cm.options.lineWrapping) { 5330 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); 5331 doc.iter(checkWidthStart, to.line + 1, function (line) { 5332 if (line == display.maxLine) { 5333 recomputeMaxLength = true; 5334 return true 5335 } 5336 }); 5337 } 5338 5339 if (doc.sel.contains(change.from, change.to) > -1) 5340 { signalCursorActivity(cm); } 5341 5342 updateDoc(doc, change, spans, estimateHeight(cm)); 5343 5344 if (!cm.options.lineWrapping) { 5345 doc.iter(checkWidthStart, from.line + change.text.length, function (line) { 5346 var len = lineLength(line); 5347 if (len > display.maxLineLength) { 5348 display.maxLine = line; 5349 display.maxLineLength = len; 5350 display.maxLineChanged = true; 5351 recomputeMaxLength = false; 5352 } 5353 }); 5354 if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } 5355 } 5356 5357 retreatFrontier(doc, from.line); 5358 startWorker(cm, 400); 5359 5360 var lendiff = change.text.length - (to.line - from.line) - 1; 5361 // Remember that these lines changed, for updating the display 5362 if (change.full) 5363 { regChange(cm); } 5364 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) 5365 { regLineChange(cm, from.line, "text"); } 5366 else 5367 { regChange(cm, from.line, to.line + 1, lendiff); } 5368 5369 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); 5370 if (changeHandler || changesHandler) { 5371 var obj = { 5372 from: from, to: to, 5373 text: change.text, 5374 removed: change.removed, 5375 origin: change.origin 5376 }; 5377 if (changeHandler) { signalLater(cm, "change", cm, obj); } 5378 if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } 5379 } 5380 cm.display.selForContextMenu = null; 5381 } 5382 5383 function replaceRange(doc, code, from, to, origin) { 5384 if (!to) { to = from; } 5385 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } 5386 if (typeof code == "string") { code = doc.splitLines(code); } 5387 makeChange(doc, {from: from, to: to, text: code, origin: origin}); 5388 } 5389 5390 // Rebasing/resetting history to deal with externally-sourced changes 5391 5392 function rebaseHistSelSingle(pos, from, to, diff) { 5393 if (to < pos.line) { 5394 pos.line += diff; 5395 } else if (from < pos.line) { 5396 pos.line = from; 5397 pos.ch = 0; 5398 } 5399 } 5400 5401 // Tries to rebase an array of history events given a change in the 5402 // document. If the change touches the same lines as the event, the 5403 // event, and everything 'behind' it, is discarded. If the change is 5404 // before the event, the event's positions are updated. Uses a 5405 // copy-on-write scheme for the positions, to avoid having to 5406 // reallocate them all on every rebase, but also avoid problems with 5407 // shared position objects being unsafely updated. 5408 function rebaseHistArray(array, from, to, diff) { 5409 for (var i = 0; i < array.length; ++i) { 5410 var sub = array[i], ok = true; 5411 if (sub.ranges) { 5412 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } 5413 for (var j = 0; j < sub.ranges.length; j++) { 5414 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); 5415 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); 5416 } 5417 continue 5418 } 5419 for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { 5420 var cur = sub.changes[j$1]; 5421 if (to < cur.from.line) { 5422 cur.from = Pos(cur.from.line + diff, cur.from.ch); 5423 cur.to = Pos(cur.to.line + diff, cur.to.ch); 5424 } else if (from <= cur.to.line) { 5425 ok = false; 5426 break 5427 } 5428 } 5429 if (!ok) { 5430 array.splice(0, i + 1); 5431 i = 0; 5432 } 5433 } 5434 } 5435 5436 function rebaseHist(hist, change) { 5437 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 5438 rebaseHistArray(hist.done, from, to, diff); 5439 rebaseHistArray(hist.undone, from, to, diff); 5440 } 5441 5442 // Utility for applying a change to a line by handle or number, 5443 // returning the number and optionally registering the line as 5444 // changed. 5445 function changeLine(doc, handle, changeType, op) { 5446 var no = handle, line = handle; 5447 if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } 5448 else { no = lineNo(handle); } 5449 if (no == null) { return null } 5450 if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } 5451 return line 5452 } 5453 5454 // The document is represented as a BTree consisting of leaves, with 5455 // chunk of lines in them, and branches, with up to ten leaves or 5456 // other branch nodes below them. The top node is always a branch 5457 // node, and is the document object itself (meaning it has 5458 // additional methods and properties). 5459 // 5460 // All nodes have parent links. The tree is used both to go from 5461 // line numbers to line objects, and to go from objects to numbers. 5462 // It also indexes by height, and is used to convert between height 5463 // and line object, and to find the total height of the document. 5464 // 5465 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html 5466 5467 function LeafChunk(lines) { 5468 var this$1 = this; 5469 5470 this.lines = lines; 5471 this.parent = null; 5472 var height = 0; 5473 for (var i = 0; i < lines.length; ++i) { 5474 lines[i].parent = this$1; 5475 height += lines[i].height; 5476 } 5477 this.height = height; 5478 } 5479 5480 LeafChunk.prototype = { 5481 chunkSize: function chunkSize() { return this.lines.length }, 5482 5483 // Remove the n lines at offset 'at'. 5484 removeInner: function removeInner(at, n) { 5485 var this$1 = this; 5486 5487 for (var i = at, e = at + n; i < e; ++i) { 5488 var line = this$1.lines[i]; 5489 this$1.height -= line.height; 5490 cleanUpLine(line); 5491 signalLater(line, "delete"); 5492 } 5493 this.lines.splice(at, n); 5494 }, 5495 5496 // Helper used to collapse a small branch into a single leaf. 5497 collapse: function collapse(lines) { 5498 lines.push.apply(lines, this.lines); 5499 }, 5500 5501 // Insert the given array of lines at offset 'at', count them as 5502 // having the given height. 5503 insertInner: function insertInner(at, lines, height) { 5504 var this$1 = this; 5505 5506 this.height += height; 5507 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 5508 for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } 5509 }, 5510 5511 // Used to iterate over a part of the tree. 5512 iterN: function iterN(at, n, op) { 5513 var this$1 = this; 5514 5515 for (var e = at + n; at < e; ++at) 5516 { if (op(this$1.lines[at])) { return true } } 5517 } 5518 }; 5519 5520 function BranchChunk(children) { 5521 var this$1 = this; 5522 5523 this.children = children; 5524 var size = 0, height = 0; 5525 for (var i = 0; i < children.length; ++i) { 5526 var ch = children[i]; 5527 size += ch.chunkSize(); height += ch.height; 5528 ch.parent = this$1; 5529 } 5530 this.size = size; 5531 this.height = height; 5532 this.parent = null; 5533 } 5534 5535 BranchChunk.prototype = { 5536 chunkSize: function chunkSize() { return this.size }, 5537 5538 removeInner: function removeInner(at, n) { 5539 var this$1 = this; 5540 5541 this.size -= n; 5542 for (var i = 0; i < this.children.length; ++i) { 5543 var child = this$1.children[i], sz = child.chunkSize(); 5544 if (at < sz) { 5545 var rm = Math.min(n, sz - at), oldHeight = child.height; 5546 child.removeInner(at, rm); 5547 this$1.height -= oldHeight - child.height; 5548 if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } 5549 if ((n -= rm) == 0) { break } 5550 at = 0; 5551 } else { at -= sz; } 5552 } 5553 // If the result is smaller than 25 lines, ensure that it is a 5554 // single leaf node. 5555 if (this.size - n < 25 && 5556 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { 5557 var lines = []; 5558 this.collapse(lines); 5559 this.children = [new LeafChunk(lines)]; 5560 this.children[0].parent = this; 5561 } 5562 }, 5563 5564 collapse: function collapse(lines) { 5565 var this$1 = this; 5566 5567 for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } 5568 }, 5569 5570 insertInner: function insertInner(at, lines, height) { 5571 var this$1 = this; 5572 5573 this.size += lines.length; 5574 this.height += height; 5575 for (var i = 0; i < this.children.length; ++i) { 5576 var child = this$1.children[i], sz = child.chunkSize(); 5577 if (at <= sz) { 5578 child.insertInner(at, lines, height); 5579 if (child.lines && child.lines.length > 50) { 5580 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. 5581 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. 5582 var remaining = child.lines.length % 25 + 25; 5583 for (var pos = remaining; pos < child.lines.length;) { 5584 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); 5585 child.height -= leaf.height; 5586 this$1.children.splice(++i, 0, leaf); 5587 leaf.parent = this$1; 5588 } 5589 child.lines = child.lines.slice(0, remaining); 5590 this$1.maybeSpill(); 5591 } 5592 break 5593 } 5594 at -= sz; 5595 } 5596 }, 5597 5598 // When a node has grown, check whether it should be split. 5599 maybeSpill: function maybeSpill() { 5600 if (this.children.length <= 10) { return } 5601 var me = this; 5602 do { 5603 var spilled = me.children.splice(me.children.length - 5, 5); 5604 var sibling = new BranchChunk(spilled); 5605 if (!me.parent) { // Become the parent node 5606 var copy = new BranchChunk(me.children); 5607 copy.parent = me; 5608 me.children = [copy, sibling]; 5609 me = copy; 5610 } else { 5611 me.size -= sibling.size; 5612 me.height -= sibling.height; 5613 var myIndex = indexOf(me.parent.children, me); 5614 me.parent.children.splice(myIndex + 1, 0, sibling); 5615 } 5616 sibling.parent = me.parent; 5617 } while (me.children.length > 10) 5618 me.parent.maybeSpill(); 5619 }, 5620 5621 iterN: function iterN(at, n, op) { 5622 var this$1 = this; 5623 5624 for (var i = 0; i < this.children.length; ++i) { 5625 var child = this$1.children[i], sz = child.chunkSize(); 5626 if (at < sz) { 5627 var used = Math.min(n, sz - at); 5628 if (child.iterN(at, used, op)) { return true } 5629 if ((n -= used) == 0) { break } 5630 at = 0; 5631 } else { at -= sz; } 5632 } 5633 } 5634 }; 5635 5636 // Line widgets are block elements displayed above or below a line. 5637 5638 var LineWidget = function(doc, node, options) { 5639 var this$1 = this; 5640 5641 if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) 5642 { this$1[opt] = options[opt]; } } } 5643 this.doc = doc; 5644 this.node = node; 5645 }; 5646 5647 LineWidget.prototype.clear = function () { 5648 var this$1 = this; 5649 5650 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); 5651 if (no == null || !ws) { return } 5652 for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } 5653 if (!ws.length) { line.widgets = null; } 5654 var height = widgetHeight(this); 5655 updateLineHeight(line, Math.max(0, line.height - height)); 5656 if (cm) { 5657 runInOp(cm, function () { 5658 adjustScrollWhenAboveVisible(cm, line, -height); 5659 regLineChange(cm, no, "widget"); 5660 }); 5661 signalLater(cm, "lineWidgetCleared", cm, this, no); 5662 } 5663 }; 5664 5665 LineWidget.prototype.changed = function () { 5666 var this$1 = this; 5667 5668 var oldH = this.height, cm = this.doc.cm, line = this.line; 5669 this.height = null; 5670 var diff = widgetHeight(this) - oldH; 5671 if (!diff) { return } 5672 updateLineHeight(line, line.height + diff); 5673 if (cm) { 5674 runInOp(cm, function () { 5675 cm.curOp.forceUpdate = true; 5676 adjustScrollWhenAboveVisible(cm, line, diff); 5677 signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); 5678 }); 5679 } 5680 }; 5681 eventMixin(LineWidget); 5682 5683 function adjustScrollWhenAboveVisible(cm, line, diff) { 5684 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) 5685 { addToScrollTop(cm, diff); } 5686 } 5687 5688 function addLineWidget(doc, handle, node, options) { 5689 var widget = new LineWidget(doc, node, options); 5690 var cm = doc.cm; 5691 if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } 5692 changeLine(doc, handle, "widget", function (line) { 5693 var widgets = line.widgets || (line.widgets = []); 5694 if (widget.insertAt == null) { widgets.push(widget); } 5695 else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } 5696 widget.line = line; 5697 if (cm && !lineIsHidden(doc, line)) { 5698 var aboveVisible = heightAtLine(line) < doc.scrollTop; 5699 updateLineHeight(line, line.height + widgetHeight(widget)); 5700 if (aboveVisible) { addToScrollTop(cm, widget.height); } 5701 cm.curOp.forceUpdate = true; 5702 } 5703 return true 5704 }); 5705 signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); 5706 return widget 5707 } 5708 5709 // TEXTMARKERS 5710 5711 // Created with markText and setBookmark methods. A TextMarker is a 5712 // handle that can be used to clear or find a marked position in the 5713 // document. Line objects hold arrays (markedSpans) containing 5714 // {from, to, marker} object pointing to such marker objects, and 5715 // indicating that such a marker is present on that line. Multiple 5716 // lines may point to the same marker when it spans across lines. 5717 // The spans will have null for their from/to properties when the 5718 // marker continues beyond the start/end of the line. Markers have 5719 // links back to the lines they currently touch. 5720 5721 // Collapsed markers have unique ids, in order to be able to order 5722 // them, which is needed for uniquely determining an outer marker 5723 // when they overlap (they may nest, but not partially overlap). 5724 var nextMarkerId = 0; 5725 5726 var TextMarker = function(doc, type) { 5727 this.lines = []; 5728 this.type = type; 5729 this.doc = doc; 5730 this.id = ++nextMarkerId; 5731 }; 5732 5733 // Clear the marker. 5734 TextMarker.prototype.clear = function () { 5735 var this$1 = this; 5736 5737 if (this.explicitlyCleared) { return } 5738 var cm = this.doc.cm, withOp = cm && !cm.curOp; 5739 if (withOp) { startOperation(cm); } 5740 if (hasHandler(this, "clear")) { 5741 var found = this.find(); 5742 if (found) { signalLater(this, "clear", found.from, found.to); } 5743 } 5744 var min = null, max = null; 5745 for (var i = 0; i < this.lines.length; ++i) { 5746 var line = this$1.lines[i]; 5747 var span = getMarkedSpanFor(line.markedSpans, this$1); 5748 if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } 5749 else if (cm) { 5750 if (span.to != null) { max = lineNo(line); } 5751 if (span.from != null) { min = lineNo(line); } 5752 } 5753 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 5754 if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) 5755 { updateLineHeight(line, textHeight(cm.display)); } 5756 } 5757 if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { 5758 var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); 5759 if (len > cm.display.maxLineLength) { 5760 cm.display.maxLine = visual; 5761 cm.display.maxLineLength = len; 5762 cm.display.maxLineChanged = true; 5763 } 5764 } } 5765 5766 if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } 5767 this.lines.length = 0; 5768 this.explicitlyCleared = true; 5769 if (this.atomic && this.doc.cantEdit) { 5770 this.doc.cantEdit = false; 5771 if (cm) { reCheckSelection(cm.doc); } 5772 } 5773 if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } 5774 if (withOp) { endOperation(cm); } 5775 if (this.parent) { this.parent.clear(); } 5776 }; 5777 5778 // Find the position of the marker in the document. Returns a {from, 5779 // to} object by default. Side can be passed to get a specific side 5780 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the 5781 // Pos objects returned contain a line object, rather than a line 5782 // number (used to prevent looking up the same line twice). 5783 TextMarker.prototype.find = function (side, lineObj) { 5784 var this$1 = this; 5785 5786 if (side == null && this.type == "bookmark") { side = 1; } 5787 var from, to; 5788 for (var i = 0; i < this.lines.length; ++i) { 5789 var line = this$1.lines[i]; 5790 var span = getMarkedSpanFor(line.markedSpans, this$1); 5791 if (span.from != null) { 5792 from = Pos(lineObj ? line : lineNo(line), span.from); 5793 if (side == -1) { return from } 5794 } 5795 if (span.to != null) { 5796 to = Pos(lineObj ? line : lineNo(line), span.to); 5797 if (side == 1) { return to } 5798 } 5799 } 5800 return from && {from: from, to: to} 5801 }; 5802 5803 // Signals that the marker's widget changed, and surrounding layout 5804 // should be recomputed. 5805 TextMarker.prototype.changed = function () { 5806 var this$1 = this; 5807 5808 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; 5809 if (!pos || !cm) { return } 5810 runInOp(cm, function () { 5811 var line = pos.line, lineN = lineNo(pos.line); 5812 var view = findViewForLine(cm, lineN); 5813 if (view) { 5814 clearLineMeasurementCacheFor(view); 5815 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; 5816 } 5817 cm.curOp.updateMaxLine = true; 5818 if (!lineIsHidden(widget.doc, line) && widget.height != null) { 5819 var oldHeight = widget.height; 5820 widget.height = null; 5821 var dHeight = widgetHeight(widget) - oldHeight; 5822 if (dHeight) 5823 { updateLineHeight(line, line.height + dHeight); } 5824 } 5825 signalLater(cm, "markerChanged", cm, this$1); 5826 }); 5827 }; 5828 5829 TextMarker.prototype.attachLine = function (line) { 5830 if (!this.lines.length && this.doc.cm) { 5831 var op = this.doc.cm.curOp; 5832 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 5833 { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } 5834 } 5835 this.lines.push(line); 5836 }; 5837 5838 TextMarker.prototype.detachLine = function (line) { 5839 this.lines.splice(indexOf(this.lines, line), 1); 5840 if (!this.lines.length && this.doc.cm) { 5841 var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 5842 } 5843 }; 5844 eventMixin(TextMarker); 5845 5846 // Create a marker, wire it up to the right lines, and 5847 function markText(doc, from, to, options, type) { 5848 // Shared markers (across linked documents) are handled separately 5849 // (markTextShared will call out to this again, once per 5850 // document). 5851 if (options && options.shared) { return markTextShared(doc, from, to, options, type) } 5852 // Ensure we are in an operation. 5853 if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } 5854 5855 var marker = new TextMarker(doc, type), diff = cmp(from, to); 5856 if (options) { copyObj(options, marker, false); } 5857 // Don't connect empty markers unless clearWhenEmpty is false 5858 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) 5859 { return marker } 5860 if (marker.replacedWith) { 5861 // Showing up as a widget implies collapsed (widget replaces text) 5862 marker.collapsed = true; 5863 marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); 5864 if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } 5865 if (options.insertLeft) { marker.widgetNode.insertLeft = true; } 5866 } 5867 if (marker.collapsed) { 5868 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || 5869 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) 5870 { throw new Error("Inserting collapsed marker partially overlapping an existing one") } 5871 seeCollapsedSpans(); 5872 } 5873 5874 if (marker.addToHistory) 5875 { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } 5876 5877 var curLine = from.line, cm = doc.cm, updateMaxLine; 5878 doc.iter(curLine, to.line + 1, function (line) { 5879 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) 5880 { updateMaxLine = true; } 5881 if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } 5882 addMarkedSpan(line, new MarkedSpan(marker, 5883 curLine == from.line ? from.ch : null, 5884 curLine == to.line ? to.ch : null)); 5885 ++curLine; 5886 }); 5887 // lineIsHidden depends on the presence of the spans, so needs a second pass 5888 if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { 5889 if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } 5890 }); } 5891 5892 if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } 5893 5894 if (marker.readOnly) { 5895 seeReadOnlySpans(); 5896 if (doc.history.done.length || doc.history.undone.length) 5897 { doc.clearHistory(); } 5898 } 5899 if (marker.collapsed) { 5900 marker.id = ++nextMarkerId; 5901 marker.atomic = true; 5902 } 5903 if (cm) { 5904 // Sync editor state 5905 if (updateMaxLine) { cm.curOp.updateMaxLine = true; } 5906 if (marker.collapsed) 5907 { regChange(cm, from.line, to.line + 1); } 5908 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) 5909 { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } 5910 if (marker.atomic) { reCheckSelection(cm.doc); } 5911 signalLater(cm, "markerAdded", cm, marker); 5912 } 5913 return marker 5914 } 5915 5916 // SHARED TEXTMARKERS 5917 5918 // A shared marker spans multiple linked documents. It is 5919 // implemented as a meta-marker-object controlling multiple normal 5920 // markers. 5921 var SharedTextMarker = function(markers, primary) { 5922 var this$1 = this; 5923 5924 this.markers = markers; 5925 this.primary = primary; 5926 for (var i = 0; i < markers.length; ++i) 5927 { markers[i].parent = this$1; } 5928 }; 5929 5930 SharedTextMarker.prototype.clear = function () { 5931 var this$1 = this; 5932 5933 if (this.explicitlyCleared) { return } 5934 this.explicitlyCleared = true; 5935 for (var i = 0; i < this.markers.length; ++i) 5936 { this$1.markers[i].clear(); } 5937 signalLater(this, "clear"); 5938 }; 5939 5940 SharedTextMarker.prototype.find = function (side, lineObj) { 5941 return this.primary.find(side, lineObj) 5942 }; 5943 eventMixin(SharedTextMarker); 5944 5945 function markTextShared(doc, from, to, options, type) { 5946 options = copyObj(options); 5947 options.shared = false; 5948 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 5949 var widget = options.widgetNode; 5950 linkedDocs(doc, function (doc) { 5951 if (widget) { options.widgetNode = widget.cloneNode(true); } 5952 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 5953 for (var i = 0; i < doc.linked.length; ++i) 5954 { if (doc.linked[i].isParent) { return } } 5955 primary = lst(markers); 5956 }); 5957 return new SharedTextMarker(markers, primary) 5958 } 5959 5960 function findSharedMarkers(doc) { 5961 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) 5962 } 5963 5964 function copySharedMarkers(doc, markers) { 5965 for (var i = 0; i < markers.length; i++) { 5966 var marker = markers[i], pos = marker.find(); 5967 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); 5968 if (cmp(mFrom, mTo)) { 5969 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); 5970 marker.markers.push(subMark); 5971 subMark.parent = marker; 5972 } 5973 } 5974 } 5975 5976 function detachSharedMarkers(markers) { 5977 var loop = function ( i ) { 5978 var marker = markers[i], linked = [marker.primary.doc]; 5979 linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); 5980 for (var j = 0; j < marker.markers.length; j++) { 5981 var subMarker = marker.markers[j]; 5982 if (indexOf(linked, subMarker.doc) == -1) { 5983 subMarker.parent = null; 5984 marker.markers.splice(j--, 1); 5985 } 5986 } 5987 }; 5988 5989 for (var i = 0; i < markers.length; i++) loop( i ); 5990 } 5991 5992 var nextDocId = 0; 5993 var Doc = function(text, mode, firstLine, lineSep, direction) { 5994 if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } 5995 if (firstLine == null) { firstLine = 0; } 5996 5997 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); 5998 this.first = firstLine; 5999 this.scrollTop = this.scrollLeft = 0; 6000 this.cantEdit = false; 6001 this.cleanGeneration = 1; 6002 this.modeFrontier = this.highlightFrontier = firstLine; 6003 var start = Pos(firstLine, 0); 6004 this.sel = simpleSelection(start); 6005 this.history = new History(null); 6006 this.id = ++nextDocId; 6007 this.modeOption = mode; 6008 this.lineSep = lineSep; 6009 this.direction = (direction == "rtl") ? "rtl" : "ltr"; 6010 this.extend = false; 6011 6012 if (typeof text == "string") { text = this.splitLines(text); } 6013 updateDoc(this, {from: start, to: start, text: text}); 6014 setSelection(this, simpleSelection(start), sel_dontScroll); 6015 }; 6016 6017 Doc.prototype = createObj(BranchChunk.prototype, { 6018 constructor: Doc, 6019 // Iterate over the document. Supports two forms -- with only one 6020 // argument, it calls that for each line in the document. With 6021 // three, it iterates over the range given by the first two (with 6022 // the second being non-inclusive). 6023 iter: function(from, to, op) { 6024 if (op) { this.iterN(from - this.first, to - from, op); } 6025 else { this.iterN(this.first, this.first + this.size, from); } 6026 }, 6027 6028 // Non-public interface for adding and removing lines. 6029 insert: function(at, lines) { 6030 var height = 0; 6031 for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } 6032 this.insertInner(at - this.first, lines, height); 6033 }, 6034 remove: function(at, n) { this.removeInner(at - this.first, n); }, 6035 6036 // From here, the methods are part of the public interface. Most 6037 // are also available from CodeMirror (editor) instances. 6038 6039 getValue: function(lineSep) { 6040 var lines = getLines(this, this.first, this.first + this.size); 6041 if (lineSep === false) { return lines } 6042 return lines.join(lineSep || this.lineSeparator()) 6043 }, 6044 setValue: docMethodOp(function(code) { 6045 var top = Pos(this.first, 0), last = this.first + this.size - 1; 6046 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 6047 text: this.splitLines(code), origin: "setValue", full: true}, true); 6048 if (this.cm) { scrollToCoords(this.cm, 0, 0); } 6049 setSelection(this, simpleSelection(top), sel_dontScroll); 6050 }), 6051 replaceRange: function(code, from, to, origin) { 6052 from = clipPos(this, from); 6053 to = to ? clipPos(this, to) : from; 6054 replaceRange(this, code, from, to, origin); 6055 }, 6056 getRange: function(from, to, lineSep) { 6057 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 6058 if (lineSep === false) { return lines } 6059 return lines.join(lineSep || this.lineSeparator()) 6060 }, 6061 6062 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, 6063 6064 getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, 6065 getLineNumber: function(line) {return lineNo(line)}, 6066 6067 getLineHandleVisualStart: function(line) { 6068 if (typeof line == "number") { line = getLine(this, line); } 6069 return visualLine(line) 6070 }, 6071 6072 lineCount: function() {return this.size}, 6073 firstLine: function() {return this.first}, 6074 lastLine: function() {return this.first + this.size - 1}, 6075 6076 clipPos: function(pos) {return clipPos(this, pos)}, 6077 6078 getCursor: function(start) { 6079 var range$$1 = this.sel.primary(), pos; 6080 if (start == null || start == "head") { pos = range$$1.head; } 6081 else if (start == "anchor") { pos = range$$1.anchor; } 6082 else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } 6083 else { pos = range$$1.from(); } 6084 return pos 6085 }, 6086 listSelections: function() { return this.sel.ranges }, 6087 somethingSelected: function() {return this.sel.somethingSelected()}, 6088 6089 setCursor: docMethodOp(function(line, ch, options) { 6090 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); 6091 }), 6092 setSelection: docMethodOp(function(anchor, head, options) { 6093 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); 6094 }), 6095 extendSelection: docMethodOp(function(head, other, options) { 6096 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); 6097 }), 6098 extendSelections: docMethodOp(function(heads, options) { 6099 extendSelections(this, clipPosArray(this, heads), options); 6100 }), 6101 extendSelectionsBy: docMethodOp(function(f, options) { 6102 var heads = map(this.sel.ranges, f); 6103 extendSelections(this, clipPosArray(this, heads), options); 6104 }), 6105 setSelections: docMethodOp(function(ranges, primary, options) { 6106 var this$1 = this; 6107 6108 if (!ranges.length) { return } 6109 var out = []; 6110 for (var i = 0; i < ranges.length; i++) 6111 { out[i] = new Range(clipPos(this$1, ranges[i].anchor), 6112 clipPos(this$1, ranges[i].head)); } 6113 if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } 6114 setSelection(this, normalizeSelection(out, primary), options); 6115 }), 6116 addSelection: docMethodOp(function(anchor, head, options) { 6117 var ranges = this.sel.ranges.slice(0); 6118 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); 6119 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); 6120 }), 6121 6122 getSelection: function(lineSep) { 6123 var this$1 = this; 6124 6125 var ranges = this.sel.ranges, lines; 6126 for (var i = 0; i < ranges.length; i++) { 6127 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6128 lines = lines ? lines.concat(sel) : sel; 6129 } 6130 if (lineSep === false) { return lines } 6131 else { return lines.join(lineSep || this.lineSeparator()) } 6132 }, 6133 getSelections: function(lineSep) { 6134 var this$1 = this; 6135 6136 var parts = [], ranges = this.sel.ranges; 6137 for (var i = 0; i < ranges.length; i++) { 6138 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6139 if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } 6140 parts[i] = sel; 6141 } 6142 return parts 6143 }, 6144 replaceSelection: function(code, collapse, origin) { 6145 var dup = []; 6146 for (var i = 0; i < this.sel.ranges.length; i++) 6147 { dup[i] = code; } 6148 this.replaceSelections(dup, collapse, origin || "+input"); 6149 }, 6150 replaceSelections: docMethodOp(function(code, collapse, origin) { 6151 var this$1 = this; 6152 6153 var changes = [], sel = this.sel; 6154 for (var i = 0; i < sel.ranges.length; i++) { 6155 var range$$1 = sel.ranges[i]; 6156 changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; 6157 } 6158 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); 6159 for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) 6160 { makeChange(this$1, changes[i$1]); } 6161 if (newSel) { setSelectionReplaceHistory(this, newSel); } 6162 else if (this.cm) { ensureCursorVisible(this.cm); } 6163 }), 6164 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), 6165 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), 6166 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), 6167 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), 6168 6169 setExtending: function(val) {this.extend = val;}, 6170 getExtending: function() {return this.extend}, 6171 6172 historySize: function() { 6173 var hist = this.history, done = 0, undone = 0; 6174 for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } 6175 for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } 6176 return {undo: done, redo: undone} 6177 }, 6178 clearHistory: function() {this.history = new History(this.history.maxGeneration);}, 6179 6180 markClean: function() { 6181 this.cleanGeneration = this.changeGeneration(true); 6182 }, 6183 changeGeneration: function(forceSplit) { 6184 if (forceSplit) 6185 { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } 6186 return this.history.generation 6187 }, 6188 isClean: function (gen) { 6189 return this.history.generation == (gen || this.cleanGeneration) 6190 }, 6191 6192 getHistory: function() { 6193 return {done: copyHistoryArray(this.history.done), 6194 undone: copyHistoryArray(this.history.undone)} 6195 }, 6196 setHistory: function(histData) { 6197 var hist = this.history = new History(this.history.maxGeneration); 6198 hist.done = copyHistoryArray(histData.done.slice(0), null, true); 6199 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); 6200 }, 6201 6202 setGutterMarker: docMethodOp(function(line, gutterID, value) { 6203 return changeLine(this, line, "gutter", function (line) { 6204 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 6205 markers[gutterID] = value; 6206 if (!value && isEmpty(markers)) { line.gutterMarkers = null; } 6207 return true 6208 }) 6209 }), 6210 6211 clearGutter: docMethodOp(function(gutterID) { 6212 var this$1 = this; 6213 6214 this.iter(function (line) { 6215 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 6216 changeLine(this$1, line, "gutter", function () { 6217 line.gutterMarkers[gutterID] = null; 6218 if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } 6219 return true 6220 }); 6221 } 6222 }); 6223 }), 6224 6225 lineInfo: function(line) { 6226 var n; 6227 if (typeof line == "number") { 6228 if (!isLine(this, line)) { return null } 6229 n = line; 6230 line = getLine(this, line); 6231 if (!line) { return null } 6232 } else { 6233 n = lineNo(line); 6234 if (n == null) { return null } 6235 } 6236 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 6237 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 6238 widgets: line.widgets} 6239 }, 6240 6241 addLineClass: docMethodOp(function(handle, where, cls) { 6242 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6243 var prop = where == "text" ? "textClass" 6244 : where == "background" ? "bgClass" 6245 : where == "gutter" ? "gutterClass" : "wrapClass"; 6246 if (!line[prop]) { line[prop] = cls; } 6247 else if (classTest(cls).test(line[prop])) { return false } 6248 else { line[prop] += " " + cls; } 6249 return true 6250 }) 6251 }), 6252 removeLineClass: docMethodOp(function(handle, where, cls) { 6253 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6254 var prop = where == "text" ? "textClass" 6255 : where == "background" ? "bgClass" 6256 : where == "gutter" ? "gutterClass" : "wrapClass"; 6257 var cur = line[prop]; 6258 if (!cur) { return false } 6259 else if (cls == null) { line[prop] = null; } 6260 else { 6261 var found = cur.match(classTest(cls)); 6262 if (!found) { return false } 6263 var end = found.index + found[0].length; 6264 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; 6265 } 6266 return true 6267 }) 6268 }), 6269 6270 addLineWidget: docMethodOp(function(handle, node, options) { 6271 return addLineWidget(this, handle, node, options) 6272 }), 6273 removeLineWidget: function(widget) { widget.clear(); }, 6274 6275 markText: function(from, to, options) { 6276 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") 6277 }, 6278 setBookmark: function(pos, options) { 6279 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 6280 insertLeft: options && options.insertLeft, 6281 clearWhenEmpty: false, shared: options && options.shared, 6282 handleMouseEvents: options && options.handleMouseEvents}; 6283 pos = clipPos(this, pos); 6284 return markText(this, pos, pos, realOpts, "bookmark") 6285 }, 6286 findMarksAt: function(pos) { 6287 pos = clipPos(this, pos); 6288 var markers = [], spans = getLine(this, pos.line).markedSpans; 6289 if (spans) { for (var i = 0; i < spans.length; ++i) { 6290 var span = spans[i]; 6291 if ((span.from == null || span.from <= pos.ch) && 6292 (span.to == null || span.to >= pos.ch)) 6293 { markers.push(span.marker.parent || span.marker); } 6294 } } 6295 return markers 6296 }, 6297 findMarks: function(from, to, filter) { 6298 from = clipPos(this, from); to = clipPos(this, to); 6299 var found = [], lineNo$$1 = from.line; 6300 this.iter(from.line, to.line + 1, function (line) { 6301 var spans = line.markedSpans; 6302 if (spans) { for (var i = 0; i < spans.length; i++) { 6303 var span = spans[i]; 6304 if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || 6305 span.from == null && lineNo$$1 != from.line || 6306 span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && 6307 (!filter || filter(span.marker))) 6308 { found.push(span.marker.parent || span.marker); } 6309 } } 6310 ++lineNo$$1; 6311 }); 6312 return found 6313 }, 6314 getAllMarks: function() { 6315 var markers = []; 6316 this.iter(function (line) { 6317 var sps = line.markedSpans; 6318 if (sps) { for (var i = 0; i < sps.length; ++i) 6319 { if (sps[i].from != null) { markers.push(sps[i].marker); } } } 6320 }); 6321 return markers 6322 }, 6323 6324 posFromIndex: function(off) { 6325 var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; 6326 this.iter(function (line) { 6327 var sz = line.text.length + sepSize; 6328 if (sz > off) { ch = off; return true } 6329 off -= sz; 6330 ++lineNo$$1; 6331 }); 6332 return clipPos(this, Pos(lineNo$$1, ch)) 6333 }, 6334 indexFromPos: function (coords) { 6335 coords = clipPos(this, coords); 6336 var index = coords.ch; 6337 if (coords.line < this.first || coords.ch < 0) { return 0 } 6338 var sepSize = this.lineSeparator().length; 6339 this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value 6340 index += line.text.length + sepSize; 6341 }); 6342 return index 6343 }, 6344 6345 copy: function(copyHistory) { 6346 var doc = new Doc(getLines(this, this.first, this.first + this.size), 6347 this.modeOption, this.first, this.lineSep, this.direction); 6348 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 6349 doc.sel = this.sel; 6350 doc.extend = false; 6351 if (copyHistory) { 6352 doc.history.undoDepth = this.history.undoDepth; 6353 doc.setHistory(this.getHistory()); 6354 } 6355 return doc 6356 }, 6357 6358 linkedDoc: function(options) { 6359 if (!options) { options = {}; } 6360 var from = this.first, to = this.first + this.size; 6361 if (options.from != null && options.from > from) { from = options.from; } 6362 if (options.to != null && options.to < to) { to = options.to; } 6363 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); 6364 if (options.sharedHist) { copy.history = this.history 6365 ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 6366 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 6367 copySharedMarkers(copy, findSharedMarkers(this)); 6368 return copy 6369 }, 6370 unlinkDoc: function(other) { 6371 var this$1 = this; 6372 6373 if (other instanceof CodeMirror$1) { other = other.doc; } 6374 if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { 6375 var link = this$1.linked[i]; 6376 if (link.doc != other) { continue } 6377 this$1.linked.splice(i, 1); 6378 other.unlinkDoc(this$1); 6379 detachSharedMarkers(findSharedMarkers(this$1)); 6380 break 6381 } } 6382 // If the histories were shared, split them again 6383 if (other.history == this.history) { 6384 var splitIds = [other.id]; 6385 linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); 6386 other.history = new History(null); 6387 other.history.done = copyHistoryArray(this.history.done, splitIds); 6388 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 6389 } 6390 }, 6391 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 6392 6393 getMode: function() {return this.mode}, 6394 getEditor: function() {return this.cm}, 6395 6396 splitLines: function(str) { 6397 if (this.lineSep) { return str.split(this.lineSep) } 6398 return splitLinesAuto(str) 6399 }, 6400 lineSeparator: function() { return this.lineSep || "\n" }, 6401 6402 setDirection: docMethodOp(function (dir) { 6403 if (dir != "rtl") { dir = "ltr"; } 6404 if (dir == this.direction) { return } 6405 this.direction = dir; 6406 this.iter(function (line) { return line.order = null; }); 6407 if (this.cm) { directionChanged(this.cm); } 6408 }) 6409 }); 6410 6411 // Public alias. 6412 Doc.prototype.eachLine = Doc.prototype.iter; 6413 6414 // Kludge to work around strange IE behavior where it'll sometimes 6415 // re-fire a series of drag-related events right after the drop (#1551) 6416 var lastDrop = 0; 6417 6418 function onDrop(e) { 6419 var cm = this; 6420 clearDragCursor(cm); 6421 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) 6422 { return } 6423 e_preventDefault(e); 6424 if (ie) { lastDrop = +new Date; } 6425 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 6426 if (!pos || cm.isReadOnly()) { return } 6427 // Might be a file drop, in which case we simply extract the text 6428 // and insert it. 6429 if (files && files.length && window.FileReader && window.File) { 6430 var n = files.length, text = Array(n), read = 0; 6431 var loadFile = function (file, i) { 6432 if (cm.options.allowDropFileTypes && 6433 indexOf(cm.options.allowDropFileTypes, file.type) == -1) 6434 { return } 6435 6436 var reader = new FileReader; 6437 reader.onload = operation(cm, function () { 6438 var content = reader.result; 6439 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } 6440 text[i] = content; 6441 if (++read == n) { 6442 pos = clipPos(cm.doc, pos); 6443 var change = {from: pos, to: pos, 6444 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), 6445 origin: "paste"}; 6446 makeChange(cm.doc, change); 6447 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); 6448 } 6449 }); 6450 reader.readAsText(file); 6451 }; 6452 for (var i = 0; i < n; ++i) { loadFile(files[i], i); } 6453 } else { // Normal drop 6454 // Don't do a replace if the drop happened inside of the selected text. 6455 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { 6456 cm.state.draggingText(e); 6457 // Ensure the editor is re-focused 6458 setTimeout(function () { return cm.display.input.focus(); }, 20); 6459 return 6460 } 6461 try { 6462 var text$1 = e.dataTransfer.getData("Text"); 6463 if (text$1) { 6464 var selected; 6465 if (cm.state.draggingText && !cm.state.draggingText.copy) 6466 { selected = cm.listSelections(); } 6467 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); 6468 if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) 6469 { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } 6470 cm.replaceSelection(text$1, "around", "paste"); 6471 cm.display.input.focus(); 6472 } 6473 } 6474 catch(e){} 6475 } 6476 } 6477 6478 function onDragStart(cm, e) { 6479 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } 6480 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } 6481 6482 e.dataTransfer.setData("Text", cm.getSelection()); 6483 e.dataTransfer.effectAllowed = "copyMove"; 6484 6485 // Use dummy image instead of default browsers image. 6486 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 6487 if (e.dataTransfer.setDragImage && !safari) { 6488 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 6489 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; 6490 if (presto) { 6491 img.width = img.height = 1; 6492 cm.display.wrapper.appendChild(img); 6493 // Force a relayout, or Opera won't use our image for some obscure reason 6494 img._top = img.offsetTop; 6495 } 6496 e.dataTransfer.setDragImage(img, 0, 0); 6497 if (presto) { img.parentNode.removeChild(img); } 6498 } 6499 } 6500 6501 function onDragOver(cm, e) { 6502 var pos = posFromMouse(cm, e); 6503 if (!pos) { return } 6504 var frag = document.createDocumentFragment(); 6505 drawSelectionCursor(cm, pos, frag); 6506 if (!cm.display.dragCursor) { 6507 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); 6508 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); 6509 } 6510 removeChildrenAndAdd(cm.display.dragCursor, frag); 6511 } 6512 6513 function clearDragCursor(cm) { 6514 if (cm.display.dragCursor) { 6515 cm.display.lineSpace.removeChild(cm.display.dragCursor); 6516 cm.display.dragCursor = null; 6517 } 6518 } 6519 6520 // These must be handled carefully, because naively registering a 6521 // handler for each editor will cause the editors to never be 6522 // garbage collected. 6523 6524 function forEachCodeMirror(f) { 6525 if (!document.getElementsByClassName) { return } 6526 var byClass = document.getElementsByClassName("CodeMirror"); 6527 for (var i = 0; i < byClass.length; i++) { 6528 var cm = byClass[i].CodeMirror; 6529 if (cm) { f(cm); } 6530 } 6531 } 6532 6533 var globalsRegistered = false; 6534 function ensureGlobalHandlers() { 6535 if (globalsRegistered) { return } 6536 registerGlobalHandlers(); 6537 globalsRegistered = true; 6538 } 6539 function registerGlobalHandlers() { 6540 // When the window resizes, we need to refresh active editors. 6541 var resizeTimer; 6542 on(window, "resize", function () { 6543 if (resizeTimer == null) { resizeTimer = setTimeout(function () { 6544 resizeTimer = null; 6545 forEachCodeMirror(onResize); 6546 }, 100); } 6547 }); 6548 // When the window loses focus, we want to show the editor as blurred 6549 on(window, "blur", function () { return forEachCodeMirror(onBlur); }); 6550 } 6551 // Called when the window resizes 6552 function onResize(cm) { 6553 var d = cm.display; 6554 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) 6555 { return } 6556 // Might be a text scaling operation, clear size caches. 6557 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 6558 d.scrollbarsClipped = false; 6559 cm.setSize(); 6560 } 6561 6562 var keyNames = { 6563 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 6564 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 6565 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 6566 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 6567 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 6568 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 6569 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 6570 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 6571 }; 6572 6573 // Number keys 6574 for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } 6575 // Alphabetic keys 6576 for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } 6577 // Function keys 6578 for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } 6579 6580 var keyMap = {}; 6581 6582 keyMap.basic = { 6583 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 6584 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 6585 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", 6586 "Tab": "defaultTab", "Shift-Tab": "indentAuto", 6587 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", 6588 "Esc": "singleSelection" 6589 }; 6590 // Note that the save and find-related commands aren't defined by 6591 // default. User code or addons can define them. Unknown commands 6592 // are simply ignored. 6593 keyMap.pcDefault = { 6594 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 6595 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", 6596 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 6597 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", 6598 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 6599 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 6600 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", 6601 fallthrough: "basic" 6602 }; 6603 // Very basic readline/emacs-style bindings, which are standard on Mac. 6604 keyMap.emacsy = { 6605 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 6606 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 6607 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 6608 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", 6609 "Ctrl-O": "openLine" 6610 }; 6611 keyMap.macDefault = { 6612 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 6613 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", 6614 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", 6615 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", 6616 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 6617 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", 6618 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", 6619 fallthrough: ["basic", "emacsy"] 6620 }; 6621 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 6622 6623 // KEYMAP DISPATCH 6624 6625 function normalizeKeyName(name) { 6626 var parts = name.split(/-(?!$)/); 6627 name = parts[parts.length - 1]; 6628 var alt, ctrl, shift, cmd; 6629 for (var i = 0; i < parts.length - 1; i++) { 6630 var mod = parts[i]; 6631 if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } 6632 else if (/^a(lt)?$/i.test(mod)) { alt = true; } 6633 else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } 6634 else if (/^s(hift)?$/i.test(mod)) { shift = true; } 6635 else { throw new Error("Unrecognized modifier name: " + mod) } 6636 } 6637 if (alt) { name = "Alt-" + name; } 6638 if (ctrl) { name = "Ctrl-" + name; } 6639 if (cmd) { name = "Cmd-" + name; } 6640 if (shift) { name = "Shift-" + name; } 6641 return name 6642 } 6643 6644 // This is a kludge to keep keymaps mostly working as raw objects 6645 // (backwards compatibility) while at the same time support features 6646 // like normalization and multi-stroke key bindings. It compiles a 6647 // new normalized keymap, and then updates the old object to reflect 6648 // this. 6649 function normalizeKeyMap(keymap) { 6650 var copy = {}; 6651 for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { 6652 var value = keymap[keyname]; 6653 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } 6654 if (value == "...") { delete keymap[keyname]; continue } 6655 6656 var keys = map(keyname.split(" "), normalizeKeyName); 6657 for (var i = 0; i < keys.length; i++) { 6658 var val = (void 0), name = (void 0); 6659 if (i == keys.length - 1) { 6660 name = keys.join(" "); 6661 val = value; 6662 } else { 6663 name = keys.slice(0, i + 1).join(" "); 6664 val = "..."; 6665 } 6666 var prev = copy[name]; 6667 if (!prev) { copy[name] = val; } 6668 else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } 6669 } 6670 delete keymap[keyname]; 6671 } } 6672 for (var prop in copy) { keymap[prop] = copy[prop]; } 6673 return keymap 6674 } 6675 6676 function lookupKey(key, map$$1, handle, context) { 6677 map$$1 = getKeyMap(map$$1); 6678 var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; 6679 if (found === false) { return "nothing" } 6680 if (found === "...") { return "multi" } 6681 if (found != null && handle(found)) { return "handled" } 6682 6683 if (map$$1.fallthrough) { 6684 if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") 6685 { return lookupKey(key, map$$1.fallthrough, handle, context) } 6686 for (var i = 0; i < map$$1.fallthrough.length; i++) { 6687 var result = lookupKey(key, map$$1.fallthrough[i], handle, context); 6688 if (result) { return result } 6689 } 6690 } 6691 } 6692 6693 // Modifier key presses don't count as 'real' key presses for the 6694 // purpose of keymap fallthrough. 6695 function isModifierKey(value) { 6696 var name = typeof value == "string" ? value : keyNames[value.keyCode]; 6697 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" 6698 } 6699 6700 function addModifierNames(name, event, noShift) { 6701 var base = name; 6702 if (event.altKey && base != "Alt") { name = "Alt-" + name; } 6703 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } 6704 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } 6705 if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } 6706 return name 6707 } 6708 6709 // Look up the name of a key as indicated by an event object. 6710 function keyName(event, noShift) { 6711 if (presto && event.keyCode == 34 && event["char"]) { return false } 6712 var name = keyNames[event.keyCode]; 6713 if (name == null || event.altGraphKey) { return false } 6714 return addModifierNames(name, event, noShift) 6715 } 6716 6717 function getKeyMap(val) { 6718 return typeof val == "string" ? keyMap[val] : val 6719 } 6720 6721 // Helper for deleting text near the selection(s), used to implement 6722 // backspace, delete, and similar functionality. 6723 function deleteNearSelection(cm, compute) { 6724 var ranges = cm.doc.sel.ranges, kill = []; 6725 // Build up a set of ranges to kill first, merging overlapping 6726 // ranges. 6727 for (var i = 0; i < ranges.length; i++) { 6728 var toKill = compute(ranges[i]); 6729 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { 6730 var replaced = kill.pop(); 6731 if (cmp(replaced.from, toKill.from) < 0) { 6732 toKill.from = replaced.from; 6733 break 6734 } 6735 } 6736 kill.push(toKill); 6737 } 6738 // Next, remove those actual ranges. 6739 runInOp(cm, function () { 6740 for (var i = kill.length - 1; i >= 0; i--) 6741 { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } 6742 ensureCursorVisible(cm); 6743 }); 6744 } 6745 6746 // Commands are parameter-less actions that can be performed on an 6747 // editor, mostly used for keybindings. 6748 var commands = { 6749 selectAll: selectAll, 6750 singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, 6751 killLine: function (cm) { return deleteNearSelection(cm, function (range) { 6752 if (range.empty()) { 6753 var len = getLine(cm.doc, range.head.line).text.length; 6754 if (range.head.ch == len && range.head.line < cm.lastLine()) 6755 { return {from: range.head, to: Pos(range.head.line + 1, 0)} } 6756 else 6757 { return {from: range.head, to: Pos(range.head.line, len)} } 6758 } else { 6759 return {from: range.from(), to: range.to()} 6760 } 6761 }); }, 6762 deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6763 from: Pos(range.from().line, 0), 6764 to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) 6765 }); }); }, 6766 delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6767 from: Pos(range.from().line, 0), to: range.from() 6768 }); }); }, 6769 delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { 6770 var top = cm.charCoords(range.head, "div").top + 5; 6771 var leftPos = cm.coordsChar({left: 0, top: top}, "div"); 6772 return {from: leftPos, to: range.from()} 6773 }); }, 6774 delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { 6775 var top = cm.charCoords(range.head, "div").top + 5; 6776 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 6777 return {from: range.from(), to: rightPos } 6778 }); }, 6779 undo: function (cm) { return cm.undo(); }, 6780 redo: function (cm) { return cm.redo(); }, 6781 undoSelection: function (cm) { return cm.undoSelection(); }, 6782 redoSelection: function (cm) { return cm.redoSelection(); }, 6783 goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, 6784 goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, 6785 goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, 6786 {origin: "+move", bias: 1} 6787 ); }, 6788 goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, 6789 {origin: "+move", bias: 1} 6790 ); }, 6791 goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, 6792 {origin: "+move", bias: -1} 6793 ); }, 6794 goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { 6795 var top = cm.charCoords(range.head, "div").top + 5; 6796 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") 6797 }, sel_move); }, 6798 goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { 6799 var top = cm.charCoords(range.head, "div").top + 5; 6800 return cm.coordsChar({left: 0, top: top}, "div") 6801 }, sel_move); }, 6802 goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { 6803 var top = cm.charCoords(range.head, "div").top + 5; 6804 var pos = cm.coordsChar({left: 0, top: top}, "div"); 6805 if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } 6806 return pos 6807 }, sel_move); }, 6808 goLineUp: function (cm) { return cm.moveV(-1, "line"); }, 6809 goLineDown: function (cm) { return cm.moveV(1, "line"); }, 6810 goPageUp: function (cm) { return cm.moveV(-1, "page"); }, 6811 goPageDown: function (cm) { return cm.moveV(1, "page"); }, 6812 goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, 6813 goCharRight: function (cm) { return cm.moveH(1, "char"); }, 6814 goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, 6815 goColumnRight: function (cm) { return cm.moveH(1, "column"); }, 6816 goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, 6817 goGroupRight: function (cm) { return cm.moveH(1, "group"); }, 6818 goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, 6819 goWordRight: function (cm) { return cm.moveH(1, "word"); }, 6820 delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, 6821 delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, 6822 delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, 6823 delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, 6824 delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, 6825 delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, 6826 indentAuto: function (cm) { return cm.indentSelection("smart"); }, 6827 indentMore: function (cm) { return cm.indentSelection("add"); }, 6828 indentLess: function (cm) { return cm.indentSelection("subtract"); }, 6829 insertTab: function (cm) { return cm.replaceSelection("\t"); }, 6830 insertSoftTab: function (cm) { 6831 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; 6832 for (var i = 0; i < ranges.length; i++) { 6833 var pos = ranges[i].from(); 6834 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); 6835 spaces.push(spaceStr(tabSize - col % tabSize)); 6836 } 6837 cm.replaceSelections(spaces); 6838 }, 6839 defaultTab: function (cm) { 6840 if (cm.somethingSelected()) { cm.indentSelection("add"); } 6841 else { cm.execCommand("insertTab"); } 6842 }, 6843 // Swap the two chars left and right of each selection's head. 6844 // Move cursor behind the two swapped characters afterwards. 6845 // 6846 // Doesn't consider line feeds a character. 6847 // Doesn't scan more than one line above to find a character. 6848 // Doesn't do anything on an empty line. 6849 // Doesn't do anything with non-empty selections. 6850 transposeChars: function (cm) { return runInOp(cm, function () { 6851 var ranges = cm.listSelections(), newSel = []; 6852 for (var i = 0; i < ranges.length; i++) { 6853 if (!ranges[i].empty()) { continue } 6854 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; 6855 if (line) { 6856 if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } 6857 if (cur.ch > 0) { 6858 cur = new Pos(cur.line, cur.ch + 1); 6859 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), 6860 Pos(cur.line, cur.ch - 2), cur, "+transpose"); 6861 } else if (cur.line > cm.doc.first) { 6862 var prev = getLine(cm.doc, cur.line - 1).text; 6863 if (prev) { 6864 cur = new Pos(cur.line, 1); 6865 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + 6866 prev.charAt(prev.length - 1), 6867 Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); 6868 } 6869 } 6870 } 6871 newSel.push(new Range(cur, cur)); 6872 } 6873 cm.setSelections(newSel); 6874 }); }, 6875 newlineAndIndent: function (cm) { return runInOp(cm, function () { 6876 var sels = cm.listSelections(); 6877 for (var i = sels.length - 1; i >= 0; i--) 6878 { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } 6879 sels = cm.listSelections(); 6880 for (var i$1 = 0; i$1 < sels.length; i$1++) 6881 { cm.indentLine(sels[i$1].from().line, null, true); } 6882 ensureCursorVisible(cm); 6883 }); }, 6884 openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, 6885 toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } 6886 }; 6887 6888 6889 function lineStart(cm, lineN) { 6890 var line = getLine(cm.doc, lineN); 6891 var visual = visualLine(line); 6892 if (visual != line) { lineN = lineNo(visual); } 6893 return endOfLine(true, cm, visual, lineN, 1) 6894 } 6895 function lineEnd(cm, lineN) { 6896 var line = getLine(cm.doc, lineN); 6897 var visual = visualLineEnd(line); 6898 if (visual != line) { lineN = lineNo(visual); } 6899 return endOfLine(true, cm, line, lineN, -1) 6900 } 6901 function lineStartSmart(cm, pos) { 6902 var start = lineStart(cm, pos.line); 6903 var line = getLine(cm.doc, start.line); 6904 var order = getOrder(line, cm.doc.direction); 6905 if (!order || order[0].level == 0) { 6906 var firstNonWS = Math.max(0, line.text.search(/\S/)); 6907 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; 6908 return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) 6909 } 6910 return start 6911 } 6912 6913 // Run a handler that was bound to a key. 6914 function doHandleBinding(cm, bound, dropShift) { 6915 if (typeof bound == "string") { 6916 bound = commands[bound]; 6917 if (!bound) { return false } 6918 } 6919 // Ensure previous input has been read, so that the handler sees a 6920 // consistent view of the document 6921 cm.display.input.ensurePolled(); 6922 var prevShift = cm.display.shift, done = false; 6923 try { 6924 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 6925 if (dropShift) { cm.display.shift = false; } 6926 done = bound(cm) != Pass; 6927 } finally { 6928 cm.display.shift = prevShift; 6929 cm.state.suppressEdits = false; 6930 } 6931 return done 6932 } 6933 6934 function lookupKeyForEditor(cm, name, handle) { 6935 for (var i = 0; i < cm.state.keyMaps.length; i++) { 6936 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); 6937 if (result) { return result } 6938 } 6939 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) 6940 || lookupKey(name, cm.options.keyMap, handle, cm) 6941 } 6942 6943 // Note that, despite the name, this function is also used to check 6944 // for bound mouse clicks. 6945 6946 var stopSeq = new Delayed; 6947 function dispatchKey(cm, name, e, handle) { 6948 var seq = cm.state.keySeq; 6949 if (seq) { 6950 if (isModifierKey(name)) { return "handled" } 6951 stopSeq.set(50, function () { 6952 if (cm.state.keySeq == seq) { 6953 cm.state.keySeq = null; 6954 cm.display.input.reset(); 6955 } 6956 }); 6957 name = seq + " " + name; 6958 } 6959 var result = lookupKeyForEditor(cm, name, handle); 6960 6961 if (result == "multi") 6962 { cm.state.keySeq = name; } 6963 if (result == "handled") 6964 { signalLater(cm, "keyHandled", cm, name, e); } 6965 6966 if (result == "handled" || result == "multi") { 6967 e_preventDefault(e); 6968 restartBlink(cm); 6969 } 6970 6971 if (seq && !result && /\'$/.test(name)) { 6972 e_preventDefault(e); 6973 return true 6974 } 6975 return !!result 6976 } 6977 6978 // Handle a key from the keydown event. 6979 function handleKeyBinding(cm, e) { 6980 var name = keyName(e, true); 6981 if (!name) { return false } 6982 6983 if (e.shiftKey && !cm.state.keySeq) { 6984 // First try to resolve full name (including 'Shift-'). Failing 6985 // that, see if there is a cursor-motion command (starting with 6986 // 'go') bound to the keyname without 'Shift-'. 6987 return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) 6988 || dispatchKey(cm, name, e, function (b) { 6989 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) 6990 { return doHandleBinding(cm, b) } 6991 }) 6992 } else { 6993 return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) 6994 } 6995 } 6996 6997 // Handle a key from the keypress event 6998 function handleCharBinding(cm, e, ch) { 6999 return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) 7000 } 7001 7002 var lastStoppedKey = null; 7003 function onKeyDown(e) { 7004 var cm = this; 7005 cm.curOp.focus = activeElt(); 7006 if (signalDOMEvent(cm, e)) { return } 7007 // IE does strange things with escape. 7008 if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } 7009 var code = e.keyCode; 7010 cm.display.shift = code == 16 || e.shiftKey; 7011 var handled = handleKeyBinding(cm, e); 7012 if (presto) { 7013 lastStoppedKey = handled ? code : null; 7014 // Opera has no cut event... we try to at least catch the key combo 7015 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 7016 { cm.replaceSelection("", null, "cut"); } 7017 } 7018 7019 // Turn mouse into crosshair when Alt is held on Mac. 7020 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) 7021 { showCrossHair(cm); } 7022 } 7023 7024 function showCrossHair(cm) { 7025 var lineDiv = cm.display.lineDiv; 7026 addClass(lineDiv, "CodeMirror-crosshair"); 7027 7028 function up(e) { 7029 if (e.keyCode == 18 || !e.altKey) { 7030 rmClass(lineDiv, "CodeMirror-crosshair"); 7031 off(document, "keyup", up); 7032 off(document, "mouseover", up); 7033 } 7034 } 7035 on(document, "keyup", up); 7036 on(document, "mouseover", up); 7037 } 7038 7039 function onKeyUp(e) { 7040 if (e.keyCode == 16) { this.doc.sel.shift = false; } 7041 signalDOMEvent(this, e); 7042 } 7043 7044 function onKeyPress(e) { 7045 var cm = this; 7046 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } 7047 var keyCode = e.keyCode, charCode = e.charCode; 7048 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} 7049 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } 7050 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 7051 // Some browsers fire keypress events for backspace 7052 if (ch == "\x08") { return } 7053 if (handleCharBinding(cm, e, ch)) { return } 7054 cm.display.input.onKeyPress(e); 7055 } 7056 7057 var DOUBLECLICK_DELAY = 400; 7058 7059 var PastClick = function(time, pos, button) { 7060 this.time = time; 7061 this.pos = pos; 7062 this.button = button; 7063 }; 7064 7065 PastClick.prototype.compare = function (time, pos, button) { 7066 return this.time + DOUBLECLICK_DELAY > time && 7067 cmp(pos, this.pos) == 0 && button == this.button 7068 }; 7069 7070 var lastClick; 7071 var lastDoubleClick; 7072 function clickRepeat(pos, button) { 7073 var now = +new Date; 7074 if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { 7075 lastClick = lastDoubleClick = null; 7076 return "triple" 7077 } else if (lastClick && lastClick.compare(now, pos, button)) { 7078 lastDoubleClick = new PastClick(now, pos, button); 7079 lastClick = null; 7080 return "double" 7081 } else { 7082 lastClick = new PastClick(now, pos, button); 7083 lastDoubleClick = null; 7084 return "single" 7085 } 7086 } 7087 7088 // A mouse down can be a single click, double click, triple click, 7089 // start of selection drag, start of text drag, new cursor 7090 // (ctrl-click), rectangle drag (alt-drag), or xwin 7091 // middle-click-paste. Or it might be a click on something we should 7092 // not interfere with, such as a scrollbar or widget. 7093 function onMouseDown(e) { 7094 var cm = this, display = cm.display; 7095 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } 7096 display.input.ensurePolled(); 7097 display.shift = e.shiftKey; 7098 7099 if (eventInWidget(display, e)) { 7100 if (!webkit) { 7101 // Briefly turn off draggability, to allow widgets to do 7102 // normal dragging things. 7103 display.scroller.draggable = false; 7104 setTimeout(function () { return display.scroller.draggable = true; }, 100); 7105 } 7106 return 7107 } 7108 if (clickInGutter(cm, e)) { return } 7109 var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; 7110 window.focus(); 7111 7112 // #3261: make sure, that we're not starting a second selection 7113 if (button == 1 && cm.state.selectingText) 7114 { cm.state.selectingText(e); } 7115 7116 if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } 7117 7118 if (button == 1) { 7119 if (pos) { leftButtonDown(cm, pos, repeat, e); } 7120 else if (e_target(e) == display.scroller) { e_preventDefault(e); } 7121 } else if (button == 2) { 7122 if (pos) { extendSelection(cm.doc, pos); } 7123 setTimeout(function () { return display.input.focus(); }, 20); 7124 } else if (button == 3) { 7125 if (captureRightClick) { onContextMenu(cm, e); } 7126 else { delayBlurEvent(cm); } 7127 } 7128 } 7129 7130 function handleMappedButton(cm, button, pos, repeat, event) { 7131 var name = "Click"; 7132 if (repeat == "double") { name = "Double" + name; } 7133 else if (repeat == "triple") { name = "Triple" + name; } 7134 name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; 7135 7136 return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { 7137 if (typeof bound == "string") { bound = commands[bound]; } 7138 if (!bound) { return false } 7139 var done = false; 7140 try { 7141 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 7142 done = bound(cm, pos) != Pass; 7143 } finally { 7144 cm.state.suppressEdits = false; 7145 } 7146 return done 7147 }) 7148 } 7149 7150 function configureMouse(cm, repeat, event) { 7151 var option = cm.getOption("configureMouse"); 7152 var value = option ? option(cm, repeat, event) : {}; 7153 if (value.unit == null) { 7154 var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; 7155 value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; 7156 } 7157 if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } 7158 if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } 7159 if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } 7160 return value 7161 } 7162 7163 function leftButtonDown(cm, pos, repeat, event) { 7164 if (ie) { setTimeout(bind(ensureFocus, cm), 0); } 7165 else { cm.curOp.focus = activeElt(); } 7166 7167 var behavior = configureMouse(cm, repeat, event); 7168 7169 var sel = cm.doc.sel, contained; 7170 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && 7171 repeat == "single" && (contained = sel.contains(pos)) > -1 && 7172 (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && 7173 (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) 7174 { leftButtonStartDrag(cm, event, pos, behavior); } 7175 else 7176 { leftButtonSelect(cm, event, pos, behavior); } 7177 } 7178 7179 // Start a text drag. When it ends, see if any dragging actually 7180 // happen, and treat as a click if it didn't. 7181 function leftButtonStartDrag(cm, event, pos, behavior) { 7182 var display = cm.display, moved = false; 7183 var dragEnd = operation(cm, function (e) { 7184 if (webkit) { display.scroller.draggable = false; } 7185 cm.state.draggingText = false; 7186 off(document, "mouseup", dragEnd); 7187 off(document, "mousemove", mouseMove); 7188 off(display.scroller, "dragstart", dragStart); 7189 off(display.scroller, "drop", dragEnd); 7190 if (!moved) { 7191 e_preventDefault(e); 7192 if (!behavior.addNew) 7193 { extendSelection(cm.doc, pos, null, null, behavior.extend); } 7194 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) 7195 if (webkit || ie && ie_version == 9) 7196 { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); } 7197 else 7198 { display.input.focus(); } 7199 } 7200 }); 7201 var mouseMove = function(e2) { 7202 moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; 7203 }; 7204 var dragStart = function () { return moved = true; }; 7205 // Let the drag handler handle this. 7206 if (webkit) { display.scroller.draggable = true; } 7207 cm.state.draggingText = dragEnd; 7208 dragEnd.copy = !behavior.moveOnDrag; 7209 // IE's approach to draggable 7210 if (display.scroller.dragDrop) { display.scroller.dragDrop(); } 7211 on(document, "mouseup", dragEnd); 7212 on(document, "mousemove", mouseMove); 7213 on(display.scroller, "dragstart", dragStart); 7214 on(display.scroller, "drop", dragEnd); 7215 7216 delayBlurEvent(cm); 7217 setTimeout(function () { return display.input.focus(); }, 20); 7218 } 7219 7220 function rangeForUnit(cm, pos, unit) { 7221 if (unit == "char") { return new Range(pos, pos) } 7222 if (unit == "word") { return cm.findWordAt(pos) } 7223 if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } 7224 var result = unit(cm, pos); 7225 return new Range(result.from, result.to) 7226 } 7227 7228 // Normal selection, as opposed to text dragging. 7229 function leftButtonSelect(cm, event, start, behavior) { 7230 var display = cm.display, doc = cm.doc; 7231 e_preventDefault(event); 7232 7233 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; 7234 if (behavior.addNew && !behavior.extend) { 7235 ourIndex = doc.sel.contains(start); 7236 if (ourIndex > -1) 7237 { ourRange = ranges[ourIndex]; } 7238 else 7239 { ourRange = new Range(start, start); } 7240 } else { 7241 ourRange = doc.sel.primary(); 7242 ourIndex = doc.sel.primIndex; 7243 } 7244 7245 if (behavior.unit == "rectangle") { 7246 if (!behavior.addNew) { ourRange = new Range(start, start); } 7247 start = posFromMouse(cm, event, true, true); 7248 ourIndex = -1; 7249 } else { 7250 var range$$1 = rangeForUnit(cm, start, behavior.unit); 7251 if (behavior.extend) 7252 { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } 7253 else 7254 { ourRange = range$$1; } 7255 } 7256 7257 if (!behavior.addNew) { 7258 ourIndex = 0; 7259 setSelection(doc, new Selection([ourRange], 0), sel_mouse); 7260 startSel = doc.sel; 7261 } else if (ourIndex == -1) { 7262 ourIndex = ranges.length; 7263 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), 7264 {scroll: false, origin: "*mouse"}); 7265 } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { 7266 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), 7267 {scroll: false, origin: "*mouse"}); 7268 startSel = doc.sel; 7269 } else { 7270 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); 7271 } 7272 7273 var lastPos = start; 7274 function extendTo(pos) { 7275 if (cmp(lastPos, pos) == 0) { return } 7276 lastPos = pos; 7277 7278 if (behavior.unit == "rectangle") { 7279 var ranges = [], tabSize = cm.options.tabSize; 7280 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); 7281 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); 7282 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); 7283 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); 7284 line <= end; line++) { 7285 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); 7286 if (left == right) 7287 { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } 7288 else if (text.length > leftPos) 7289 { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } 7290 } 7291 if (!ranges.length) { ranges.push(new Range(start, start)); } 7292 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), 7293 {origin: "*mouse", scroll: false}); 7294 cm.scrollIntoView(pos); 7295 } else { 7296 var oldRange = ourRange; 7297 var range$$1 = rangeForUnit(cm, pos, behavior.unit); 7298 var anchor = oldRange.anchor, head; 7299 if (cmp(range$$1.anchor, anchor) > 0) { 7300 head = range$$1.head; 7301 anchor = minPos(oldRange.from(), range$$1.anchor); 7302 } else { 7303 head = range$$1.anchor; 7304 anchor = maxPos(oldRange.to(), range$$1.head); 7305 } 7306 var ranges$1 = startSel.ranges.slice(0); 7307 ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head); 7308 setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse); 7309 } 7310 } 7311 7312 var editorSize = display.wrapper.getBoundingClientRect(); 7313 // Used to ensure timeout re-tries don't fire when another extend 7314 // happened in the meantime (clearTimeout isn't reliable -- at 7315 // least on Chrome, the timeouts still happen even when cleared, 7316 // if the clear happens after their scheduled firing time). 7317 var counter = 0; 7318 7319 function extend(e) { 7320 var curCount = ++counter; 7321 var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); 7322 if (!cur) { return } 7323 if (cmp(cur, lastPos) != 0) { 7324 cm.curOp.focus = activeElt(); 7325 extendTo(cur); 7326 var visible = visibleLines(display, doc); 7327 if (cur.line >= visible.to || cur.line < visible.from) 7328 { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } 7329 } else { 7330 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 7331 if (outside) { setTimeout(operation(cm, function () { 7332 if (counter != curCount) { return } 7333 display.scroller.scrollTop += outside; 7334 extend(e); 7335 }), 50); } 7336 } 7337 } 7338 7339 function done(e) { 7340 cm.state.selectingText = false; 7341 counter = Infinity; 7342 e_preventDefault(e); 7343 display.input.focus(); 7344 off(document, "mousemove", move); 7345 off(document, "mouseup", up); 7346 doc.history.lastSelOrigin = null; 7347 } 7348 7349 var move = operation(cm, function (e) { 7350 if (!e_button(e)) { done(e); } 7351 else { extend(e); } 7352 }); 7353 var up = operation(cm, done); 7354 cm.state.selectingText = up; 7355 on(document, "mousemove", move); 7356 on(document, "mouseup", up); 7357 } 7358 7359 7360 // Determines whether an event happened in the gutter, and fires the 7361 // handlers for the corresponding event. 7362 function gutterEvent(cm, e, type, prevent) { 7363 var mX, mY; 7364 try { mX = e.clientX; mY = e.clientY; } 7365 catch(e) { return false } 7366 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } 7367 if (prevent) { e_preventDefault(e); } 7368 7369 var display = cm.display; 7370 var lineBox = display.lineDiv.getBoundingClientRect(); 7371 7372 if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } 7373 mY -= lineBox.top - display.viewOffset; 7374 7375 for (var i = 0; i < cm.options.gutters.length; ++i) { 7376 var g = display.gutters.childNodes[i]; 7377 if (g && g.getBoundingClientRect().right >= mX) { 7378 var line = lineAtHeight(cm.doc, mY); 7379 var gutter = cm.options.gutters[i]; 7380 signal(cm, type, cm, line, gutter, e); 7381 return e_defaultPrevented(e) 7382 } 7383 } 7384 } 7385 7386 function clickInGutter(cm, e) { 7387 return gutterEvent(cm, e, "gutterClick", true) 7388 } 7389 7390 // CONTEXT MENU HANDLING 7391 7392 // To make the context menu work, we need to briefly unhide the 7393 // textarea (making it as unobtrusive as possible) to let the 7394 // right-click take effect on it. 7395 function onContextMenu(cm, e) { 7396 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } 7397 if (signalDOMEvent(cm, e, "contextmenu")) { return } 7398 cm.display.input.onContextMenu(e); 7399 } 7400 7401 function contextMenuInGutter(cm, e) { 7402 if (!hasHandler(cm, "gutterContextMenu")) { return false } 7403 return gutterEvent(cm, e, "gutterContextMenu", false) 7404 } 7405 7406 function themeChanged(cm) { 7407 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + 7408 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); 7409 clearCaches(cm); 7410 } 7411 7412 var Init = {toString: function(){return "CodeMirror.Init"}}; 7413 7414 var defaults = {}; 7415 var optionHandlers = {}; 7416 7417 function defineOptions(CodeMirror) { 7418 var optionHandlers = CodeMirror.optionHandlers; 7419 7420 function option(name, deflt, handle, notOnInit) { 7421 CodeMirror.defaults[name] = deflt; 7422 if (handle) { optionHandlers[name] = 7423 notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } 7424 } 7425 7426 CodeMirror.defineOption = option; 7427 7428 // Passed to option handlers when there is no old value. 7429 CodeMirror.Init = Init; 7430 7431 // These two are, on init, called from the constructor because they 7432 // have to be initialized before the editor can start at all. 7433 option("value", "", function (cm, val) { return cm.setValue(val); }, true); 7434 option("mode", null, function (cm, val) { 7435 cm.doc.modeOption = val; 7436 loadMode(cm); 7437 }, true); 7438 7439 option("indentUnit", 2, loadMode, true); 7440 option("indentWithTabs", false); 7441 option("smartIndent", true); 7442 option("tabSize", 4, function (cm) { 7443 resetModeState(cm); 7444 clearCaches(cm); 7445 regChange(cm); 7446 }, true); 7447 option("lineSeparator", null, function (cm, val) { 7448 cm.doc.lineSep = val; 7449 if (!val) { return } 7450 var newBreaks = [], lineNo = cm.doc.first; 7451 cm.doc.iter(function (line) { 7452 for (var pos = 0;;) { 7453 var found = line.text.indexOf(val, pos); 7454 if (found == -1) { break } 7455 pos = found + val.length; 7456 newBreaks.push(Pos(lineNo, found)); 7457 } 7458 lineNo++; 7459 }); 7460 for (var i = newBreaks.length - 1; i >= 0; i--) 7461 { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } 7462 }); 7463 option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { 7464 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); 7465 if (old != Init) { cm.refresh(); } 7466 }); 7467 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); 7468 option("electricChars", true); 7469 option("inputStyle", mobile ? "contenteditable" : "textarea", function () { 7470 throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME 7471 }, true); 7472 option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); 7473 option("rtlMoveVisually", !windows); 7474 option("wholeLineUpdateBefore", true); 7475 7476 option("theme", "default", function (cm) { 7477 themeChanged(cm); 7478 guttersChanged(cm); 7479 }, true); 7480 option("keyMap", "default", function (cm, val, old) { 7481 var next = getKeyMap(val); 7482 var prev = old != Init && getKeyMap(old); 7483 if (prev && prev.detach) { prev.detach(cm, next); } 7484 if (next.attach) { next.attach(cm, prev || null); } 7485 }); 7486 option("extraKeys", null); 7487 option("configureMouse", null); 7488 7489 option("lineWrapping", false, wrappingChanged, true); 7490 option("gutters", [], function (cm) { 7491 setGuttersForLineNumbers(cm.options); 7492 guttersChanged(cm); 7493 }, true); 7494 option("fixedGutter", true, function (cm, val) { 7495 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 7496 cm.refresh(); 7497 }, true); 7498 option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); 7499 option("scrollbarStyle", "native", function (cm) { 7500 initScrollbars(cm); 7501 updateScrollbars(cm); 7502 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); 7503 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); 7504 }, true); 7505 option("lineNumbers", false, function (cm) { 7506 setGuttersForLineNumbers(cm.options); 7507 guttersChanged(cm); 7508 }, true); 7509 option("firstLineNumber", 1, guttersChanged, true); 7510 option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true); 7511 option("showCursorWhenSelecting", false, updateSelection, true); 7512 7513 option("resetSelectionOnContextMenu", true); 7514 option("lineWiseCopyCut", true); 7515 option("pasteLinesPerSelection", true); 7516 7517 option("readOnly", false, function (cm, val) { 7518 if (val == "nocursor") { 7519 onBlur(cm); 7520 cm.display.input.blur(); 7521 } 7522 cm.display.input.readOnlyChanged(val); 7523 }); 7524 option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); 7525 option("dragDrop", true, dragDropChanged); 7526 option("allowDropFileTypes", null); 7527 7528 option("cursorBlinkRate", 530); 7529 option("cursorScrollMargin", 0); 7530 option("cursorHeight", 1, updateSelection, true); 7531 option("singleCursorHeightPerLine", true, updateSelection, true); 7532 option("workTime", 100); 7533 option("workDelay", 100); 7534 option("flattenSpans", true, resetModeState, true); 7535 option("addModeClass", false, resetModeState, true); 7536 option("pollInterval", 100); 7537 option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); 7538 option("historyEventDelay", 1250); 7539 option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); 7540 option("maxHighlightLength", 10000, resetModeState, true); 7541 option("moveInputWithCursor", true, function (cm, val) { 7542 if (!val) { cm.display.input.resetPosition(); } 7543 }); 7544 7545 option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); 7546 option("autofocus", null); 7547 option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); 7548 } 7549 7550 function guttersChanged(cm) { 7551 updateGutters(cm); 7552 regChange(cm); 7553 alignHorizontally(cm); 7554 } 7555 7556 function dragDropChanged(cm, value, old) { 7557 var wasOn = old && old != Init; 7558 if (!value != !wasOn) { 7559 var funcs = cm.display.dragFunctions; 7560 var toggle = value ? on : off; 7561 toggle(cm.display.scroller, "dragstart", funcs.start); 7562 toggle(cm.display.scroller, "dragenter", funcs.enter); 7563 toggle(cm.display.scroller, "dragover", funcs.over); 7564 toggle(cm.display.scroller, "dragleave", funcs.leave); 7565 toggle(cm.display.scroller, "drop", funcs.drop); 7566 } 7567 } 7568 7569 function wrappingChanged(cm) { 7570 if (cm.options.lineWrapping) { 7571 addClass(cm.display.wrapper, "CodeMirror-wrap"); 7572 cm.display.sizer.style.minWidth = ""; 7573 cm.display.sizerWidth = null; 7574 } else { 7575 rmClass(cm.display.wrapper, "CodeMirror-wrap"); 7576 findMaxLine(cm); 7577 } 7578 estimateLineHeights(cm); 7579 regChange(cm); 7580 clearCaches(cm); 7581 setTimeout(function () { return updateScrollbars(cm); }, 100); 7582 } 7583 7584 // A CodeMirror instance represents an editor. This is the object 7585 // that user code is usually dealing with. 7586 7587 function CodeMirror$1(place, options) { 7588 var this$1 = this; 7589 7590 if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) } 7591 7592 this.options = options = options ? copyObj(options) : {}; 7593 // Determine effective options based on given values and defaults. 7594 copyObj(defaults, options, false); 7595 setGuttersForLineNumbers(options); 7596 7597 var doc = options.value; 7598 if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } 7599 this.doc = doc; 7600 7601 var input = new CodeMirror$1.inputStyles[options.inputStyle](this); 7602 var display = this.display = new Display(place, doc, input); 7603 display.wrapper.CodeMirror = this; 7604 updateGutters(this); 7605 themeChanged(this); 7606 if (options.lineWrapping) 7607 { this.display.wrapper.className += " CodeMirror-wrap"; } 7608 initScrollbars(this); 7609 7610 this.state = { 7611 keyMaps: [], // stores maps added by addKeyMap 7612 overlays: [], // highlighting overlays, as added by addOverlay 7613 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info 7614 overwrite: false, 7615 delayingBlurEvent: false, 7616 focused: false, 7617 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode 7618 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll 7619 selectingText: false, 7620 draggingText: false, 7621 highlight: new Delayed(), // stores highlight worker timeout 7622 keySeq: null, // Unfinished key sequence 7623 specialChars: null 7624 }; 7625 7626 if (options.autofocus && !mobile) { display.input.focus(); } 7627 7628 // Override magic textarea content restore that IE sometimes does 7629 // on our hidden textarea on reload 7630 if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } 7631 7632 registerEventHandlers(this); 7633 ensureGlobalHandlers(); 7634 7635 startOperation(this); 7636 this.curOp.forceUpdate = true; 7637 attachDoc(this, doc); 7638 7639 if ((options.autofocus && !mobile) || this.hasFocus()) 7640 { setTimeout(bind(onFocus, this), 20); } 7641 else 7642 { onBlur(this); } 7643 7644 for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) 7645 { optionHandlers[opt](this$1, options[opt], Init); } } 7646 maybeUpdateLineNumberWidth(this); 7647 if (options.finishInit) { options.finishInit(this); } 7648 for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } 7649 endOperation(this); 7650 // Suppress optimizelegibility in Webkit, since it breaks text 7651 // measuring on line wrapping boundaries. 7652 if (webkit && options.lineWrapping && 7653 getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") 7654 { display.lineDiv.style.textRendering = "auto"; } 7655 } 7656 7657 // The default configuration options. 7658 CodeMirror$1.defaults = defaults; 7659 // Functions to run when options are changed. 7660 CodeMirror$1.optionHandlers = optionHandlers; 7661 7662 // Attach the necessary event handlers when initializing the editor 7663 function registerEventHandlers(cm) { 7664 var d = cm.display; 7665 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 7666 // Older IE's will not fire a second mousedown for a double click 7667 if (ie && ie_version < 11) 7668 { on(d.scroller, "dblclick", operation(cm, function (e) { 7669 if (signalDOMEvent(cm, e)) { return } 7670 var pos = posFromMouse(cm, e); 7671 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } 7672 e_preventDefault(e); 7673 var word = cm.findWordAt(pos); 7674 extendSelection(cm.doc, word.anchor, word.head); 7675 })); } 7676 else 7677 { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } 7678 // Some browsers fire contextmenu *after* opening the menu, at 7679 // which point we can't mess with it anymore. Context menu is 7680 // handled in onMouseDown for these browsers. 7681 if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); } 7682 7683 // Used to suppress mouse event handling when a touch happens 7684 var touchFinished, prevTouch = {end: 0}; 7685 function finishTouch() { 7686 if (d.activeTouch) { 7687 touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); 7688 prevTouch = d.activeTouch; 7689 prevTouch.end = +new Date; 7690 } 7691 } 7692 function isMouseLikeTouchEvent(e) { 7693 if (e.touches.length != 1) { return false } 7694 var touch = e.touches[0]; 7695 return touch.radiusX <= 1 && touch.radiusY <= 1 7696 } 7697 function farAway(touch, other) { 7698 if (other.left == null) { return true } 7699 var dx = other.left - touch.left, dy = other.top - touch.top; 7700 return dx * dx + dy * dy > 20 * 20 7701 } 7702 on(d.scroller, "touchstart", function (e) { 7703 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { 7704 d.input.ensurePolled(); 7705 clearTimeout(touchFinished); 7706 var now = +new Date; 7707 d.activeTouch = {start: now, moved: false, 7708 prev: now - prevTouch.end <= 300 ? prevTouch : null}; 7709 if (e.touches.length == 1) { 7710 d.activeTouch.left = e.touches[0].pageX; 7711 d.activeTouch.top = e.touches[0].pageY; 7712 } 7713 } 7714 }); 7715 on(d.scroller, "touchmove", function () { 7716 if (d.activeTouch) { d.activeTouch.moved = true; } 7717 }); 7718 on(d.scroller, "touchend", function (e) { 7719 var touch = d.activeTouch; 7720 if (touch && !eventInWidget(d, e) && touch.left != null && 7721 !touch.moved && new Date - touch.start < 300) { 7722 var pos = cm.coordsChar(d.activeTouch, "page"), range; 7723 if (!touch.prev || farAway(touch, touch.prev)) // Single tap 7724 { range = new Range(pos, pos); } 7725 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap 7726 { range = cm.findWordAt(pos); } 7727 else // Triple tap 7728 { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } 7729 cm.setSelection(range.anchor, range.head); 7730 cm.focus(); 7731 e_preventDefault(e); 7732 } 7733 finishTouch(); 7734 }); 7735 on(d.scroller, "touchcancel", finishTouch); 7736 7737 // Sync scrolling between fake scrollbars and real scrollable 7738 // area, ensure viewport is updated when scrolling. 7739 on(d.scroller, "scroll", function () { 7740 if (d.scroller.clientHeight) { 7741 updateScrollTop(cm, d.scroller.scrollTop); 7742 setScrollLeft(cm, d.scroller.scrollLeft, true); 7743 signal(cm, "scroll", cm); 7744 } 7745 }); 7746 7747 // Listen to wheel events in order to try and update the viewport on time. 7748 on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); 7749 on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); 7750 7751 // Prevent wrapper from ever scrolling 7752 on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 7753 7754 d.dragFunctions = { 7755 enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, 7756 over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, 7757 start: function (e) { return onDragStart(cm, e); }, 7758 drop: operation(cm, onDrop), 7759 leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} 7760 }; 7761 7762 var inp = d.input.getField(); 7763 on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); 7764 on(inp, "keydown", operation(cm, onKeyDown)); 7765 on(inp, "keypress", operation(cm, onKeyPress)); 7766 on(inp, "focus", function (e) { return onFocus(cm, e); }); 7767 on(inp, "blur", function (e) { return onBlur(cm, e); }); 7768 } 7769 7770 var initHooks = []; 7771 CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); }; 7772 7773 // Indent the given line. The how parameter can be "smart", 7774 // "add"/null, "subtract", or "prev". When aggressive is false 7775 // (typically set to true for forced single-line indents), empty 7776 // lines are not indented, and places where the mode returns Pass 7777 // are left alone. 7778 function indentLine(cm, n, how, aggressive) { 7779 var doc = cm.doc, state; 7780 if (how == null) { how = "add"; } 7781 if (how == "smart") { 7782 // Fall back to "prev" when the mode doesn't have an indentation 7783 // method. 7784 if (!doc.mode.indent) { how = "prev"; } 7785 else { state = getContextBefore(cm, n).state; } 7786 } 7787 7788 var tabSize = cm.options.tabSize; 7789 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 7790 if (line.stateAfter) { line.stateAfter = null; } 7791 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 7792 if (!aggressive && !/\S/.test(line.text)) { 7793 indentation = 0; 7794 how = "not"; 7795 } else if (how == "smart") { 7796 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 7797 if (indentation == Pass || indentation > 150) { 7798 if (!aggressive) { return } 7799 how = "prev"; 7800 } 7801 } 7802 if (how == "prev") { 7803 if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } 7804 else { indentation = 0; } 7805 } else if (how == "add") { 7806 indentation = curSpace + cm.options.indentUnit; 7807 } else if (how == "subtract") { 7808 indentation = curSpace - cm.options.indentUnit; 7809 } else if (typeof how == "number") { 7810 indentation = curSpace + how; 7811 } 7812 indentation = Math.max(0, indentation); 7813 7814 var indentString = "", pos = 0; 7815 if (cm.options.indentWithTabs) 7816 { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } 7817 if (pos < indentation) { indentString += spaceStr(indentation - pos); } 7818 7819 if (indentString != curSpaceString) { 7820 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 7821 line.stateAfter = null; 7822 return true 7823 } else { 7824 // Ensure that, if the cursor was in the whitespace at the start 7825 // of the line, it is moved to the end of that space. 7826 for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { 7827 var range = doc.sel.ranges[i$1]; 7828 if (range.head.line == n && range.head.ch < curSpaceString.length) { 7829 var pos$1 = Pos(n, curSpaceString.length); 7830 replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); 7831 break 7832 } 7833 } 7834 } 7835 } 7836 7837 // This will be set to a {lineWise: bool, text: [string]} object, so 7838 // that, when pasting, we know what kind of selections the copied 7839 // text was made out of. 7840 var lastCopied = null; 7841 7842 function setLastCopied(newLastCopied) { 7843 lastCopied = newLastCopied; 7844 } 7845 7846 function applyTextInput(cm, inserted, deleted, sel, origin) { 7847 var doc = cm.doc; 7848 cm.display.shift = false; 7849 if (!sel) { sel = doc.sel; } 7850 7851 var paste = cm.state.pasteIncoming || origin == "paste"; 7852 var textLines = splitLinesAuto(inserted), multiPaste = null; 7853 // When pasing N lines into N selections, insert one line per selection 7854 if (paste && sel.ranges.length > 1) { 7855 if (lastCopied && lastCopied.text.join("\n") == inserted) { 7856 if (sel.ranges.length % lastCopied.text.length == 0) { 7857 multiPaste = []; 7858 for (var i = 0; i < lastCopied.text.length; i++) 7859 { multiPaste.push(doc.splitLines(lastCopied.text[i])); } 7860 } 7861 } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { 7862 multiPaste = map(textLines, function (l) { return [l]; }); 7863 } 7864 } 7865 7866 var updateInput; 7867 // Normal behavior is to insert the new text into every selection 7868 for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { 7869 var range$$1 = sel.ranges[i$1]; 7870 var from = range$$1.from(), to = range$$1.to(); 7871 if (range$$1.empty()) { 7872 if (deleted && deleted > 0) // Handle deletion 7873 { from = Pos(from.line, from.ch - deleted); } 7874 else if (cm.state.overwrite && !paste) // Handle overwrite 7875 { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } 7876 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) 7877 { from = to = Pos(from.line, 0); } 7878 } 7879 updateInput = cm.curOp.updateInput; 7880 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, 7881 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; 7882 makeChange(cm.doc, changeEvent); 7883 signalLater(cm, "inputRead", cm, changeEvent); 7884 } 7885 if (inserted && !paste) 7886 { triggerElectric(cm, inserted); } 7887 7888 ensureCursorVisible(cm); 7889 cm.curOp.updateInput = updateInput; 7890 cm.curOp.typing = true; 7891 cm.state.pasteIncoming = cm.state.cutIncoming = false; 7892 } 7893 7894 function handlePaste(e, cm) { 7895 var pasted = e.clipboardData && e.clipboardData.getData("Text"); 7896 if (pasted) { 7897 e.preventDefault(); 7898 if (!cm.isReadOnly() && !cm.options.disableInput) 7899 { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } 7900 return true 7901 } 7902 } 7903 7904 function triggerElectric(cm, inserted) { 7905 // When an 'electric' character is inserted, immediately trigger a reindent 7906 if (!cm.options.electricChars || !cm.options.smartIndent) { return } 7907 var sel = cm.doc.sel; 7908 7909 for (var i = sel.ranges.length - 1; i >= 0; i--) { 7910 var range$$1 = sel.ranges[i]; 7911 if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } 7912 var mode = cm.getModeAt(range$$1.head); 7913 var indented = false; 7914 if (mode.electricChars) { 7915 for (var j = 0; j < mode.electricChars.length; j++) 7916 { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { 7917 indented = indentLine(cm, range$$1.head.line, "smart"); 7918 break 7919 } } 7920 } else if (mode.electricInput) { 7921 if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) 7922 { indented = indentLine(cm, range$$1.head.line, "smart"); } 7923 } 7924 if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } 7925 } 7926 } 7927 7928 function copyableRanges(cm) { 7929 var text = [], ranges = []; 7930 for (var i = 0; i < cm.doc.sel.ranges.length; i++) { 7931 var line = cm.doc.sel.ranges[i].head.line; 7932 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; 7933 ranges.push(lineRange); 7934 text.push(cm.getRange(lineRange.anchor, lineRange.head)); 7935 } 7936 return {text: text, ranges: ranges} 7937 } 7938 7939 function disableBrowserMagic(field, spellcheck) { 7940 field.setAttribute("autocorrect", "off"); 7941 field.setAttribute("autocapitalize", "off"); 7942 field.setAttribute("spellcheck", !!spellcheck); 7943 } 7944 7945 function hiddenTextarea() { 7946 var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); 7947 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 7948 // The textarea is kept positioned near the cursor to prevent the 7949 // fact that it'll be scrolled into view on input from scrolling 7950 // our fake cursor out of view. On webkit, when wrap=off, paste is 7951 // very slow. So make the area wide instead. 7952 if (webkit) { te.style.width = "1000px"; } 7953 else { te.setAttribute("wrap", "off"); } 7954 // If border: 0; -- iOS fails to open keyboard (issue #1287) 7955 if (ios) { te.style.border = "1px solid black"; } 7956 disableBrowserMagic(te); 7957 return div 7958 } 7959 7960 // The publicly visible API. Note that methodOp(f) means 7961 // 'wrap f in an operation, performed on its `this` parameter'. 7962 7963 // This is not the complete set of editor methods. Most of the 7964 // methods defined on the Doc type are also injected into 7965 // CodeMirror.prototype, for backwards compatibility and 7966 // convenience. 7967 7968 var addEditorMethods = function(CodeMirror) { 7969 var optionHandlers = CodeMirror.optionHandlers; 7970 7971 var helpers = CodeMirror.helpers = {}; 7972 7973 CodeMirror.prototype = { 7974 constructor: CodeMirror, 7975 focus: function(){window.focus(); this.display.input.focus();}, 7976 7977 setOption: function(option, value) { 7978 var options = this.options, old = options[option]; 7979 if (options[option] == value && option != "mode") { return } 7980 options[option] = value; 7981 if (optionHandlers.hasOwnProperty(option)) 7982 { operation(this, optionHandlers[option])(this, value, old); } 7983 signal(this, "optionChange", this, option); 7984 }, 7985 7986 getOption: function(option) {return this.options[option]}, 7987 getDoc: function() {return this.doc}, 7988 7989 addKeyMap: function(map$$1, bottom) { 7990 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); 7991 }, 7992 removeKeyMap: function(map$$1) { 7993 var maps = this.state.keyMaps; 7994 for (var i = 0; i < maps.length; ++i) 7995 { if (maps[i] == map$$1 || maps[i].name == map$$1) { 7996 maps.splice(i, 1); 7997 return true 7998 } } 7999 }, 8000 8001 addOverlay: methodOp(function(spec, options) { 8002 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 8003 if (mode.startState) { throw new Error("Overlays may not be stateful.") } 8004 insertSorted(this.state.overlays, 8005 {mode: mode, modeSpec: spec, opaque: options && options.opaque, 8006 priority: (options && options.priority) || 0}, 8007 function (overlay) { return overlay.priority; }); 8008 this.state.modeGen++; 8009 regChange(this); 8010 }), 8011 removeOverlay: methodOp(function(spec) { 8012 var this$1 = this; 8013 8014 var overlays = this.state.overlays; 8015 for (var i = 0; i < overlays.length; ++i) { 8016 var cur = overlays[i].modeSpec; 8017 if (cur == spec || typeof spec == "string" && cur.name == spec) { 8018 overlays.splice(i, 1); 8019 this$1.state.modeGen++; 8020 regChange(this$1); 8021 return 8022 } 8023 } 8024 }), 8025 8026 indentLine: methodOp(function(n, dir, aggressive) { 8027 if (typeof dir != "string" && typeof dir != "number") { 8028 if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } 8029 else { dir = dir ? "add" : "subtract"; } 8030 } 8031 if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } 8032 }), 8033 indentSelection: methodOp(function(how) { 8034 var this$1 = this; 8035 8036 var ranges = this.doc.sel.ranges, end = -1; 8037 for (var i = 0; i < ranges.length; i++) { 8038 var range$$1 = ranges[i]; 8039 if (!range$$1.empty()) { 8040 var from = range$$1.from(), to = range$$1.to(); 8041 var start = Math.max(end, from.line); 8042 end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; 8043 for (var j = start; j < end; ++j) 8044 { indentLine(this$1, j, how); } 8045 var newRanges = this$1.doc.sel.ranges; 8046 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) 8047 { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } 8048 } else if (range$$1.head.line > end) { 8049 indentLine(this$1, range$$1.head.line, how, true); 8050 end = range$$1.head.line; 8051 if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } 8052 } 8053 } 8054 }), 8055 8056 // Fetch the parser token for a given character. Useful for hacks 8057 // that want to inspect the mode state (say, for completion). 8058 getTokenAt: function(pos, precise) { 8059 return takeToken(this, pos, precise) 8060 }, 8061 8062 getLineTokens: function(line, precise) { 8063 return takeToken(this, Pos(line), precise, true) 8064 }, 8065 8066 getTokenTypeAt: function(pos) { 8067 pos = clipPos(this.doc, pos); 8068 var styles = getLineStyles(this, getLine(this.doc, pos.line)); 8069 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; 8070 var type; 8071 if (ch == 0) { type = styles[2]; } 8072 else { for (;;) { 8073 var mid = (before + after) >> 1; 8074 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } 8075 else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } 8076 else { type = styles[mid * 2 + 2]; break } 8077 } } 8078 var cut = type ? type.indexOf("overlay ") : -1; 8079 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) 8080 }, 8081 8082 getModeAt: function(pos) { 8083 var mode = this.doc.mode; 8084 if (!mode.innerMode) { return mode } 8085 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode 8086 }, 8087 8088 getHelper: function(pos, type) { 8089 return this.getHelpers(pos, type)[0] 8090 }, 8091 8092 getHelpers: function(pos, type) { 8093 var this$1 = this; 8094 8095 var found = []; 8096 if (!helpers.hasOwnProperty(type)) { return found } 8097 var help = helpers[type], mode = this.getModeAt(pos); 8098 if (typeof mode[type] == "string") { 8099 if (help[mode[type]]) { found.push(help[mode[type]]); } 8100 } else if (mode[type]) { 8101 for (var i = 0; i < mode[type].length; i++) { 8102 var val = help[mode[type][i]]; 8103 if (val) { found.push(val); } 8104 } 8105 } else if (mode.helperType && help[mode.helperType]) { 8106 found.push(help[mode.helperType]); 8107 } else if (help[mode.name]) { 8108 found.push(help[mode.name]); 8109 } 8110 for (var i$1 = 0; i$1 < help._global.length; i$1++) { 8111 var cur = help._global[i$1]; 8112 if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) 8113 { found.push(cur.val); } 8114 } 8115 return found 8116 }, 8117 8118 getStateAfter: function(line, precise) { 8119 var doc = this.doc; 8120 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 8121 return getContextBefore(this, line + 1, precise).state 8122 }, 8123 8124 cursorCoords: function(start, mode) { 8125 var pos, range$$1 = this.doc.sel.primary(); 8126 if (start == null) { pos = range$$1.head; } 8127 else if (typeof start == "object") { pos = clipPos(this.doc, start); } 8128 else { pos = start ? range$$1.from() : range$$1.to(); } 8129 return cursorCoords(this, pos, mode || "page") 8130 }, 8131 8132 charCoords: function(pos, mode) { 8133 return charCoords(this, clipPos(this.doc, pos), mode || "page") 8134 }, 8135 8136 coordsChar: function(coords, mode) { 8137 coords = fromCoordSystem(this, coords, mode || "page"); 8138 return coordsChar(this, coords.left, coords.top) 8139 }, 8140 8141 lineAtHeight: function(height, mode) { 8142 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; 8143 return lineAtHeight(this.doc, height + this.display.viewOffset) 8144 }, 8145 heightAtLine: function(line, mode, includeWidgets) { 8146 var end = false, lineObj; 8147 if (typeof line == "number") { 8148 var last = this.doc.first + this.doc.size - 1; 8149 if (line < this.doc.first) { line = this.doc.first; } 8150 else if (line > last) { line = last; end = true; } 8151 lineObj = getLine(this.doc, line); 8152 } else { 8153 lineObj = line; 8154 } 8155 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + 8156 (end ? this.doc.height - heightAtLine(lineObj) : 0) 8157 }, 8158 8159 defaultTextHeight: function() { return textHeight(this.display) }, 8160 defaultCharWidth: function() { return charWidth(this.display) }, 8161 8162 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, 8163 8164 addWidget: function(pos, node, scroll, vert, horiz) { 8165 var display = this.display; 8166 pos = cursorCoords(this, clipPos(this.doc, pos)); 8167 var top = pos.bottom, left = pos.left; 8168 node.style.position = "absolute"; 8169 node.setAttribute("cm-ignore-events", "true"); 8170 this.display.input.setUneditable(node); 8171 display.sizer.appendChild(node); 8172 if (vert == "over") { 8173 top = pos.top; 8174 } else if (vert == "above" || vert == "near") { 8175 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 8176 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 8177 // Default to positioning above (if specified and possible); otherwise default to positioning below 8178 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 8179 { top = pos.top - node.offsetHeight; } 8180 else if (pos.bottom + node.offsetHeight <= vspace) 8181 { top = pos.bottom; } 8182 if (left + node.offsetWidth > hspace) 8183 { left = hspace - node.offsetWidth; } 8184 } 8185 node.style.top = top + "px"; 8186 node.style.left = node.style.right = ""; 8187 if (horiz == "right") { 8188 left = display.sizer.clientWidth - node.offsetWidth; 8189 node.style.right = "0px"; 8190 } else { 8191 if (horiz == "left") { left = 0; } 8192 else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } 8193 node.style.left = left + "px"; 8194 } 8195 if (scroll) 8196 { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } 8197 }, 8198 8199 triggerOnKeyDown: methodOp(onKeyDown), 8200 triggerOnKeyPress: methodOp(onKeyPress), 8201 triggerOnKeyUp: onKeyUp, 8202 triggerOnMouseDown: methodOp(onMouseDown), 8203 8204 execCommand: function(cmd) { 8205 if (commands.hasOwnProperty(cmd)) 8206 { return commands[cmd].call(null, this) } 8207 }, 8208 8209 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), 8210 8211 findPosH: function(from, amount, unit, visually) { 8212 var this$1 = this; 8213 8214 var dir = 1; 8215 if (amount < 0) { dir = -1; amount = -amount; } 8216 var cur = clipPos(this.doc, from); 8217 for (var i = 0; i < amount; ++i) { 8218 cur = findPosH(this$1.doc, cur, dir, unit, visually); 8219 if (cur.hitSide) { break } 8220 } 8221 return cur 8222 }, 8223 8224 moveH: methodOp(function(dir, unit) { 8225 var this$1 = this; 8226 8227 this.extendSelectionsBy(function (range$$1) { 8228 if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) 8229 { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } 8230 else 8231 { return dir < 0 ? range$$1.from() : range$$1.to() } 8232 }, sel_move); 8233 }), 8234 8235 deleteH: methodOp(function(dir, unit) { 8236 var sel = this.doc.sel, doc = this.doc; 8237 if (sel.somethingSelected()) 8238 { doc.replaceSelection("", null, "+delete"); } 8239 else 8240 { deleteNearSelection(this, function (range$$1) { 8241 var other = findPosH(doc, range$$1.head, dir, unit, false); 8242 return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} 8243 }); } 8244 }), 8245 8246 findPosV: function(from, amount, unit, goalColumn) { 8247 var this$1 = this; 8248 8249 var dir = 1, x = goalColumn; 8250 if (amount < 0) { dir = -1; amount = -amount; } 8251 var cur = clipPos(this.doc, from); 8252 for (var i = 0; i < amount; ++i) { 8253 var coords = cursorCoords(this$1, cur, "div"); 8254 if (x == null) { x = coords.left; } 8255 else { coords.left = x; } 8256 cur = findPosV(this$1, coords, dir, unit); 8257 if (cur.hitSide) { break } 8258 } 8259 return cur 8260 }, 8261 8262 moveV: methodOp(function(dir, unit) { 8263 var this$1 = this; 8264 8265 var doc = this.doc, goals = []; 8266 var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); 8267 doc.extendSelectionsBy(function (range$$1) { 8268 if (collapse) 8269 { return dir < 0 ? range$$1.from() : range$$1.to() } 8270 var headPos = cursorCoords(this$1, range$$1.head, "div"); 8271 if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } 8272 goals.push(headPos.left); 8273 var pos = findPosV(this$1, headPos, dir, unit); 8274 if (unit == "page" && range$$1 == doc.sel.primary()) 8275 { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } 8276 return pos 8277 }, sel_move); 8278 if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) 8279 { doc.sel.ranges[i].goalColumn = goals[i]; } } 8280 }), 8281 8282 // Find the word at the given position (as returned by coordsChar). 8283 findWordAt: function(pos) { 8284 var doc = this.doc, line = getLine(doc, pos.line).text; 8285 var start = pos.ch, end = pos.ch; 8286 if (line) { 8287 var helper = this.getHelper(pos, "wordChars"); 8288 if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } 8289 var startChar = line.charAt(start); 8290 var check = isWordChar(startChar, helper) 8291 ? function (ch) { return isWordChar(ch, helper); } 8292 : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } 8293 : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; 8294 while (start > 0 && check(line.charAt(start - 1))) { --start; } 8295 while (end < line.length && check(line.charAt(end))) { ++end; } 8296 } 8297 return new Range(Pos(pos.line, start), Pos(pos.line, end)) 8298 }, 8299 8300 toggleOverwrite: function(value) { 8301 if (value != null && value == this.state.overwrite) { return } 8302 if (this.state.overwrite = !this.state.overwrite) 8303 { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8304 else 8305 { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8306 8307 signal(this, "overwriteToggle", this, this.state.overwrite); 8308 }, 8309 hasFocus: function() { return this.display.input.getField() == activeElt() }, 8310 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, 8311 8312 scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), 8313 getScrollInfo: function() { 8314 var scroller = this.display.scroller; 8315 return {left: scroller.scrollLeft, top: scroller.scrollTop, 8316 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, 8317 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, 8318 clientHeight: displayHeight(this), clientWidth: displayWidth(this)} 8319 }, 8320 8321 scrollIntoView: methodOp(function(range$$1, margin) { 8322 if (range$$1 == null) { 8323 range$$1 = {from: this.doc.sel.primary().head, to: null}; 8324 if (margin == null) { margin = this.options.cursorScrollMargin; } 8325 } else if (typeof range$$1 == "number") { 8326 range$$1 = {from: Pos(range$$1, 0), to: null}; 8327 } else if (range$$1.from == null) { 8328 range$$1 = {from: range$$1, to: null}; 8329 } 8330 if (!range$$1.to) { range$$1.to = range$$1.from; } 8331 range$$1.margin = margin || 0; 8332 8333 if (range$$1.from.line != null) { 8334 scrollToRange(this, range$$1); 8335 } else { 8336 scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); 8337 } 8338 }), 8339 8340 setSize: methodOp(function(width, height) { 8341 var this$1 = this; 8342 8343 var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; 8344 if (width != null) { this.display.wrapper.style.width = interpret(width); } 8345 if (height != null) { this.display.wrapper.style.height = interpret(height); } 8346 if (this.options.lineWrapping) { clearLineMeasurementCache(this); } 8347 var lineNo$$1 = this.display.viewFrom; 8348 this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { 8349 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) 8350 { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } 8351 ++lineNo$$1; 8352 }); 8353 this.curOp.forceUpdate = true; 8354 signal(this, "refresh", this); 8355 }), 8356 8357 operation: function(f){return runInOp(this, f)}, 8358 8359 refresh: methodOp(function() { 8360 var oldHeight = this.display.cachedTextHeight; 8361 regChange(this); 8362 this.curOp.forceUpdate = true; 8363 clearCaches(this); 8364 scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); 8365 updateGutterSpace(this); 8366 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) 8367 { estimateLineHeights(this); } 8368 signal(this, "refresh", this); 8369 }), 8370 8371 swapDoc: methodOp(function(doc) { 8372 var old = this.doc; 8373 old.cm = null; 8374 attachDoc(this, doc); 8375 clearCaches(this); 8376 this.display.input.reset(); 8377 scrollToCoords(this, doc.scrollLeft, doc.scrollTop); 8378 this.curOp.forceScroll = true; 8379 signalLater(this, "swapDoc", this, old); 8380 return old 8381 }), 8382 8383 getInputField: function(){return this.display.input.getField()}, 8384 getWrapperElement: function(){return this.display.wrapper}, 8385 getScrollerElement: function(){return this.display.scroller}, 8386 getGutterElement: function(){return this.display.gutters} 8387 }; 8388 eventMixin(CodeMirror); 8389 8390 CodeMirror.registerHelper = function(type, name, value) { 8391 if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } 8392 helpers[type][name] = value; 8393 }; 8394 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { 8395 CodeMirror.registerHelper(type, name, value); 8396 helpers[type]._global.push({pred: predicate, val: value}); 8397 }; 8398 }; 8399 8400 // Used for horizontal relative motion. Dir is -1 or 1 (left or 8401 // right), unit can be "char", "column" (like char, but doesn't 8402 // cross line boundaries), "word" (across next word), or "group" (to 8403 // the start of next group of word or non-word-non-whitespace 8404 // chars). The visually param controls whether, in right-to-left 8405 // text, direction 1 means to move towards the next index in the 8406 // string, or towards the character to the right of the current 8407 // position. The resulting position will have a hitSide=true 8408 // property if it reached the end of the document. 8409 function findPosH(doc, pos, dir, unit, visually) { 8410 var oldPos = pos; 8411 var origDir = dir; 8412 var lineObj = getLine(doc, pos.line); 8413 function findNextLine() { 8414 var l = pos.line + dir; 8415 if (l < doc.first || l >= doc.first + doc.size) { return false } 8416 pos = new Pos(l, pos.ch, pos.sticky); 8417 return lineObj = getLine(doc, l) 8418 } 8419 function moveOnce(boundToLine) { 8420 var next; 8421 if (visually) { 8422 next = moveVisually(doc.cm, lineObj, pos, dir); 8423 } else { 8424 next = moveLogically(lineObj, pos, dir); 8425 } 8426 if (next == null) { 8427 if (!boundToLine && findNextLine()) 8428 { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } 8429 else 8430 { return false } 8431 } else { 8432 pos = next; 8433 } 8434 return true 8435 } 8436 8437 if (unit == "char") { 8438 moveOnce(); 8439 } else if (unit == "column") { 8440 moveOnce(true); 8441 } else if (unit == "word" || unit == "group") { 8442 var sawType = null, group = unit == "group"; 8443 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); 8444 for (var first = true;; first = false) { 8445 if (dir < 0 && !moveOnce(!first)) { break } 8446 var cur = lineObj.text.charAt(pos.ch) || "\n"; 8447 var type = isWordChar(cur, helper) ? "w" 8448 : group && cur == "\n" ? "n" 8449 : !group || /\s/.test(cur) ? null 8450 : "p"; 8451 if (group && !first && !type) { type = "s"; } 8452 if (sawType && sawType != type) { 8453 if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} 8454 break 8455 } 8456 8457 if (type) { sawType = type; } 8458 if (dir > 0 && !moveOnce(!first)) { break } 8459 } 8460 } 8461 var result = skipAtomic(doc, pos, oldPos, origDir, true); 8462 if (equalCursorPos(oldPos, result)) { result.hitSide = true; } 8463 return result 8464 } 8465 8466 // For relative vertical movement. Dir may be -1 or 1. Unit can be 8467 // "page" or "line". The resulting position will have a hitSide=true 8468 // property if it reached the end of the document. 8469 function findPosV(cm, pos, dir, unit) { 8470 var doc = cm.doc, x = pos.left, y; 8471 if (unit == "page") { 8472 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 8473 var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); 8474 y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; 8475 8476 } else if (unit == "line") { 8477 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 8478 } 8479 var target; 8480 for (;;) { 8481 target = coordsChar(cm, x, y); 8482 if (!target.outside) { break } 8483 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } 8484 y += dir * 5; 8485 } 8486 return target 8487 } 8488 8489 // CONTENTEDITABLE INPUT STYLE 8490 8491 var ContentEditableInput = function(cm) { 8492 this.cm = cm; 8493 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; 8494 this.polling = new Delayed(); 8495 this.composing = null; 8496 this.gracePeriod = false; 8497 this.readDOMTimeout = null; 8498 }; 8499 8500 ContentEditableInput.prototype.init = function (display) { 8501 var this$1 = this; 8502 8503 var input = this, cm = input.cm; 8504 var div = input.div = display.lineDiv; 8505 disableBrowserMagic(div, cm.options.spellcheck); 8506 8507 on(div, "paste", function (e) { 8508 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 8509 // IE doesn't fire input events, so we schedule a read for the pasted content in this way 8510 if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } 8511 }); 8512 8513 on(div, "compositionstart", function (e) { 8514 this$1.composing = {data: e.data, done: false}; 8515 }); 8516 on(div, "compositionupdate", function (e) { 8517 if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } 8518 }); 8519 on(div, "compositionend", function (e) { 8520 if (this$1.composing) { 8521 if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } 8522 this$1.composing.done = true; 8523 } 8524 }); 8525 8526 on(div, "touchstart", function () { return input.forceCompositionEnd(); }); 8527 8528 on(div, "input", function () { 8529 if (!this$1.composing) { this$1.readFromDOMSoon(); } 8530 }); 8531 8532 function onCopyCut(e) { 8533 if (signalDOMEvent(cm, e)) { return } 8534 if (cm.somethingSelected()) { 8535 setLastCopied({lineWise: false, text: cm.getSelections()}); 8536 if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } 8537 } else if (!cm.options.lineWiseCopyCut) { 8538 return 8539 } else { 8540 var ranges = copyableRanges(cm); 8541 setLastCopied({lineWise: true, text: ranges.text}); 8542 if (e.type == "cut") { 8543 cm.operation(function () { 8544 cm.setSelections(ranges.ranges, 0, sel_dontScroll); 8545 cm.replaceSelection("", null, "cut"); 8546 }); 8547 } 8548 } 8549 if (e.clipboardData) { 8550 e.clipboardData.clearData(); 8551 var content = lastCopied.text.join("\n"); 8552 // iOS exposes the clipboard API, but seems to discard content inserted into it 8553 e.clipboardData.setData("Text", content); 8554 if (e.clipboardData.getData("Text") == content) { 8555 e.preventDefault(); 8556 return 8557 } 8558 } 8559 // Old-fashioned briefly-focus-a-textarea hack 8560 var kludge = hiddenTextarea(), te = kludge.firstChild; 8561 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); 8562 te.value = lastCopied.text.join("\n"); 8563 var hadFocus = document.activeElement; 8564 selectInput(te); 8565 setTimeout(function () { 8566 cm.display.lineSpace.removeChild(kludge); 8567 hadFocus.focus(); 8568 if (hadFocus == div) { input.showPrimarySelection(); } 8569 }, 50); 8570 } 8571 on(div, "copy", onCopyCut); 8572 on(div, "cut", onCopyCut); 8573 }; 8574 8575 ContentEditableInput.prototype.prepareSelection = function () { 8576 var result = prepareSelection(this.cm, false); 8577 result.focus = this.cm.state.focused; 8578 return result 8579 }; 8580 8581 ContentEditableInput.prototype.showSelection = function (info, takeFocus) { 8582 if (!info || !this.cm.display.view.length) { return } 8583 if (info.focus || takeFocus) { this.showPrimarySelection(); } 8584 this.showMultipleSelections(info); 8585 }; 8586 8587 ContentEditableInput.prototype.showPrimarySelection = function () { 8588 var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); 8589 var from = prim.from(), to = prim.to(); 8590 8591 if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { 8592 sel.removeAllRanges(); 8593 return 8594 } 8595 8596 var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8597 var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); 8598 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && 8599 cmp(minPos(curAnchor, curFocus), from) == 0 && 8600 cmp(maxPos(curAnchor, curFocus), to) == 0) 8601 { return } 8602 8603 var view = cm.display.view; 8604 var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || 8605 {node: view[0].measure.map[2], offset: 0}; 8606 var end = to.line < cm.display.viewTo && posToDOM(cm, to); 8607 if (!end) { 8608 var measure = view[view.length - 1].measure; 8609 var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; 8610 end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; 8611 } 8612 8613 if (!start || !end) { 8614 sel.removeAllRanges(); 8615 return 8616 } 8617 8618 var old = sel.rangeCount && sel.getRangeAt(0), rng; 8619 try { rng = range(start.node, start.offset, end.offset, end.node); } 8620 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible 8621 if (rng) { 8622 if (!gecko && cm.state.focused) { 8623 sel.collapse(start.node, start.offset); 8624 if (!rng.collapsed) { 8625 sel.removeAllRanges(); 8626 sel.addRange(rng); 8627 } 8628 } else { 8629 sel.removeAllRanges(); 8630 sel.addRange(rng); 8631 } 8632 if (old && sel.anchorNode == null) { sel.addRange(old); } 8633 else if (gecko) { this.startGracePeriod(); } 8634 } 8635 this.rememberSelection(); 8636 }; 8637 8638 ContentEditableInput.prototype.startGracePeriod = function () { 8639 var this$1 = this; 8640 8641 clearTimeout(this.gracePeriod); 8642 this.gracePeriod = setTimeout(function () { 8643 this$1.gracePeriod = false; 8644 if (this$1.selectionChanged()) 8645 { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } 8646 }, 20); 8647 }; 8648 8649 ContentEditableInput.prototype.showMultipleSelections = function (info) { 8650 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); 8651 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); 8652 }; 8653 8654 ContentEditableInput.prototype.rememberSelection = function () { 8655 var sel = window.getSelection(); 8656 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; 8657 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; 8658 }; 8659 8660 ContentEditableInput.prototype.selectionInEditor = function () { 8661 var sel = window.getSelection(); 8662 if (!sel.rangeCount) { return false } 8663 var node = sel.getRangeAt(0).commonAncestorContainer; 8664 return contains(this.div, node) 8665 }; 8666 8667 ContentEditableInput.prototype.focus = function () { 8668 if (this.cm.options.readOnly != "nocursor") { 8669 if (!this.selectionInEditor()) 8670 { this.showSelection(this.prepareSelection(), true); } 8671 this.div.focus(); 8672 } 8673 }; 8674 ContentEditableInput.prototype.blur = function () { this.div.blur(); }; 8675 ContentEditableInput.prototype.getField = function () { return this.div }; 8676 8677 ContentEditableInput.prototype.supportsTouch = function () { return true }; 8678 8679 ContentEditableInput.prototype.receivedFocus = function () { 8680 var input = this; 8681 if (this.selectionInEditor()) 8682 { this.pollSelection(); } 8683 else 8684 { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } 8685 8686 function poll() { 8687 if (input.cm.state.focused) { 8688 input.pollSelection(); 8689 input.polling.set(input.cm.options.pollInterval, poll); 8690 } 8691 } 8692 this.polling.set(this.cm.options.pollInterval, poll); 8693 }; 8694 8695 ContentEditableInput.prototype.selectionChanged = function () { 8696 var sel = window.getSelection(); 8697 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || 8698 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset 8699 }; 8700 8701 ContentEditableInput.prototype.pollSelection = function () { 8702 if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } 8703 var sel = window.getSelection(), cm = this.cm; 8704 // On Android Chrome (version 56, at least), backspacing into an 8705 // uneditable block element will put the cursor in that element, 8706 // and then, because it's not editable, hide the virtual keyboard. 8707 // Because Android doesn't allow us to actually detect backspace 8708 // presses in a sane way, this code checks for when that happens 8709 // and simulates a backspace press in this case. 8710 if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { 8711 this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); 8712 this.blur(); 8713 this.focus(); 8714 return 8715 } 8716 if (this.composing) { return } 8717 this.rememberSelection(); 8718 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8719 var head = domToPos(cm, sel.focusNode, sel.focusOffset); 8720 if (anchor && head) { runInOp(cm, function () { 8721 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); 8722 if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } 8723 }); } 8724 }; 8725 8726 ContentEditableInput.prototype.pollContent = function () { 8727 if (this.readDOMTimeout != null) { 8728 clearTimeout(this.readDOMTimeout); 8729 this.readDOMTimeout = null; 8730 } 8731 8732 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); 8733 var from = sel.from(), to = sel.to(); 8734 if (from.ch == 0 && from.line > cm.firstLine()) 8735 { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } 8736 if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) 8737 { to = Pos(to.line + 1, 0); } 8738 if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } 8739 8740 var fromIndex, fromLine, fromNode; 8741 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { 8742 fromLine = lineNo(display.view[0].line); 8743 fromNode = display.view[0].node; 8744 } else { 8745 fromLine = lineNo(display.view[fromIndex].line); 8746 fromNode = display.view[fromIndex - 1].node.nextSibling; 8747 } 8748 var toIndex = findViewIndex(cm, to.line); 8749 var toLine, toNode; 8750 if (toIndex == display.view.length - 1) { 8751 toLine = display.viewTo - 1; 8752 toNode = display.lineDiv.lastChild; 8753 } else { 8754 toLine = lineNo(display.view[toIndex + 1].line) - 1; 8755 toNode = display.view[toIndex + 1].node.previousSibling; 8756 } 8757 8758 if (!fromNode) { return false } 8759 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); 8760 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); 8761 while (newText.length > 1 && oldText.length > 1) { 8762 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } 8763 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } 8764 else { break } 8765 } 8766 8767 var cutFront = 0, cutEnd = 0; 8768 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); 8769 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) 8770 { ++cutFront; } 8771 var newBot = lst(newText), oldBot = lst(oldText); 8772 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), 8773 oldBot.length - (oldText.length == 1 ? cutFront : 0)); 8774 while (cutEnd < maxCutEnd && 8775 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) 8776 { ++cutEnd; } 8777 // Try to move start of change to start of selection if ambiguous 8778 if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { 8779 while (cutFront && cutFront > from.ch && 8780 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { 8781 cutFront--; 8782 cutEnd++; 8783 } 8784 } 8785 8786 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); 8787 newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); 8788 8789 var chFrom = Pos(fromLine, cutFront); 8790 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); 8791 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { 8792 replaceRange(cm.doc, newText, chFrom, chTo, "+input"); 8793 return true 8794 } 8795 }; 8796 8797 ContentEditableInput.prototype.ensurePolled = function () { 8798 this.forceCompositionEnd(); 8799 }; 8800 ContentEditableInput.prototype.reset = function () { 8801 this.forceCompositionEnd(); 8802 }; 8803 ContentEditableInput.prototype.forceCompositionEnd = function () { 8804 if (!this.composing) { return } 8805 clearTimeout(this.readDOMTimeout); 8806 this.composing = null; 8807 this.updateFromDOM(); 8808 this.div.blur(); 8809 this.div.focus(); 8810 }; 8811 ContentEditableInput.prototype.readFromDOMSoon = function () { 8812 var this$1 = this; 8813 8814 if (this.readDOMTimeout != null) { return } 8815 this.readDOMTimeout = setTimeout(function () { 8816 this$1.readDOMTimeout = null; 8817 if (this$1.composing) { 8818 if (this$1.composing.done) { this$1.composing = null; } 8819 else { return } 8820 } 8821 this$1.updateFromDOM(); 8822 }, 80); 8823 }; 8824 8825 ContentEditableInput.prototype.updateFromDOM = function () { 8826 var this$1 = this; 8827 8828 if (this.cm.isReadOnly() || !this.pollContent()) 8829 { runInOp(this.cm, function () { return regChange(this$1.cm); }); } 8830 }; 8831 8832 ContentEditableInput.prototype.setUneditable = function (node) { 8833 node.contentEditable = "false"; 8834 }; 8835 8836 ContentEditableInput.prototype.onKeyPress = function (e) { 8837 if (e.charCode == 0) { return } 8838 e.preventDefault(); 8839 if (!this.cm.isReadOnly()) 8840 { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } 8841 }; 8842 8843 ContentEditableInput.prototype.readOnlyChanged = function (val) { 8844 this.div.contentEditable = String(val != "nocursor"); 8845 }; 8846 8847 ContentEditableInput.prototype.onContextMenu = function () {}; 8848 ContentEditableInput.prototype.resetPosition = function () {}; 8849 8850 ContentEditableInput.prototype.needsContentAttribute = true; 8851 8852 function posToDOM(cm, pos) { 8853 var view = findViewForLine(cm, pos.line); 8854 if (!view || view.hidden) { return null } 8855 var line = getLine(cm.doc, pos.line); 8856 var info = mapFromLineView(view, line, pos.line); 8857 8858 var order = getOrder(line, cm.doc.direction), side = "left"; 8859 if (order) { 8860 var partPos = getBidiPartAt(order, pos.ch); 8861 side = partPos % 2 ? "right" : "left"; 8862 } 8863 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); 8864 result.offset = result.collapse == "right" ? result.end : result.start; 8865 return result 8866 } 8867 8868 function isInGutter(node) { 8869 for (var scan = node; scan; scan = scan.parentNode) 8870 { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } 8871 return false 8872 } 8873 8874 function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } 8875 8876 function domTextBetween(cm, from, to, fromLine, toLine) { 8877 var text = "", closing = false, lineSep = cm.doc.lineSeparator(); 8878 function recognizeMarker(id) { return function (marker) { return marker.id == id; } } 8879 function close() { 8880 if (closing) { 8881 text += lineSep; 8882 closing = false; 8883 } 8884 } 8885 function addText(str) { 8886 if (str) { 8887 close(); 8888 text += str; 8889 } 8890 } 8891 function walk(node) { 8892 if (node.nodeType == 1) { 8893 var cmText = node.getAttribute("cm-text"); 8894 if (cmText != null) { 8895 addText(cmText || node.textContent.replace(/\u200b/g, "")); 8896 return 8897 } 8898 var markerID = node.getAttribute("cm-marker"), range$$1; 8899 if (markerID) { 8900 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); 8901 if (found.length && (range$$1 = found[0].find())) 8902 { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } 8903 return 8904 } 8905 if (node.getAttribute("contenteditable") == "false") { return } 8906 var isBlock = /^(pre|div|p)$/i.test(node.nodeName); 8907 if (isBlock) { close(); } 8908 for (var i = 0; i < node.childNodes.length; i++) 8909 { walk(node.childNodes[i]); } 8910 if (isBlock) { closing = true; } 8911 } else if (node.nodeType == 3) { 8912 addText(node.nodeValue); 8913 } 8914 } 8915 for (;;) { 8916 walk(from); 8917 if (from == to) { break } 8918 from = from.nextSibling; 8919 } 8920 return text 8921 } 8922 8923 function domToPos(cm, node, offset) { 8924 var lineNode; 8925 if (node == cm.display.lineDiv) { 8926 lineNode = cm.display.lineDiv.childNodes[offset]; 8927 if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } 8928 node = null; offset = 0; 8929 } else { 8930 for (lineNode = node;; lineNode = lineNode.parentNode) { 8931 if (!lineNode || lineNode == cm.display.lineDiv) { return null } 8932 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } 8933 } 8934 } 8935 for (var i = 0; i < cm.display.view.length; i++) { 8936 var lineView = cm.display.view[i]; 8937 if (lineView.node == lineNode) 8938 { return locateNodeInLineView(lineView, node, offset) } 8939 } 8940 } 8941 8942 function locateNodeInLineView(lineView, node, offset) { 8943 var wrapper = lineView.text.firstChild, bad = false; 8944 if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } 8945 if (node == wrapper) { 8946 bad = true; 8947 node = wrapper.childNodes[offset]; 8948 offset = 0; 8949 if (!node) { 8950 var line = lineView.rest ? lst(lineView.rest) : lineView.line; 8951 return badPos(Pos(lineNo(line), line.text.length), bad) 8952 } 8953 } 8954 8955 var textNode = node.nodeType == 3 ? node : null, topNode = node; 8956 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { 8957 textNode = node.firstChild; 8958 if (offset) { offset = textNode.nodeValue.length; } 8959 } 8960 while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } 8961 var measure = lineView.measure, maps = measure.maps; 8962 8963 function find(textNode, topNode, offset) { 8964 for (var i = -1; i < (maps ? maps.length : 0); i++) { 8965 var map$$1 = i < 0 ? measure.map : maps[i]; 8966 for (var j = 0; j < map$$1.length; j += 3) { 8967 var curNode = map$$1[j + 2]; 8968 if (curNode == textNode || curNode == topNode) { 8969 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); 8970 var ch = map$$1[j] + offset; 8971 if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } 8972 return Pos(line, ch) 8973 } 8974 } 8975 } 8976 } 8977 var found = find(textNode, topNode, offset); 8978 if (found) { return badPos(found, bad) } 8979 8980 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems 8981 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { 8982 found = find(after, after.firstChild, 0); 8983 if (found) 8984 { return badPos(Pos(found.line, found.ch - dist), bad) } 8985 else 8986 { dist += after.textContent.length; } 8987 } 8988 for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { 8989 found = find(before, before.firstChild, -1); 8990 if (found) 8991 { return badPos(Pos(found.line, found.ch + dist$1), bad) } 8992 else 8993 { dist$1 += before.textContent.length; } 8994 } 8995 } 8996 8997 // TEXTAREA INPUT STYLE 8998 8999 var TextareaInput = function(cm) { 9000 this.cm = cm; 9001 // See input.poll and input.reset 9002 this.prevInput = ""; 9003 9004 // Flag that indicates whether we expect input to appear real soon 9005 // now (after some event like 'keypress' or 'input') and are 9006 // polling intensively. 9007 this.pollingFast = false; 9008 // Self-resetting timeout for the poller 9009 this.polling = new Delayed(); 9010 // Tracks when input.reset has punted to just putting a short 9011 // string into the textarea instead of the full selection. 9012 this.inaccurateSelection = false; 9013 // Used to work around IE issue with selection being forgotten when focus moves away from textarea 9014 this.hasSelection = false; 9015 this.composing = null; 9016 }; 9017 9018 TextareaInput.prototype.init = function (display) { 9019 var this$1 = this; 9020 9021 var input = this, cm = this.cm; 9022 9023 // Wraps and hides input textarea 9024 var div = this.wrapper = hiddenTextarea(); 9025 // The semihidden textarea that is focused when the editor is 9026 // focused, and receives input. 9027 var te = this.textarea = div.firstChild; 9028 display.wrapper.insertBefore(div, display.wrapper.firstChild); 9029 9030 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) 9031 if (ios) { te.style.width = "0px"; } 9032 9033 on(te, "input", function () { 9034 if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } 9035 input.poll(); 9036 }); 9037 9038 on(te, "paste", function (e) { 9039 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 9040 9041 cm.state.pasteIncoming = true; 9042 input.fastPoll(); 9043 }); 9044 9045 function prepareCopyCut(e) { 9046 if (signalDOMEvent(cm, e)) { return } 9047 if (cm.somethingSelected()) { 9048 setLastCopied({lineWise: false, text: cm.getSelections()}); 9049 if (input.inaccurateSelection) { 9050 input.prevInput = ""; 9051 input.inaccurateSelection = false; 9052 te.value = lastCopied.text.join("\n"); 9053 selectInput(te); 9054 } 9055 } else if (!cm.options.lineWiseCopyCut) { 9056 return 9057 } else { 9058 var ranges = copyableRanges(cm); 9059 setLastCopied({lineWise: true, text: ranges.text}); 9060 if (e.type == "cut") { 9061 cm.setSelections(ranges.ranges, null, sel_dontScroll); 9062 } else { 9063 input.prevInput = ""; 9064 te.value = ranges.text.join("\n"); 9065 selectInput(te); 9066 } 9067 } 9068 if (e.type == "cut") { cm.state.cutIncoming = true; } 9069 } 9070 on(te, "cut", prepareCopyCut); 9071 on(te, "copy", prepareCopyCut); 9072 9073 on(display.scroller, "paste", function (e) { 9074 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } 9075 cm.state.pasteIncoming = true; 9076 input.focus(); 9077 }); 9078 9079 // Prevent normal selection in the editor (we handle our own) 9080 on(display.lineSpace, "selectstart", function (e) { 9081 if (!eventInWidget(display, e)) { e_preventDefault(e); } 9082 }); 9083 9084 on(te, "compositionstart", function () { 9085 var start = cm.getCursor("from"); 9086 if (input.composing) { input.composing.range.clear(); } 9087 input.composing = { 9088 start: start, 9089 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) 9090 }; 9091 }); 9092 on(te, "compositionend", function () { 9093 if (input.composing) { 9094 input.poll(); 9095 input.composing.range.clear(); 9096 input.composing = null; 9097 } 9098 }); 9099 }; 9100 9101 TextareaInput.prototype.prepareSelection = function () { 9102 // Redraw the selection and/or cursor 9103 var cm = this.cm, display = cm.display, doc = cm.doc; 9104 var result = prepareSelection(cm); 9105 9106 // Move the hidden textarea near the cursor to prevent scrolling artifacts 9107 if (cm.options.moveInputWithCursor) { 9108 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); 9109 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); 9110 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 9111 headPos.top + lineOff.top - wrapOff.top)); 9112 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 9113 headPos.left + lineOff.left - wrapOff.left)); 9114 } 9115 9116 return result 9117 }; 9118 9119 TextareaInput.prototype.showSelection = function (drawn) { 9120 var cm = this.cm, display = cm.display; 9121 removeChildrenAndAdd(display.cursorDiv, drawn.cursors); 9122 removeChildrenAndAdd(display.selectionDiv, drawn.selection); 9123 if (drawn.teTop != null) { 9124 this.wrapper.style.top = drawn.teTop + "px"; 9125 this.wrapper.style.left = drawn.teLeft + "px"; 9126 } 9127 }; 9128 9129 // Reset the input to correspond to the selection (or to be empty, 9130 // when not typing and nothing is selected) 9131 TextareaInput.prototype.reset = function (typing) { 9132 if (this.contextMenuPending || this.composing) { return } 9133 var minimal, selected, cm = this.cm, doc = cm.doc; 9134 if (cm.somethingSelected()) { 9135 this.prevInput = ""; 9136 var range$$1 = doc.sel.primary(); 9137 minimal = hasCopyEvent && 9138 (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000); 9139 var content = minimal ? "-" : selected || cm.getSelection(); 9140 this.textarea.value = content; 9141 if (cm.state.focused) { selectInput(this.textarea); } 9142 if (ie && ie_version >= 9) { this.hasSelection = content; } 9143 } else if (!typing) { 9144 this.prevInput = this.textarea.value = ""; 9145 if (ie && ie_version >= 9) { this.hasSelection = null; } 9146 } 9147 this.inaccurateSelection = minimal; 9148 }; 9149 9150 TextareaInput.prototype.getField = function () { return this.textarea }; 9151 9152 TextareaInput.prototype.supportsTouch = function () { return false }; 9153 9154 TextareaInput.prototype.focus = function () { 9155 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { 9156 try { this.textarea.focus(); } 9157 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM 9158 } 9159 }; 9160 9161 TextareaInput.prototype.blur = function () { this.textarea.blur(); }; 9162 9163 TextareaInput.prototype.resetPosition = function () { 9164 this.wrapper.style.top = this.wrapper.style.left = 0; 9165 }; 9166 9167 TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; 9168 9169 // Poll for input changes, using the normal rate of polling. This 9170 // runs as long as the editor is focused. 9171 TextareaInput.prototype.slowPoll = function () { 9172 var this$1 = this; 9173 9174 if (this.pollingFast) { return } 9175 this.polling.set(this.cm.options.pollInterval, function () { 9176 this$1.poll(); 9177 if (this$1.cm.state.focused) { this$1.slowPoll(); } 9178 }); 9179 }; 9180 9181 // When an event has just come in that is likely to add or change 9182 // something in the input textarea, we poll faster, to ensure that 9183 // the change appears on the screen quickly. 9184 TextareaInput.prototype.fastPoll = function () { 9185 var missed = false, input = this; 9186 input.pollingFast = true; 9187 function p() { 9188 var changed = input.poll(); 9189 if (!changed && !missed) {missed = true; input.polling.set(60, p);} 9190 else {input.pollingFast = false; input.slowPoll();} 9191 } 9192 input.polling.set(20, p); 9193 }; 9194 9195 // Read input from the textarea, and update the document to match. 9196 // When something is selected, it is present in the textarea, and 9197 // selected (unless it is huge, in which case a placeholder is 9198 // used). When nothing is selected, the cursor sits after previously 9199 // seen text (can be empty), which is stored in prevInput (we must 9200 // not reset the textarea when typing, because that breaks IME). 9201 TextareaInput.prototype.poll = function () { 9202 var this$1 = this; 9203 9204 var cm = this.cm, input = this.textarea, prevInput = this.prevInput; 9205 // Since this is called a *lot*, try to bail out as cheaply as 9206 // possible when it is clear that nothing happened. hasSelection 9207 // will be the case when there is a lot of text in the textarea, 9208 // in which case reading its value would be expensive. 9209 if (this.contextMenuPending || !cm.state.focused || 9210 (hasSelection(input) && !prevInput && !this.composing) || 9211 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) 9212 { return false } 9213 9214 var text = input.value; 9215 // If nothing changed, bail. 9216 if (text == prevInput && !cm.somethingSelected()) { return false } 9217 // Work around nonsensical selection resetting in IE9/10, and 9218 // inexplicable appearance of private area unicode characters on 9219 // some key combos in Mac (#2689). 9220 if (ie && ie_version >= 9 && this.hasSelection === text || 9221 mac && /[\uf700-\uf7ff]/.test(text)) { 9222 cm.display.input.reset(); 9223 return false 9224 } 9225 9226 if (cm.doc.sel == cm.display.selForContextMenu) { 9227 var first = text.charCodeAt(0); 9228 if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } 9229 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } 9230 } 9231 // Find the part of the input that is actually new 9232 var same = 0, l = Math.min(prevInput.length, text.length); 9233 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } 9234 9235 runInOp(cm, function () { 9236 applyTextInput(cm, text.slice(same), prevInput.length - same, 9237 null, this$1.composing ? "*compose" : null); 9238 9239 // Don't leave long text in the textarea, since it makes further polling slow 9240 if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } 9241 else { this$1.prevInput = text; } 9242 9243 if (this$1.composing) { 9244 this$1.composing.range.clear(); 9245 this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), 9246 {className: "CodeMirror-composing"}); 9247 } 9248 }); 9249 return true 9250 }; 9251 9252 TextareaInput.prototype.ensurePolled = function () { 9253 if (this.pollingFast && this.poll()) { this.pollingFast = false; } 9254 }; 9255 9256 TextareaInput.prototype.onKeyPress = function () { 9257 if (ie && ie_version >= 9) { this.hasSelection = null; } 9258 this.fastPoll(); 9259 }; 9260 9261 TextareaInput.prototype.onContextMenu = function (e) { 9262 var input = this, cm = input.cm, display = cm.display, te = input.textarea; 9263 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 9264 if (!pos || presto) { return } // Opera is difficult. 9265 9266 // Reset the current text selection only if the click is done outside of the selection 9267 // and 'resetSelectionOnContextMenu' option is true. 9268 var reset = cm.options.resetSelectionOnContextMenu; 9269 if (reset && cm.doc.sel.contains(pos) == -1) 9270 { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } 9271 9272 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; 9273 input.wrapper.style.cssText = "position: absolute"; 9274 var wrapperBox = input.wrapper.getBoundingClientRect(); 9275 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);"; 9276 var oldScrollY; 9277 if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) 9278 display.input.focus(); 9279 if (webkit) { window.scrollTo(null, oldScrollY); } 9280 display.input.reset(); 9281 // Adds "Select all" to context menu in FF 9282 if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } 9283 input.contextMenuPending = true; 9284 display.selForContextMenu = cm.doc.sel; 9285 clearTimeout(display.detectingSelectAll); 9286 9287 // Select-all will be greyed out if there's nothing to select, so 9288 // this adds a zero-width space so that we can later check whether 9289 // it got selected. 9290 function prepareSelectAllHack() { 9291 if (te.selectionStart != null) { 9292 var selected = cm.somethingSelected(); 9293 var extval = "\u200b" + (selected ? te.value : ""); 9294 te.value = "\u21da"; // Used to catch context-menu undo 9295 te.value = extval; 9296 input.prevInput = selected ? "" : "\u200b"; 9297 te.selectionStart = 1; te.selectionEnd = extval.length; 9298 // Re-set this, in case some other handler touched the 9299 // selection in the meantime. 9300 display.selForContextMenu = cm.doc.sel; 9301 } 9302 } 9303 function rehide() { 9304 input.contextMenuPending = false; 9305 input.wrapper.style.cssText = oldWrapperCSS; 9306 te.style.cssText = oldCSS; 9307 if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } 9308 9309 // Try to detect the user choosing select-all 9310 if (te.selectionStart != null) { 9311 if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } 9312 var i = 0, poll = function () { 9313 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && 9314 te.selectionEnd > 0 && input.prevInput == "\u200b") { 9315 operation(cm, selectAll)(cm); 9316 } else if (i++ < 10) { 9317 display.detectingSelectAll = setTimeout(poll, 500); 9318 } else { 9319 display.selForContextMenu = null; 9320 display.input.reset(); 9321 } 9322 }; 9323 display.detectingSelectAll = setTimeout(poll, 200); 9324 } 9325 } 9326 9327 if (ie && ie_version >= 9) { prepareSelectAllHack(); } 9328 if (captureRightClick) { 9329 e_stop(e); 9330 var mouseup = function () { 9331 off(window, "mouseup", mouseup); 9332 setTimeout(rehide, 20); 9333 }; 9334 on(window, "mouseup", mouseup); 9335 } else { 9336 setTimeout(rehide, 50); 9337 } 9338 }; 9339 9340 TextareaInput.prototype.readOnlyChanged = function (val) { 9341 if (!val) { this.reset(); } 9342 this.textarea.disabled = val == "nocursor"; 9343 }; 9344 9345 TextareaInput.prototype.setUneditable = function () {}; 9346 9347 TextareaInput.prototype.needsContentAttribute = false; 9348 9349 function fromTextArea(textarea, options) { 9350 options = options ? copyObj(options) : {}; 9351 options.value = textarea.value; 9352 if (!options.tabindex && textarea.tabIndex) 9353 { options.tabindex = textarea.tabIndex; } 9354 if (!options.placeholder && textarea.placeholder) 9355 { options.placeholder = textarea.placeholder; } 9356 // Set autofocus to true if this textarea is focused, or if it has 9357 // autofocus and no other element is focused. 9358 if (options.autofocus == null) { 9359 var hasFocus = activeElt(); 9360 options.autofocus = hasFocus == textarea || 9361 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 9362 } 9363 9364 function save() {textarea.value = cm.getValue();} 9365 9366 var realSubmit; 9367 if (textarea.form) { 9368 on(textarea.form, "submit", save); 9369 // Deplorable hack to make the submit method do the right thing. 9370 if (!options.leaveSubmitMethodAlone) { 9371 var form = textarea.form; 9372 realSubmit = form.submit; 9373 try { 9374 var wrappedSubmit = form.submit = function () { 9375 save(); 9376 form.submit = realSubmit; 9377 form.submit(); 9378 form.submit = wrappedSubmit; 9379 }; 9380 } catch(e) {} 9381 } 9382 } 9383 9384 options.finishInit = function (cm) { 9385 cm.save = save; 9386 cm.getTextArea = function () { return textarea; }; 9387 cm.toTextArea = function () { 9388 cm.toTextArea = isNaN; // Prevent this from being ran twice 9389 save(); 9390 textarea.parentNode.removeChild(cm.getWrapperElement()); 9391 textarea.style.display = ""; 9392 if (textarea.form) { 9393 off(textarea.form, "submit", save); 9394 if (typeof textarea.form.submit == "function") 9395 { textarea.form.submit = realSubmit; } 9396 } 9397 }; 9398 }; 9399 9400 textarea.style.display = "none"; 9401 var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, 9402 options); 9403 return cm 9404 } 9405 9406 function addLegacyProps(CodeMirror) { 9407 CodeMirror.off = off; 9408 CodeMirror.on = on; 9409 CodeMirror.wheelEventPixels = wheelEventPixels; 9410 CodeMirror.Doc = Doc; 9411 CodeMirror.splitLines = splitLinesAuto; 9412 CodeMirror.countColumn = countColumn; 9413 CodeMirror.findColumn = findColumn; 9414 CodeMirror.isWordChar = isWordCharBasic; 9415 CodeMirror.Pass = Pass; 9416 CodeMirror.signal = signal; 9417 CodeMirror.Line = Line; 9418 CodeMirror.changeEnd = changeEnd; 9419 CodeMirror.scrollbarModel = scrollbarModel; 9420 CodeMirror.Pos = Pos; 9421 CodeMirror.cmpPos = cmp; 9422 CodeMirror.modes = modes; 9423 CodeMirror.mimeModes = mimeModes; 9424 CodeMirror.resolveMode = resolveMode; 9425 CodeMirror.getMode = getMode; 9426 CodeMirror.modeExtensions = modeExtensions; 9427 CodeMirror.extendMode = extendMode; 9428 CodeMirror.copyState = copyState; 9429 CodeMirror.startState = startState; 9430 CodeMirror.innerMode = innerMode; 9431 CodeMirror.commands = commands; 9432 CodeMirror.keyMap = keyMap; 9433 CodeMirror.keyName = keyName; 9434 CodeMirror.isModifierKey = isModifierKey; 9435 CodeMirror.lookupKey = lookupKey; 9436 CodeMirror.normalizeKeyMap = normalizeKeyMap; 9437 CodeMirror.StringStream = StringStream; 9438 CodeMirror.SharedTextMarker = SharedTextMarker; 9439 CodeMirror.TextMarker = TextMarker; 9440 CodeMirror.LineWidget = LineWidget; 9441 CodeMirror.e_preventDefault = e_preventDefault; 9442 CodeMirror.e_stopPropagation = e_stopPropagation; 9443 CodeMirror.e_stop = e_stop; 9444 CodeMirror.addClass = addClass; 9445 CodeMirror.contains = contains; 9446 CodeMirror.rmClass = rmClass; 9447 CodeMirror.keyNames = keyNames; 9448 } 9449 9450 // EDITOR CONSTRUCTOR 9451 9452 defineOptions(CodeMirror$1); 9453 9454 addEditorMethods(CodeMirror$1); 9455 9456 // Set up methods on CodeMirror's prototype to redirect to the editor's document. 9457 var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); 9458 for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 9459 { CodeMirror$1.prototype[prop] = (function(method) { 9460 return function() {return method.apply(this.doc, arguments)} 9461 })(Doc.prototype[prop]); } } 9462 9463 eventMixin(Doc); 9464 9465 // INPUT HANDLING 9466 9467 CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; 9468 9469 // MODE DEFINITION AND QUERYING 9470 9471 // Extra arguments are stored as the mode's dependencies, which is 9472 // used by (legacy) mechanisms like loadmode.js to automatically 9473 // load a mode. (Preferred mechanism is the require/define calls.) 9474 CodeMirror$1.defineMode = function(name/*, mode, …*/) { 9475 if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; } 9476 defineMode.apply(this, arguments); 9477 }; 9478 9479 CodeMirror$1.defineMIME = defineMIME; 9480 9481 // Minimal default mode. 9482 CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); 9483 CodeMirror$1.defineMIME("text/plain", "null"); 9484 9485 // EXTENSIONS 9486 9487 CodeMirror$1.defineExtension = function (name, func) { 9488 CodeMirror$1.prototype[name] = func; 9489 }; 9490 CodeMirror$1.defineDocExtension = function (name, func) { 9491 Doc.prototype[name] = func; 9492 }; 9493 9494 CodeMirror$1.fromTextArea = fromTextArea; 9495 9496 addLegacyProps(CodeMirror$1); 9497 9498 CodeMirror$1.version = "5.27.4"; 9499 9500 return CodeMirror$1; 9501 9502 })));