Changeset 7223
- Timestamp:
- 10/21/18 18:27:59 (6 years ago)
- Location:
- SRUAggregator/trunk
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
SRUAggregator/trunk/pom.xml
r7147 r7223 8 8 <groupId>eu.clarin.sru.fcs</groupId> 9 9 <artifactId>aggregator</artifactId> 10 <version> 2.9.91-alpha-57</version>10 <version>3.0.0-64</version> 11 11 <name>FCS Aggregator</name> 12 12 -
SRUAggregator/trunk/src/main/resources/assets/js/main.js
r7157 r7223 50 50 51 51 },{}],2:[function(require,module,exports){ 52 // CodeMirror, copyright (c) by Marijn Haverbeke and others 53 // Distributed under an MIT license: http://codemirror.net/LICENSE 54 55 // This is CodeMirror (http://codemirror.net), a code editor 56 // implemented in JavaScript on top of the browser's DOM. 57 // 58 // You can find some technical background for some of the code below 59 // at http://marijnhaverbeke.nl/blog/#cm-internals . 60 61 (function (global, factory) { 62 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 63 typeof define === 'function' && define.amd ? define(factory) : 64 (global.CodeMirror = factory()); 65 }(this, (function () { 'use strict'; 66 67 // Kludges for bugs and behavior differences that can't be feature 68 // detected are enabled based on userAgent etc sniffing. 69 var userAgent = navigator.userAgent; 70 var platform = navigator.platform; 71 72 var gecko = /gecko\/\d/i.test(userAgent); 73 var ie_upto10 = /MSIE \d/.test(userAgent); 74 var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); 75 var edge = /Edge\/(\d+)/.exec(userAgent); 76 var ie = ie_upto10 || ie_11up || edge; 77 var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); 78 var webkit = !edge && /WebKit\//.test(userAgent); 79 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); 80 var chrome = !edge && /Chrome\//.test(userAgent); 81 var presto = /Opera\//.test(userAgent); 82 var safari = /Apple Computer/.test(navigator.vendor); 83 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); 84 var phantom = /PhantomJS/.test(userAgent); 85 86 var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); 87 var android = /Android/.test(userAgent); 88 // This is woefully incomplete. Suggestions for alternative methods welcome. 89 var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); 90 var mac = ios || /Mac/.test(platform); 91 var chromeOS = /\bCrOS\b/.test(userAgent); 92 var windows = /win/i.test(platform); 93 94 var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); 95 if (presto_version) { presto_version = Number(presto_version[1]); } 96 if (presto_version && presto_version >= 15) { presto = false; webkit = true; } 97 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X 98 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); 99 var captureRightClick = gecko || (ie && ie_version >= 9); 100 101 function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } 102 103 var rmClass = function(node, cls) { 104 var current = node.className; 105 var match = classTest(cls).exec(current); 106 if (match) { 107 var after = current.slice(match.index + match[0].length); 108 node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); 109 } 110 }; 111 112 function removeChildren(e) { 113 for (var count = e.childNodes.length; count > 0; --count) 114 { e.removeChild(e.firstChild); } 115 return e 116 } 117 118 function removeChildrenAndAdd(parent, e) { 119 return removeChildren(parent).appendChild(e) 120 } 121 122 function elt(tag, content, className, style) { 123 var e = document.createElement(tag); 124 if (className) { e.className = className; } 125 if (style) { e.style.cssText = style; } 126 if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } 127 else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } 128 return e 129 } 130 // wrapper for elt, which removes the elt from the accessibility tree 131 function eltP(tag, content, className, style) { 132 var e = elt(tag, content, className, style); 133 e.setAttribute("role", "presentation"); 134 return e 135 } 136 137 var range; 138 if (document.createRange) { range = function(node, start, end, endNode) { 139 var r = document.createRange(); 140 r.setEnd(endNode || node, end); 141 r.setStart(node, start); 142 return r 143 }; } 144 else { range = function(node, start, end) { 145 var r = document.body.createTextRange(); 146 try { r.moveToElementText(node.parentNode); } 147 catch(e) { return r } 148 r.collapse(true); 149 r.moveEnd("character", end); 150 r.moveStart("character", start); 151 return r 152 }; } 153 154 function contains(parent, child) { 155 if (child.nodeType == 3) // Android browser always returns false when child is a textnode 156 { child = child.parentNode; } 157 if (parent.contains) 158 { return parent.contains(child) } 159 do { 160 if (child.nodeType == 11) { child = child.host; } 161 if (child == parent) { return true } 162 } while (child = child.parentNode) 163 } 164 165 function activeElt() { 166 // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. 167 // IE < 10 will throw when accessed while the page is loading or in an iframe. 168 // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. 169 var activeElement; 170 try { 171 activeElement = document.activeElement; 172 } catch(e) { 173 activeElement = document.body || null; 174 } 175 while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) 176 { activeElement = activeElement.shadowRoot.activeElement; } 177 return activeElement 178 } 179 180 function addClass(node, cls) { 181 var current = node.className; 182 if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } 183 } 184 function joinClasses(a, b) { 185 var as = a.split(" "); 186 for (var i = 0; i < as.length; i++) 187 { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } 188 return b 189 } 190 191 var selectInput = function(node) { node.select(); }; 192 if (ios) // Mobile Safari apparently has a bug where select() is broken. 193 { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } 194 else if (ie) // Suppress mysterious IE10 errors 195 { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } 196 197 function bind(f) { 198 var args = Array.prototype.slice.call(arguments, 1); 199 return function(){return f.apply(null, args)} 200 } 201 202 function copyObj(obj, target, overwrite) { 203 if (!target) { target = {}; } 204 for (var prop in obj) 205 { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) 206 { target[prop] = obj[prop]; } } 207 return target 208 } 209 210 // Counts the column offset in a string, taking tabs into account. 211 // Used mostly to find indentation. 212 function countColumn(string, end, tabSize, startIndex, startValue) { 213 if (end == null) { 214 end = string.search(/[^\s\u00a0]/); 215 if (end == -1) { end = string.length; } 216 } 217 for (var i = startIndex || 0, n = startValue || 0;;) { 218 var nextTab = string.indexOf("\t", i); 219 if (nextTab < 0 || nextTab >= end) 220 { return n + (end - i) } 221 n += nextTab - i; 222 n += tabSize - (n % tabSize); 223 i = nextTab + 1; 224 } 225 } 226 227 var Delayed = function() {this.id = null;}; 228 Delayed.prototype.set = function (ms, f) { 229 clearTimeout(this.id); 230 this.id = setTimeout(f, ms); 231 }; 232 233 function indexOf(array, elt) { 234 for (var i = 0; i < array.length; ++i) 235 { if (array[i] == elt) { return i } } 236 return -1 237 } 238 239 // Number of pixels added to scroller and sizer to hide scrollbar 240 var scrollerGap = 30; 241 242 // Returned or thrown by various protocols to signal 'I'm not 243 // handling this'. 244 var Pass = {toString: function(){return "CodeMirror.Pass"}}; 245 246 // Reused option objects for setSelection & friends 247 var sel_dontScroll = {scroll: false}; 248 var sel_mouse = {origin: "*mouse"}; 249 var sel_move = {origin: "+move"}; 250 251 // The inverse of countColumn -- find the offset that corresponds to 252 // a particular column. 253 function findColumn(string, goal, tabSize) { 254 for (var pos = 0, col = 0;;) { 255 var nextTab = string.indexOf("\t", pos); 256 if (nextTab == -1) { nextTab = string.length; } 257 var skipped = nextTab - pos; 258 if (nextTab == string.length || col + skipped >= goal) 259 { return pos + Math.min(skipped, goal - col) } 260 col += nextTab - pos; 261 col += tabSize - (col % tabSize); 262 pos = nextTab + 1; 263 if (col >= goal) { return pos } 264 } 265 } 266 267 var spaceStrs = [""]; 268 function spaceStr(n) { 269 while (spaceStrs.length <= n) 270 { spaceStrs.push(lst(spaceStrs) + " "); } 271 return spaceStrs[n] 272 } 273 274 function lst(arr) { return arr[arr.length-1] } 275 276 function map(array, f) { 277 var out = []; 278 for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } 279 return out 280 } 281 282 function insertSorted(array, value, score) { 283 var pos = 0, priority = score(value); 284 while (pos < array.length && score(array[pos]) <= priority) { pos++; } 285 array.splice(pos, 0, value); 286 } 287 288 function nothing() {} 289 290 function createObj(base, props) { 291 var inst; 292 if (Object.create) { 293 inst = Object.create(base); 294 } else { 295 nothing.prototype = base; 296 inst = new nothing(); 297 } 298 if (props) { copyObj(props, inst); } 299 return inst 300 } 301 302 var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; 303 function isWordCharBasic(ch) { 304 return /\w/.test(ch) || ch > "\x80" && 305 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) 306 } 307 function isWordChar(ch, helper) { 308 if (!helper) { return isWordCharBasic(ch) } 309 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } 310 return helper.test(ch) 311 } 312 313 function isEmpty(obj) { 314 for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } 315 return true 316 } 317 318 // Extending unicode characters. A series of a non-extending char + 319 // any number of extending chars is treated as a single unit as far 320 // as editing and measuring is concerned. This is not fully correct, 321 // since some scripts/fonts/browsers also treat other configurations 322 // of code points as a group. 323 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]/; 324 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } 325 326 // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. 327 function skipExtendingChars(str, pos, dir) { 328 while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } 329 return pos 330 } 331 332 // Returns the value from the range [`from`; `to`] that satisfies 333 // `pred` and is closest to `from`. Assumes that at least `to` 334 // satisfies `pred`. Supports `from` being greater than `to`. 335 function findFirst(pred, from, to) { 336 // At any point we are certain `to` satisfies `pred`, don't know 337 // whether `from` does. 338 var dir = from > to ? -1 : 1; 339 for (;;) { 340 if (from == to) { return from } 341 var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); 342 if (mid == from) { return pred(mid) ? from : to } 343 if (pred(mid)) { to = mid; } 344 else { from = mid + dir; } 345 } 346 } 347 348 // The display handles the DOM integration, both for input reading 349 // and content drawing. It holds references to DOM nodes and 350 // display-related state. 351 352 function Display(place, doc, input) { 353 var d = this; 354 this.input = input; 355 356 // Covers bottom-right square when both scrollbars are present. 357 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); 358 d.scrollbarFiller.setAttribute("cm-not-content", "true"); 359 // Covers bottom of gutter when coverGutterNextToScrollbar is on 360 // and h scrollbar is present. 361 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); 362 d.gutterFiller.setAttribute("cm-not-content", "true"); 363 // Will contain the actual code, positioned to cover the viewport. 364 d.lineDiv = eltP("div", null, "CodeMirror-code"); 365 // Elements are added to these to represent selection and cursors. 366 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); 367 d.cursorDiv = elt("div", null, "CodeMirror-cursors"); 368 // A visibility: hidden element used to find the size of things. 369 d.measure = elt("div", null, "CodeMirror-measure"); 370 // When lines outside of the viewport are measured, they are drawn in this. 371 d.lineMeasure = elt("div", null, "CodeMirror-measure"); 372 // Wraps everything that needs to exist inside the vertically-padded coordinate system 373 d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], 374 null, "position: relative; outline: none"); 375 var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); 376 // Moved around its parent to cover visible view. 377 d.mover = elt("div", [lines], null, "position: relative"); 378 // Set to the height of the document, allowing scrolling. 379 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); 380 d.sizerWidth = null; 381 // Behavior of elts with overflow: auto and padding is 382 // inconsistent across browsers. This is used to ensure the 383 // scrollable area is big enough. 384 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); 385 // Will contain the gutters, if any. 386 d.gutters = elt("div", null, "CodeMirror-gutters"); 387 d.lineGutter = null; 388 // Actual scrollable element. 389 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); 390 d.scroller.setAttribute("tabIndex", "-1"); 391 // The element in which the editor lives. 392 d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); 393 394 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) 395 if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } 396 if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } 397 398 if (place) { 399 if (place.appendChild) { place.appendChild(d.wrapper); } 400 else { place(d.wrapper); } 401 } 402 403 // Current rendered range (may be bigger than the view window). 404 d.viewFrom = d.viewTo = doc.first; 405 d.reportedViewFrom = d.reportedViewTo = doc.first; 406 // Information about the rendered lines. 407 d.view = []; 408 d.renderedView = null; 409 // Holds info about a single rendered line when it was rendered 410 // for measurement, while not in view. 411 d.externalMeasured = null; 412 // Empty space (in pixels) above the view 413 d.viewOffset = 0; 414 d.lastWrapHeight = d.lastWrapWidth = 0; 415 d.updateLineNumbers = null; 416 417 d.nativeBarWidth = d.barHeight = d.barWidth = 0; 418 d.scrollbarsClipped = false; 419 420 // Used to only resize the line number gutter when necessary (when 421 // the amount of lines crosses a boundary that makes its width change) 422 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; 423 // Set to true when a non-horizontal-scrolling line widget is 424 // added. As an optimization, line widget aligning is skipped when 425 // this is false. 426 d.alignWidgets = false; 427 428 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 429 430 // Tracks the maximum line length so that the horizontal scrollbar 431 // can be kept static when scrolling. 432 d.maxLine = null; 433 d.maxLineLength = 0; 434 d.maxLineChanged = false; 435 436 // Used for measuring wheel scrolling granularity 437 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; 438 439 // True when shift is held down. 440 d.shift = false; 441 442 // Used to track whether anything happened since the context menu 443 // was opened. 444 d.selForContextMenu = null; 445 446 d.activeTouch = null; 447 448 input.init(d); 449 } 450 451 // Find the line object corresponding to the given line number. 452 function getLine(doc, n) { 453 n -= doc.first; 454 if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } 455 var chunk = doc; 456 while (!chunk.lines) { 457 for (var i = 0;; ++i) { 458 var child = chunk.children[i], sz = child.chunkSize(); 459 if (n < sz) { chunk = child; break } 460 n -= sz; 461 } 462 } 463 return chunk.lines[n] 464 } 465 466 // Get the part of a document between two positions, as an array of 467 // strings. 468 function getBetween(doc, start, end) { 469 var out = [], n = start.line; 470 doc.iter(start.line, end.line + 1, function (line) { 471 var text = line.text; 472 if (n == end.line) { text = text.slice(0, end.ch); } 473 if (n == start.line) { text = text.slice(start.ch); } 474 out.push(text); 475 ++n; 476 }); 477 return out 478 } 479 // Get the lines between from and to, as array of strings. 480 function getLines(doc, from, to) { 481 var out = []; 482 doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value 483 return out 484 } 485 486 // Update the height of a line, propagating the height change 487 // upwards to parent nodes. 488 function updateLineHeight(line, height) { 489 var diff = height - line.height; 490 if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } 491 } 492 493 // Given a line object, find its line number by walking up through 494 // its parent links. 495 function lineNo(line) { 496 if (line.parent == null) { return null } 497 var cur = line.parent, no = indexOf(cur.lines, line); 498 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 499 for (var i = 0;; ++i) { 500 if (chunk.children[i] == cur) { break } 501 no += chunk.children[i].chunkSize(); 502 } 503 } 504 return no + cur.first 505 } 506 507 // Find the line at the given vertical position, using the height 508 // information in the document tree. 509 function lineAtHeight(chunk, h) { 510 var n = chunk.first; 511 outer: do { 512 for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { 513 var child = chunk.children[i$1], ch = child.height; 514 if (h < ch) { chunk = child; continue outer } 515 h -= ch; 516 n += child.chunkSize(); 517 } 518 return n 519 } while (!chunk.lines) 520 var i = 0; 521 for (; i < chunk.lines.length; ++i) { 522 var line = chunk.lines[i], lh = line.height; 523 if (h < lh) { break } 524 h -= lh; 525 } 526 return n + i 527 } 528 529 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} 530 531 function lineNumberFor(options, i) { 532 return String(options.lineNumberFormatter(i + options.firstLineNumber)) 533 } 534 535 // A Pos instance represents a position within the text. 536 function Pos(line, ch, sticky) { 537 if ( sticky === void 0 ) sticky = null; 538 539 if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } 540 this.line = line; 541 this.ch = ch; 542 this.sticky = sticky; 543 } 544 545 // Compare two positions, return 0 if they are the same, a negative 546 // number when a is less, and a positive number otherwise. 547 function cmp(a, b) { return a.line - b.line || a.ch - b.ch } 548 549 function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } 550 551 function copyPos(x) {return Pos(x.line, x.ch)} 552 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } 553 function minPos(a, b) { return cmp(a, b) < 0 ? a : b } 554 555 // Most of the external API clips given positions to make sure they 556 // actually exist within the document. 557 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} 558 function clipPos(doc, pos) { 559 if (pos.line < doc.first) { return Pos(doc.first, 0) } 560 var last = doc.first + doc.size - 1; 561 if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } 562 return clipToLen(pos, getLine(doc, pos.line).text.length) 563 } 564 function clipToLen(pos, linelen) { 565 var ch = pos.ch; 566 if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } 567 else if (ch < 0) { return Pos(pos.line, 0) } 568 else { return pos } 569 } 570 function clipPosArray(doc, array) { 571 var out = []; 572 for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } 573 return out 574 } 575 576 // Optimize some code when these features are not used. 577 var sawReadOnlySpans = false; 578 var sawCollapsedSpans = false; 579 580 function seeReadOnlySpans() { 581 sawReadOnlySpans = true; 582 } 583 584 function seeCollapsedSpans() { 585 sawCollapsedSpans = true; 586 } 587 588 // TEXTMARKER SPANS 589 590 function MarkedSpan(marker, from, to) { 591 this.marker = marker; 592 this.from = from; this.to = to; 593 } 594 595 // Search an array of spans for a span matching the given marker. 596 function getMarkedSpanFor(spans, marker) { 597 if (spans) { for (var i = 0; i < spans.length; ++i) { 598 var span = spans[i]; 599 if (span.marker == marker) { return span } 600 } } 601 } 602 // Remove a span from an array, returning undefined if no spans are 603 // left (we don't store arrays for lines without spans). 604 function removeMarkedSpan(spans, span) { 605 var r; 606 for (var i = 0; i < spans.length; ++i) 607 { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } 608 return r 609 } 610 // Add a span to a line. 611 function addMarkedSpan(line, span) { 612 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 613 span.marker.attachLine(line); 614 } 615 616 // Used for the algorithm that adjusts markers for a change in the 617 // document. These functions cut an array of spans at a given 618 // character position, returning an array of remaining chunks (or 619 // undefined if nothing remains). 620 function markedSpansBefore(old, startCh, isInsert) { 621 var nw; 622 if (old) { for (var i = 0; i < old.length; ++i) { 623 var span = old[i], marker = span.marker; 624 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 625 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { 626 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)); 627 } 628 } } 629 return nw 630 } 631 function markedSpansAfter(old, endCh, isInsert) { 632 var nw; 633 if (old) { for (var i = 0; i < old.length; ++i) { 634 var span = old[i], marker = span.marker; 635 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 636 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { 637 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, 638 span.to == null ? null : span.to - endCh)); 639 } 640 } } 641 return nw 642 } 643 644 // Given a change object, compute the new set of marker spans that 645 // cover the line in which the change took place. Removes spans 646 // entirely within the change, reconnects spans belonging to the 647 // same marker that appear on both sides of the change, and cuts off 648 // spans partially within the change. Returns an array of span 649 // arrays with one element for each line in (after) the change. 650 function stretchSpansOverChange(doc, change) { 651 if (change.full) { return null } 652 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 653 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 654 if (!oldFirst && !oldLast) { return null } 655 656 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; 657 // Get the spans that 'stick out' on both sides 658 var first = markedSpansBefore(oldFirst, startCh, isInsert); 659 var last = markedSpansAfter(oldLast, endCh, isInsert); 660 661 // Next, merge those two ends 662 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 663 if (first) { 664 // Fix up .to properties of first 665 for (var i = 0; i < first.length; ++i) { 666 var span = first[i]; 667 if (span.to == null) { 668 var found = getMarkedSpanFor(last, span.marker); 669 if (!found) { span.to = startCh; } 670 else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } 671 } 672 } 673 } 674 if (last) { 675 // Fix up .from in last (or move them into first in case of sameLine) 676 for (var i$1 = 0; i$1 < last.length; ++i$1) { 677 var span$1 = last[i$1]; 678 if (span$1.to != null) { span$1.to += offset; } 679 if (span$1.from == null) { 680 var found$1 = getMarkedSpanFor(first, span$1.marker); 681 if (!found$1) { 682 span$1.from = offset; 683 if (sameLine) { (first || (first = [])).push(span$1); } 684 } 685 } else { 686 span$1.from += offset; 687 if (sameLine) { (first || (first = [])).push(span$1); } 688 } 689 } 690 } 691 // Make sure we didn't create any zero-length spans 692 if (first) { first = clearEmptySpans(first); } 693 if (last && last != first) { last = clearEmptySpans(last); } 694 695 var newMarkers = [first]; 696 if (!sameLine) { 697 // Fill gap with whole-line-spans 698 var gap = change.text.length - 2, gapMarkers; 699 if (gap > 0 && first) 700 { for (var i$2 = 0; i$2 < first.length; ++i$2) 701 { if (first[i$2].to == null) 702 { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } 703 for (var i$3 = 0; i$3 < gap; ++i$3) 704 { newMarkers.push(gapMarkers); } 705 newMarkers.push(last); 706 } 707 return newMarkers 708 } 709 710 // Remove spans that are empty and don't have a clearWhenEmpty 711 // option of false. 712 function clearEmptySpans(spans) { 713 for (var i = 0; i < spans.length; ++i) { 714 var span = spans[i]; 715 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) 716 { spans.splice(i--, 1); } 717 } 718 if (!spans.length) { return null } 719 return spans 720 } 721 722 // Used to 'clip' out readOnly ranges when making a change. 723 function removeReadOnlyRanges(doc, from, to) { 724 var markers = null; 725 doc.iter(from.line, to.line + 1, function (line) { 726 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 727 var mark = line.markedSpans[i].marker; 728 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 729 { (markers || (markers = [])).push(mark); } 730 } } 731 }); 732 if (!markers) { return null } 733 var parts = [{from: from, to: to}]; 734 for (var i = 0; i < markers.length; ++i) { 735 var mk = markers[i], m = mk.find(0); 736 for (var j = 0; j < parts.length; ++j) { 737 var p = parts[j]; 738 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } 739 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); 740 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) 741 { newParts.push({from: p.from, to: m.from}); } 742 if (dto > 0 || !mk.inclusiveRight && !dto) 743 { newParts.push({from: m.to, to: p.to}); } 744 parts.splice.apply(parts, newParts); 745 j += newParts.length - 3; 746 } 747 } 748 return parts 749 } 750 751 // Connect or disconnect spans from a line. 752 function detachMarkedSpans(line) { 753 var spans = line.markedSpans; 754 if (!spans) { return } 755 for (var i = 0; i < spans.length; ++i) 756 { spans[i].marker.detachLine(line); } 757 line.markedSpans = null; 758 } 759 function attachMarkedSpans(line, spans) { 760 if (!spans) { return } 761 for (var i = 0; i < spans.length; ++i) 762 { spans[i].marker.attachLine(line); } 763 line.markedSpans = spans; 764 } 765 766 // Helpers used when computing which overlapping collapsed span 767 // counts as the larger one. 768 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } 769 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } 770 771 // Returns a number indicating which of two overlapping collapsed 772 // spans is larger (and thus includes the other). Falls back to 773 // comparing ids when the spans cover exactly the same range. 774 function compareCollapsedMarkers(a, b) { 775 var lenDiff = a.lines.length - b.lines.length; 776 if (lenDiff != 0) { return lenDiff } 777 var aPos = a.find(), bPos = b.find(); 778 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); 779 if (fromCmp) { return -fromCmp } 780 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); 781 if (toCmp) { return toCmp } 782 return b.id - a.id 783 } 784 785 // Find out whether a line ends or starts in a collapsed span. If 786 // so, return the marker for that span. 787 function collapsedSpanAtSide(line, start) { 788 var sps = sawCollapsedSpans && line.markedSpans, found; 789 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 790 sp = sps[i]; 791 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && 792 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) 793 { found = sp.marker; } 794 } } 795 return found 796 } 797 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } 798 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } 799 800 // Test whether there exists a collapsed span that partially 801 // overlaps (covers the start or end, but not both) of a new span. 802 // Such overlap is not allowed. 803 function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { 804 var line = getLine(doc, lineNo$$1); 805 var sps = sawCollapsedSpans && line.markedSpans; 806 if (sps) { for (var i = 0; i < sps.length; ++i) { 807 var sp = sps[i]; 808 if (!sp.marker.collapsed) { continue } 809 var found = sp.marker.find(0); 810 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); 811 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); 812 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } 813 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || 814 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) 815 { return true } 816 } } 817 } 818 819 // A visual line is a line as drawn on the screen. Folding, for 820 // example, can cause multiple logical lines to appear on the same 821 // visual line. This finds the start of the visual line that the 822 // given line is part of (usually that is the line itself). 823 function visualLine(line) { 824 var merged; 825 while (merged = collapsedSpanAtStart(line)) 826 { line = merged.find(-1, true).line; } 827 return line 828 } 829 830 function visualLineEnd(line) { 831 var merged; 832 while (merged = collapsedSpanAtEnd(line)) 833 { line = merged.find(1, true).line; } 834 return line 835 } 836 837 // Returns an array of logical lines that continue the visual line 838 // started by the argument, or undefined if there are no such lines. 839 function visualLineContinued(line) { 840 var merged, lines; 841 while (merged = collapsedSpanAtEnd(line)) { 842 line = merged.find(1, true).line 843 ;(lines || (lines = [])).push(line); 844 } 845 return lines 846 } 847 848 // Get the line number of the start of the visual line that the 849 // given line number is part of. 850 function visualLineNo(doc, lineN) { 851 var line = getLine(doc, lineN), vis = visualLine(line); 852 if (line == vis) { return lineN } 853 return lineNo(vis) 854 } 855 856 // Get the line number of the start of the next visual line after 857 // the given line. 858 function visualLineEndNo(doc, lineN) { 859 if (lineN > doc.lastLine()) { return lineN } 860 var line = getLine(doc, lineN), merged; 861 if (!lineIsHidden(doc, line)) { return lineN } 862 while (merged = collapsedSpanAtEnd(line)) 863 { line = merged.find(1, true).line; } 864 return lineNo(line) + 1 865 } 866 867 // Compute whether a line is hidden. Lines count as hidden when they 868 // are part of a visual line that starts with another line, or when 869 // they are entirely covered by collapsed, non-widget span. 870 function lineIsHidden(doc, line) { 871 var sps = sawCollapsedSpans && line.markedSpans; 872 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 873 sp = sps[i]; 874 if (!sp.marker.collapsed) { continue } 875 if (sp.from == null) { return true } 876 if (sp.marker.widgetNode) { continue } 877 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 878 { return true } 879 } } 880 } 881 function lineIsHiddenInner(doc, line, span) { 882 if (span.to == null) { 883 var end = span.marker.find(1, true); 884 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) 885 } 886 if (span.marker.inclusiveRight && span.to == line.text.length) 887 { return true } 888 for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { 889 sp = line.markedSpans[i]; 890 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && 891 (sp.to == null || sp.to != span.from) && 892 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 893 lineIsHiddenInner(doc, line, sp)) { return true } 894 } 895 } 896 897 // Find the height above the given line. 898 function heightAtLine(lineObj) { 899 lineObj = visualLine(lineObj); 900 901 var h = 0, chunk = lineObj.parent; 902 for (var i = 0; i < chunk.lines.length; ++i) { 903 var line = chunk.lines[i]; 904 if (line == lineObj) { break } 905 else { h += line.height; } 906 } 907 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 908 for (var i$1 = 0; i$1 < p.children.length; ++i$1) { 909 var cur = p.children[i$1]; 910 if (cur == chunk) { break } 911 else { h += cur.height; } 912 } 913 } 914 return h 915 } 916 917 // Compute the character length of a line, taking into account 918 // collapsed ranges (see markText) that might hide parts, and join 919 // other lines onto it. 920 function lineLength(line) { 921 if (line.height == 0) { return 0 } 922 var len = line.text.length, merged, cur = line; 923 while (merged = collapsedSpanAtStart(cur)) { 924 var found = merged.find(0, true); 925 cur = found.from.line; 926 len += found.from.ch - found.to.ch; 927 } 928 cur = line; 929 while (merged = collapsedSpanAtEnd(cur)) { 930 var found$1 = merged.find(0, true); 931 len -= cur.text.length - found$1.from.ch; 932 cur = found$1.to.line; 933 len += cur.text.length - found$1.to.ch; 934 } 935 return len 936 } 937 938 // Find the longest line in the document. 939 function findMaxLine(cm) { 940 var d = cm.display, doc = cm.doc; 941 d.maxLine = getLine(doc, doc.first); 942 d.maxLineLength = lineLength(d.maxLine); 943 d.maxLineChanged = true; 944 doc.iter(function (line) { 945 var len = lineLength(line); 946 if (len > d.maxLineLength) { 947 d.maxLineLength = len; 948 d.maxLine = line; 949 } 950 }); 951 } 952 953 // BIDI HELPERS 954 955 function iterateBidiSections(order, from, to, f) { 956 if (!order) { return f(from, to, "ltr", 0) } 957 var found = false; 958 for (var i = 0; i < order.length; ++i) { 959 var part = order[i]; 960 if (part.from < to && part.to > from || from == to && part.to == from) { 961 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); 962 found = true; 963 } 964 } 965 if (!found) { f(from, to, "ltr"); } 966 } 967 968 var bidiOther = null; 969 function getBidiPartAt(order, ch, sticky) { 970 var found; 971 bidiOther = null; 972 for (var i = 0; i < order.length; ++i) { 973 var cur = order[i]; 974 if (cur.from < ch && cur.to > ch) { return i } 975 if (cur.to == ch) { 976 if (cur.from != cur.to && sticky == "before") { found = i; } 977 else { bidiOther = i; } 978 } 979 if (cur.from == ch) { 980 if (cur.from != cur.to && sticky != "before") { found = i; } 981 else { bidiOther = i; } 982 } 983 } 984 return found != null ? found : bidiOther 985 } 986 987 // Bidirectional ordering algorithm 988 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 989 // that this (partially) implements. 990 991 // One-char codes used for character types: 992 // L (L): Left-to-Right 993 // R (R): Right-to-Left 994 // r (AL): Right-to-Left Arabic 995 // 1 (EN): European Number 996 // + (ES): European Number Separator 997 // % (ET): European Number Terminator 998 // n (AN): Arabic Number 999 // , (CS): Common Number Separator 1000 // m (NSM): Non-Spacing Mark 1001 // b (BN): Boundary Neutral 1002 // s (B): Paragraph Separator 1003 // t (S): Segment Separator 1004 // w (WS): Whitespace 1005 // N (ON): Other Neutrals 1006 1007 // Returns null if characters are ordered as they appear 1008 // (left-to-right), or an array of sections ({from, to, level} 1009 // objects) in the order in which they occur visually. 1010 var bidiOrdering = (function() { 1011 // Character types for codepoints 0 to 0xff 1012 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; 1013 // Character types for codepoints 0x600 to 0x6f9 1014 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; 1015 function charType(code) { 1016 if (code <= 0xf7) { return lowTypes.charAt(code) } 1017 else if (0x590 <= code && code <= 0x5f4) { return "R" } 1018 else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } 1019 else if (0x6ee <= code && code <= 0x8ac) { return "r" } 1020 else if (0x2000 <= code && code <= 0x200b) { return "w" } 1021 else if (code == 0x200c) { return "b" } 1022 else { return "L" } 1023 } 1024 1025 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 1026 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 1027 1028 function BidiSpan(level, from, to) { 1029 this.level = level; 1030 this.from = from; this.to = to; 1031 } 1032 1033 return function(str, direction) { 1034 var outerType = direction == "ltr" ? "L" : "R"; 1035 1036 if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } 1037 var len = str.length, types = []; 1038 for (var i = 0; i < len; ++i) 1039 { types.push(charType(str.charCodeAt(i))); } 1040 1041 // W1. Examine each non-spacing mark (NSM) in the level run, and 1042 // change the type of the NSM to the type of the previous 1043 // character. If the NSM is at the start of the level run, it will 1044 // get the type of sor. 1045 for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { 1046 var type = types[i$1]; 1047 if (type == "m") { types[i$1] = prev; } 1048 else { prev = type; } 1049 } 1050 1051 // W2. Search backwards from each instance of a European number 1052 // until the first strong type (R, L, AL, or sor) is found. If an 1053 // AL is found, change the type of the European number to Arabic 1054 // number. 1055 // W3. Change all ALs to R. 1056 for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { 1057 var type$1 = types[i$2]; 1058 if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } 1059 else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } 1060 } 1061 1062 // W4. A single European separator between two European numbers 1063 // changes to a European number. A single common separator between 1064 // two numbers of the same type changes to that type. 1065 for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { 1066 var type$2 = types[i$3]; 1067 if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } 1068 else if (type$2 == "," && prev$1 == types[i$3+1] && 1069 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } 1070 prev$1 = type$2; 1071 } 1072 1073 // W5. A sequence of European terminators adjacent to European 1074 // numbers changes to all European numbers. 1075 // W6. Otherwise, separators and terminators change to Other 1076 // Neutral. 1077 for (var i$4 = 0; i$4 < len; ++i$4) { 1078 var type$3 = types[i$4]; 1079 if (type$3 == ",") { types[i$4] = "N"; } 1080 else if (type$3 == "%") { 1081 var end = (void 0); 1082 for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} 1083 var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; 1084 for (var j = i$4; j < end; ++j) { types[j] = replace; } 1085 i$4 = end - 1; 1086 } 1087 } 1088 1089 // W7. Search backwards from each instance of a European number 1090 // until the first strong type (R, L, or sor) is found. If an L is 1091 // found, then change the type of the European number to L. 1092 for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { 1093 var type$4 = types[i$5]; 1094 if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } 1095 else if (isStrong.test(type$4)) { cur$1 = type$4; } 1096 } 1097 1098 // N1. A sequence of neutrals takes the direction of the 1099 // surrounding strong text if the text on both sides has the same 1100 // direction. European and Arabic numbers act as if they were R in 1101 // terms of their influence on neutrals. Start-of-level-run (sor) 1102 // and end-of-level-run (eor) are used at level run boundaries. 1103 // N2. Any remaining neutrals take the embedding direction. 1104 for (var i$6 = 0; i$6 < len; ++i$6) { 1105 if (isNeutral.test(types[i$6])) { 1106 var end$1 = (void 0); 1107 for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} 1108 var before = (i$6 ? types[i$6-1] : outerType) == "L"; 1109 var after = (end$1 < len ? types[end$1] : outerType) == "L"; 1110 var replace$1 = before == after ? (before ? "L" : "R") : outerType; 1111 for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } 1112 i$6 = end$1 - 1; 1113 } 1114 } 1115 1116 // Here we depart from the documented algorithm, in order to avoid 1117 // building up an actual levels array. Since there are only three 1118 // levels (0, 1, 2) in an implementation that doesn't take 1119 // explicit embedding into account, we can build up the order on 1120 // the fly, without following the level-based algorithm. 1121 var order = [], m; 1122 for (var i$7 = 0; i$7 < len;) { 1123 if (countsAsLeft.test(types[i$7])) { 1124 var start = i$7; 1125 for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} 1126 order.push(new BidiSpan(0, start, i$7)); 1127 } else { 1128 var pos = i$7, at = order.length; 1129 for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} 1130 for (var j$2 = pos; j$2 < i$7;) { 1131 if (countsAsNum.test(types[j$2])) { 1132 if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } 1133 var nstart = j$2; 1134 for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} 1135 order.splice(at, 0, new BidiSpan(2, nstart, j$2)); 1136 pos = j$2; 1137 } else { ++j$2; } 1138 } 1139 if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } 1140 } 1141 } 1142 if (direction == "ltr") { 1143 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 1144 order[0].from = m[0].length; 1145 order.unshift(new BidiSpan(0, 0, m[0].length)); 1146 } 1147 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 1148 lst(order).to -= m[0].length; 1149 order.push(new BidiSpan(0, len - m[0].length, len)); 1150 } 1151 } 1152 1153 return direction == "rtl" ? order.reverse() : order 1154 } 1155 })(); 1156 1157 // Get the bidi ordering for the given line (and cache it). Returns 1158 // false for lines that are fully left-to-right, and an array of 1159 // BidiSpan objects otherwise. 1160 function getOrder(line, direction) { 1161 var order = line.order; 1162 if (order == null) { order = line.order = bidiOrdering(line.text, direction); } 1163 return order 1164 } 1165 1166 // EVENT HANDLING 1167 1168 // Lightweight event framework. on/off also work on DOM nodes, 1169 // registering native DOM handlers. 1170 1171 var noHandlers = []; 1172 1173 var on = function(emitter, type, f) { 1174 if (emitter.addEventListener) { 1175 emitter.addEventListener(type, f, false); 1176 } else if (emitter.attachEvent) { 1177 emitter.attachEvent("on" + type, f); 1178 } else { 1179 var map$$1 = emitter._handlers || (emitter._handlers = {}); 1180 map$$1[type] = (map$$1[type] || noHandlers).concat(f); 1181 } 1182 }; 1183 1184 function getHandlers(emitter, type) { 1185 return emitter._handlers && emitter._handlers[type] || noHandlers 1186 } 1187 1188 function off(emitter, type, f) { 1189 if (emitter.removeEventListener) { 1190 emitter.removeEventListener(type, f, false); 1191 } else if (emitter.detachEvent) { 1192 emitter.detachEvent("on" + type, f); 1193 } else { 1194 var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; 1195 if (arr) { 1196 var index = indexOf(arr, f); 1197 if (index > -1) 1198 { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } 1199 } 1200 } 1201 } 1202 1203 function signal(emitter, type /*, values...*/) { 1204 var handlers = getHandlers(emitter, type); 1205 if (!handlers.length) { return } 1206 var args = Array.prototype.slice.call(arguments, 2); 1207 for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } 1208 } 1209 1210 // The DOM events that CodeMirror handles can be overridden by 1211 // registering a (non-DOM) handler on the editor for the event name, 1212 // and preventDefault-ing the event in that handler. 1213 function signalDOMEvent(cm, e, override) { 1214 if (typeof e == "string") 1215 { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } 1216 signal(cm, override || e.type, cm, e); 1217 return e_defaultPrevented(e) || e.codemirrorIgnore 1218 } 1219 1220 function signalCursorActivity(cm) { 1221 var arr = cm._handlers && cm._handlers.cursorActivity; 1222 if (!arr) { return } 1223 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); 1224 for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) 1225 { set.push(arr[i]); } } 1226 } 1227 1228 function hasHandler(emitter, type) { 1229 return getHandlers(emitter, type).length > 0 1230 } 1231 1232 // Add on and off methods to a constructor's prototype, to make 1233 // registering events on such objects more convenient. 1234 function eventMixin(ctor) { 1235 ctor.prototype.on = function(type, f) {on(this, type, f);}; 1236 ctor.prototype.off = function(type, f) {off(this, type, f);}; 1237 } 1238 1239 // Due to the fact that we still support jurassic IE versions, some 1240 // compatibility wrappers are needed. 1241 1242 function e_preventDefault(e) { 1243 if (e.preventDefault) { e.preventDefault(); } 1244 else { e.returnValue = false; } 1245 } 1246 function e_stopPropagation(e) { 1247 if (e.stopPropagation) { e.stopPropagation(); } 1248 else { e.cancelBubble = true; } 1249 } 1250 function e_defaultPrevented(e) { 1251 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false 1252 } 1253 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} 1254 1255 function e_target(e) {return e.target || e.srcElement} 1256 function e_button(e) { 1257 var b = e.which; 1258 if (b == null) { 1259 if (e.button & 1) { b = 1; } 1260 else if (e.button & 2) { b = 3; } 1261 else if (e.button & 4) { b = 2; } 1262 } 1263 if (mac && e.ctrlKey && b == 1) { b = 3; } 1264 return b 1265 } 1266 1267 // Detect drag-and-drop 1268 var dragAndDrop = function() { 1269 // There is *some* kind of drag-and-drop support in IE6-8, but I 1270 // couldn't get it to work yet. 1271 if (ie && ie_version < 9) { return false } 1272 var div = elt('div'); 1273 return "draggable" in div || "dragDrop" in div 1274 }(); 1275 1276 var zwspSupported; 1277 function zeroWidthElement(measure) { 1278 if (zwspSupported == null) { 1279 var test = elt("span", "\u200b"); 1280 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 1281 if (measure.firstChild.offsetHeight != 0) 1282 { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } 1283 } 1284 var node = zwspSupported ? elt("span", "\u200b") : 1285 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 1286 node.setAttribute("cm-text", ""); 1287 return node 1288 } 1289 1290 // Feature-detect IE's crummy client rect reporting for bidi text 1291 var badBidiRects; 1292 function hasBadBidiRects(measure) { 1293 if (badBidiRects != null) { return badBidiRects } 1294 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); 1295 var r0 = range(txt, 0, 1).getBoundingClientRect(); 1296 var r1 = range(txt, 1, 2).getBoundingClientRect(); 1297 removeChildren(measure); 1298 if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) 1299 return badBidiRects = (r1.right - r0.right < 3) 1300 } 1301 1302 // See if "".split is the broken IE version, if so, provide an 1303 // alternative way to split lines. 1304 var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { 1305 var pos = 0, result = [], l = string.length; 1306 while (pos <= l) { 1307 var nl = string.indexOf("\n", pos); 1308 if (nl == -1) { nl = string.length; } 1309 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 1310 var rt = line.indexOf("\r"); 1311 if (rt != -1) { 1312 result.push(line.slice(0, rt)); 1313 pos += rt + 1; 1314 } else { 1315 result.push(line); 1316 pos = nl + 1; 1317 } 1318 } 1319 return result 1320 } : function (string) { return string.split(/\r\n?|\n/); }; 1321 1322 var hasSelection = window.getSelection ? function (te) { 1323 try { return te.selectionStart != te.selectionEnd } 1324 catch(e) { return false } 1325 } : function (te) { 1326 var range$$1; 1327 try {range$$1 = te.ownerDocument.selection.createRange();} 1328 catch(e) {} 1329 if (!range$$1 || range$$1.parentElement() != te) { return false } 1330 return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 1331 }; 1332 1333 var hasCopyEvent = (function () { 1334 var e = elt("div"); 1335 if ("oncopy" in e) { return true } 1336 e.setAttribute("oncopy", "return;"); 1337 return typeof e.oncopy == "function" 1338 })(); 1339 1340 var badZoomedRects = null; 1341 function hasBadZoomedRects(measure) { 1342 if (badZoomedRects != null) { return badZoomedRects } 1343 var node = removeChildrenAndAdd(measure, elt("span", "x")); 1344 var normal = node.getBoundingClientRect(); 1345 var fromRange = range(node, 0, 1).getBoundingClientRect(); 1346 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 1347 } 1348 1349 // Known modes, by name and by MIME 1350 var modes = {}; 1351 var mimeModes = {}; 1352 1353 // Extra arguments are stored as the mode's dependencies, which is 1354 // used by (legacy) mechanisms like loadmode.js to automatically 1355 // load a mode. (Preferred mechanism is the require/define calls.) 1356 function defineMode(name, mode) { 1357 if (arguments.length > 2) 1358 { mode.dependencies = Array.prototype.slice.call(arguments, 2); } 1359 modes[name] = mode; 1360 } 1361 1362 function defineMIME(mime, spec) { 1363 mimeModes[mime] = spec; 1364 } 1365 1366 // Given a MIME type, a {name, ...options} config object, or a name 1367 // string, return a mode config object. 1368 function resolveMode(spec) { 1369 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { 1370 spec = mimeModes[spec]; 1371 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { 1372 var found = mimeModes[spec.name]; 1373 if (typeof found == "string") { found = {name: found}; } 1374 spec = createObj(found, spec); 1375 spec.name = found.name; 1376 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { 1377 return resolveMode("application/xml") 1378 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { 1379 return resolveMode("application/json") 1380 } 1381 if (typeof spec == "string") { return {name: spec} } 1382 else { return spec || {name: "null"} } 1383 } 1384 1385 // Given a mode spec (anything that resolveMode accepts), find and 1386 // initialize an actual mode object. 1387 function getMode(options, spec) { 1388 spec = resolveMode(spec); 1389 var mfactory = modes[spec.name]; 1390 if (!mfactory) { return getMode(options, "text/plain") } 1391 var modeObj = mfactory(options, spec); 1392 if (modeExtensions.hasOwnProperty(spec.name)) { 1393 var exts = modeExtensions[spec.name]; 1394 for (var prop in exts) { 1395 if (!exts.hasOwnProperty(prop)) { continue } 1396 if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } 1397 modeObj[prop] = exts[prop]; 1398 } 1399 } 1400 modeObj.name = spec.name; 1401 if (spec.helperType) { modeObj.helperType = spec.helperType; } 1402 if (spec.modeProps) { for (var prop$1 in spec.modeProps) 1403 { modeObj[prop$1] = spec.modeProps[prop$1]; } } 1404 1405 return modeObj 1406 } 1407 1408 // This can be used to attach properties to mode objects from 1409 // outside the actual mode definition. 1410 var modeExtensions = {}; 1411 function extendMode(mode, properties) { 1412 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 1413 copyObj(properties, exts); 1414 } 1415 1416 function copyState(mode, state) { 1417 if (state === true) { return state } 1418 if (mode.copyState) { return mode.copyState(state) } 1419 var nstate = {}; 1420 for (var n in state) { 1421 var val = state[n]; 1422 if (val instanceof Array) { val = val.concat([]); } 1423 nstate[n] = val; 1424 } 1425 return nstate 1426 } 1427 1428 // Given a mode and a state (for that mode), find the inner mode and 1429 // state at the position that the state refers to. 1430 function innerMode(mode, state) { 1431 var info; 1432 while (mode.innerMode) { 1433 info = mode.innerMode(state); 1434 if (!info || info.mode == mode) { break } 1435 state = info.state; 1436 mode = info.mode; 1437 } 1438 return info || {mode: mode, state: state} 1439 } 1440 1441 function startState(mode, a1, a2) { 1442 return mode.startState ? mode.startState(a1, a2) : true 1443 } 1444 1445 // STRING STREAM 1446 1447 // Fed to the mode parsers, provides helper functions to make 1448 // parsers more succinct. 1449 1450 var StringStream = function(string, tabSize, lineOracle) { 1451 this.pos = this.start = 0; 1452 this.string = string; 1453 this.tabSize = tabSize || 8; 1454 this.lastColumnPos = this.lastColumnValue = 0; 1455 this.lineStart = 0; 1456 this.lineOracle = lineOracle; 1457 }; 1458 1459 StringStream.prototype.eol = function () {return this.pos >= this.string.length}; 1460 StringStream.prototype.sol = function () {return this.pos == this.lineStart}; 1461 StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; 1462 StringStream.prototype.next = function () { 1463 if (this.pos < this.string.length) 1464 { return this.string.charAt(this.pos++) } 1465 }; 1466 StringStream.prototype.eat = function (match) { 1467 var ch = this.string.charAt(this.pos); 1468 var ok; 1469 if (typeof match == "string") { ok = ch == match; } 1470 else { ok = ch && (match.test ? match.test(ch) : match(ch)); } 1471 if (ok) {++this.pos; return ch} 1472 }; 1473 StringStream.prototype.eatWhile = function (match) { 1474 var start = this.pos; 1475 while (this.eat(match)){} 1476 return this.pos > start 1477 }; 1478 StringStream.prototype.eatSpace = function () { 1479 var this$1 = this; 1480 1481 var start = this.pos; 1482 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } 1483 return this.pos > start 1484 }; 1485 StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; 1486 StringStream.prototype.skipTo = function (ch) { 1487 var found = this.string.indexOf(ch, this.pos); 1488 if (found > -1) {this.pos = found; return true} 1489 }; 1490 StringStream.prototype.backUp = function (n) {this.pos -= n;}; 1491 StringStream.prototype.column = function () { 1492 if (this.lastColumnPos < this.start) { 1493 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); 1494 this.lastColumnPos = this.start; 1495 } 1496 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1497 }; 1498 StringStream.prototype.indentation = function () { 1499 return countColumn(this.string, null, this.tabSize) - 1500 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1501 }; 1502 StringStream.prototype.match = function (pattern, consume, caseInsensitive) { 1503 if (typeof pattern == "string") { 1504 var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; 1505 var substr = this.string.substr(this.pos, pattern.length); 1506 if (cased(substr) == cased(pattern)) { 1507 if (consume !== false) { this.pos += pattern.length; } 1508 return true 1509 } 1510 } else { 1511 var match = this.string.slice(this.pos).match(pattern); 1512 if (match && match.index > 0) { return null } 1513 if (match && consume !== false) { this.pos += match[0].length; } 1514 return match 1515 } 1516 }; 1517 StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; 1518 StringStream.prototype.hideFirstChars = function (n, inner) { 1519 this.lineStart += n; 1520 try { return inner() } 1521 finally { this.lineStart -= n; } 1522 }; 1523 StringStream.prototype.lookAhead = function (n) { 1524 var oracle = this.lineOracle; 1525 return oracle && oracle.lookAhead(n) 1526 }; 1527 StringStream.prototype.baseToken = function () { 1528 var oracle = this.lineOracle; 1529 return oracle && oracle.baseToken(this.pos) 1530 }; 1531 1532 var SavedContext = function(state, lookAhead) { 1533 this.state = state; 1534 this.lookAhead = lookAhead; 1535 }; 1536 1537 var Context = function(doc, state, line, lookAhead) { 1538 this.state = state; 1539 this.doc = doc; 1540 this.line = line; 1541 this.maxLookAhead = lookAhead || 0; 1542 this.baseTokens = null; 1543 this.baseTokenPos = 1; 1544 }; 1545 1546 Context.prototype.lookAhead = function (n) { 1547 var line = this.doc.getLine(this.line + n); 1548 if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } 1549 return line 1550 }; 1551 1552 Context.prototype.baseToken = function (n) { 1553 var this$1 = this; 1554 1555 if (!this.baseTokens) { return null } 1556 while (this.baseTokens[this.baseTokenPos] <= n) 1557 { this$1.baseTokenPos += 2; } 1558 var type = this.baseTokens[this.baseTokenPos + 1]; 1559 return {type: type && type.replace(/( |^)overlay .*/, ""), 1560 size: this.baseTokens[this.baseTokenPos] - n} 1561 }; 1562 1563 Context.prototype.nextLine = function () { 1564 this.line++; 1565 if (this.maxLookAhead > 0) { this.maxLookAhead--; } 1566 }; 1567 1568 Context.fromSaved = function (doc, saved, line) { 1569 if (saved instanceof SavedContext) 1570 { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } 1571 else 1572 { return new Context(doc, copyState(doc.mode, saved), line) } 1573 }; 1574 1575 Context.prototype.save = function (copy) { 1576 var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; 1577 return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state 1578 }; 1579 1580 1581 // Compute a style array (an array starting with a mode generation 1582 // -- for invalidation -- followed by pairs of end positions and 1583 // style strings), which is used to highlight the tokens on the 1584 // line. 1585 function highlightLine(cm, line, context, forceToEnd) { 1586 // A styles array always starts with a number identifying the 1587 // mode/overlays that it is based on (for easy invalidation). 1588 var st = [cm.state.modeGen], lineClasses = {}; 1589 // Compute the base array of styles 1590 runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, 1591 lineClasses, forceToEnd); 1592 var state = context.state; 1593 1594 // Run overlays, adjust style array. 1595 var loop = function ( o ) { 1596 context.baseTokens = st; 1597 var overlay = cm.state.overlays[o], i = 1, at = 0; 1598 context.state = true; 1599 runMode(cm, line.text, overlay.mode, context, function (end, style) { 1600 var start = i; 1601 // Ensure there's a token end at the current position, and that i points at it 1602 while (at < end) { 1603 var i_end = st[i]; 1604 if (i_end > end) 1605 { st.splice(i, 1, end, st[i+1], i_end); } 1606 i += 2; 1607 at = Math.min(end, i_end); 1608 } 1609 if (!style) { return } 1610 if (overlay.opaque) { 1611 st.splice(start, i - start, end, "overlay " + style); 1612 i = start + 2; 1613 } else { 1614 for (; start < i; start += 2) { 1615 var cur = st[start+1]; 1616 st[start+1] = (cur ? cur + " " : "") + "overlay " + style; 1617 } 1618 } 1619 }, lineClasses); 1620 context.state = state; 1621 context.baseTokens = null; 1622 context.baseTokenPos = 1; 1623 }; 1624 1625 for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); 1626 1627 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} 1628 } 1629 1630 function getLineStyles(cm, line, updateFrontier) { 1631 if (!line.styles || line.styles[0] != cm.state.modeGen) { 1632 var context = getContextBefore(cm, lineNo(line)); 1633 var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); 1634 var result = highlightLine(cm, line, context); 1635 if (resetState) { context.state = resetState; } 1636 line.stateAfter = context.save(!resetState); 1637 line.styles = result.styles; 1638 if (result.classes) { line.styleClasses = result.classes; } 1639 else if (line.styleClasses) { line.styleClasses = null; } 1640 if (updateFrontier === cm.doc.highlightFrontier) 1641 { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } 1642 } 1643 return line.styles 1644 } 1645 1646 function getContextBefore(cm, n, precise) { 1647 var doc = cm.doc, display = cm.display; 1648 if (!doc.mode.startState) { return new Context(doc, true, n) } 1649 var start = findStartLine(cm, n, precise); 1650 var saved = start > doc.first && getLine(doc, start - 1).stateAfter; 1651 var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); 1652 1653 doc.iter(start, n, function (line) { 1654 processLine(cm, line.text, context); 1655 var pos = context.line; 1656 line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; 1657 context.nextLine(); 1658 }); 1659 if (precise) { doc.modeFrontier = context.line; } 1660 return context 1661 } 1662 1663 // Lightweight form of highlight -- proceed over this line and 1664 // update state, but don't save a style array. Used for lines that 1665 // aren't currently visible. 1666 function processLine(cm, text, context, startAt) { 1667 var mode = cm.doc.mode; 1668 var stream = new StringStream(text, cm.options.tabSize, context); 1669 stream.start = stream.pos = startAt || 0; 1670 if (text == "") { callBlankLine(mode, context.state); } 1671 while (!stream.eol()) { 1672 readToken(mode, stream, context.state); 1673 stream.start = stream.pos; 1674 } 1675 } 1676 1677 function callBlankLine(mode, state) { 1678 if (mode.blankLine) { return mode.blankLine(state) } 1679 if (!mode.innerMode) { return } 1680 var inner = innerMode(mode, state); 1681 if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } 1682 } 1683 1684 function readToken(mode, stream, state, inner) { 1685 for (var i = 0; i < 10; i++) { 1686 if (inner) { inner[0] = innerMode(mode, state).mode; } 1687 var style = mode.token(stream, state); 1688 if (stream.pos > stream.start) { return style } 1689 } 1690 throw new Error("Mode " + mode.name + " failed to advance stream.") 1691 } 1692 1693 var Token = function(stream, type, state) { 1694 this.start = stream.start; this.end = stream.pos; 1695 this.string = stream.current(); 1696 this.type = type || null; 1697 this.state = state; 1698 }; 1699 1700 // Utility for getTokenAt and getLineTokens 1701 function takeToken(cm, pos, precise, asArray) { 1702 var doc = cm.doc, mode = doc.mode, style; 1703 pos = clipPos(doc, pos); 1704 var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); 1705 var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; 1706 if (asArray) { tokens = []; } 1707 while ((asArray || stream.pos < pos.ch) && !stream.eol()) { 1708 stream.start = stream.pos; 1709 style = readToken(mode, stream, context.state); 1710 if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } 1711 } 1712 return asArray ? tokens : new Token(stream, style, context.state) 1713 } 1714 1715 function extractLineClasses(type, output) { 1716 if (type) { for (;;) { 1717 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); 1718 if (!lineClass) { break } 1719 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); 1720 var prop = lineClass[1] ? "bgClass" : "textClass"; 1721 if (output[prop] == null) 1722 { output[prop] = lineClass[2]; } 1723 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) 1724 { output[prop] += " " + lineClass[2]; } 1725 } } 1726 return type 1727 } 1728 1729 // Run the given mode's parser over a line, calling f for each token. 1730 function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { 1731 var flattenSpans = mode.flattenSpans; 1732 if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } 1733 var curStart = 0, curStyle = null; 1734 var stream = new StringStream(text, cm.options.tabSize, context), style; 1735 var inner = cm.options.addModeClass && [null]; 1736 if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } 1737 while (!stream.eol()) { 1738 if (stream.pos > cm.options.maxHighlightLength) { 1739 flattenSpans = false; 1740 if (forceToEnd) { processLine(cm, text, context, stream.pos); } 1741 stream.pos = text.length; 1742 style = null; 1743 } else { 1744 style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); 1745 } 1746 if (inner) { 1747 var mName = inner[0].name; 1748 if (mName) { style = "m-" + (style ? mName + " " + style : mName); } 1749 } 1750 if (!flattenSpans || curStyle != style) { 1751 while (curStart < stream.start) { 1752 curStart = Math.min(stream.start, curStart + 5000); 1753 f(curStart, curStyle); 1754 } 1755 curStyle = style; 1756 } 1757 stream.start = stream.pos; 1758 } 1759 while (curStart < stream.pos) { 1760 // Webkit seems to refuse to render text nodes longer than 57444 1761 // characters, and returns inaccurate measurements in nodes 1762 // starting around 5000 chars. 1763 var pos = Math.min(stream.pos, curStart + 5000); 1764 f(pos, curStyle); 1765 curStart = pos; 1766 } 1767 } 1768 1769 // Finds the line to start with when starting a parse. Tries to 1770 // find a line with a stateAfter, so that it can start with a 1771 // valid state. If that fails, it returns the line with the 1772 // smallest indentation, which tends to need the least context to 1773 // parse correctly. 1774 function findStartLine(cm, n, precise) { 1775 var minindent, minline, doc = cm.doc; 1776 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); 1777 for (var search = n; search > lim; --search) { 1778 if (search <= doc.first) { return doc.first } 1779 var line = getLine(doc, search - 1), after = line.stateAfter; 1780 if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) 1781 { return search } 1782 var indented = countColumn(line.text, null, cm.options.tabSize); 1783 if (minline == null || minindent > indented) { 1784 minline = search - 1; 1785 minindent = indented; 1786 } 1787 } 1788 return minline 1789 } 1790 1791 function retreatFrontier(doc, n) { 1792 doc.modeFrontier = Math.min(doc.modeFrontier, n); 1793 if (doc.highlightFrontier < n - 10) { return } 1794 var start = doc.first; 1795 for (var line = n - 1; line > start; line--) { 1796 var saved = getLine(doc, line).stateAfter; 1797 // change is on 3 1798 // state on line 1 looked ahead 2 -- so saw 3 1799 // test 1 + 2 < 3 should cover this 1800 if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { 1801 start = line + 1; 1802 break 1803 } 1804 } 1805 doc.highlightFrontier = Math.min(doc.highlightFrontier, start); 1806 } 1807 1808 // LINE DATA STRUCTURE 1809 1810 // Line objects. These hold state related to a line, including 1811 // highlighting info (the styles array). 1812 var Line = function(text, markedSpans, estimateHeight) { 1813 this.text = text; 1814 attachMarkedSpans(this, markedSpans); 1815 this.height = estimateHeight ? estimateHeight(this) : 1; 1816 }; 1817 1818 Line.prototype.lineNo = function () { return lineNo(this) }; 1819 eventMixin(Line); 1820 1821 // Change the content (text, markers) of a line. Automatically 1822 // invalidates cached information and tries to re-estimate the 1823 // line's height. 1824 function updateLine(line, text, markedSpans, estimateHeight) { 1825 line.text = text; 1826 if (line.stateAfter) { line.stateAfter = null; } 1827 if (line.styles) { line.styles = null; } 1828 if (line.order != null) { line.order = null; } 1829 detachMarkedSpans(line); 1830 attachMarkedSpans(line, markedSpans); 1831 var estHeight = estimateHeight ? estimateHeight(line) : 1; 1832 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 1833 } 1834 1835 // Detach a line from the document tree and its markers. 1836 function cleanUpLine(line) { 1837 line.parent = null; 1838 detachMarkedSpans(line); 1839 } 1840 1841 // Convert a style as returned by a mode (either null, or a string 1842 // containing one or more styles) to a CSS style. This is cached, 1843 // and also looks for line-wide styles. 1844 var styleToClassCache = {}; 1845 var styleToClassCacheWithMode = {}; 1846 function interpretTokenStyle(style, options) { 1847 if (!style || /^\s*$/.test(style)) { return null } 1848 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; 1849 return cache[style] || 1850 (cache[style] = style.replace(/\S+/g, "cm-$&")) 1851 } 1852 1853 // Render the DOM representation of the text of a line. Also builds 1854 // up a 'line map', which points at the DOM nodes that represent 1855 // specific stretches of text, and is used by the measuring code. 1856 // The returned object contains the DOM node, this map, and 1857 // information about line-wide styles that were set by the mode. 1858 function buildLineContent(cm, lineView) { 1859 // The padding-right forces the element to have a 'border', which 1860 // is needed on Webkit to be able to get line-level bounding 1861 // rectangles for it (in measureChar). 1862 var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); 1863 var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, 1864 col: 0, pos: 0, cm: cm, 1865 trailingSpace: false, 1866 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; 1867 lineView.measure = {}; 1868 1869 // Iterate over the logical lines that make up this visual line. 1870 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { 1871 var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); 1872 builder.pos = 0; 1873 builder.addToken = buildToken; 1874 // Optionally wire in some hacks into the token-rendering 1875 // algorithm, to deal with browser quirks. 1876 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) 1877 { builder.addToken = buildTokenBadBidi(builder.addToken, order); } 1878 builder.map = []; 1879 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); 1880 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); 1881 if (line.styleClasses) { 1882 if (line.styleClasses.bgClass) 1883 { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } 1884 if (line.styleClasses.textClass) 1885 { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } 1886 } 1887 1888 // Ensure at least a single node is present, for measuring. 1889 if (builder.map.length == 0) 1890 { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } 1891 1892 // Store the map and a cache object for the current logical line 1893 if (i == 0) { 1894 lineView.measure.map = builder.map; 1895 lineView.measure.cache = {}; 1896 } else { 1897 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) 1898 ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); 1899 } 1900 } 1901 1902 // See issue #2901 1903 if (webkit) { 1904 var last = builder.content.lastChild; 1905 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) 1906 { builder.content.className = "cm-tab-wrap-hack"; } 1907 } 1908 1909 signal(cm, "renderLine", cm, lineView.line, builder.pre); 1910 if (builder.pre.className) 1911 { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } 1912 1913 return builder 1914 } 1915 1916 function defaultSpecialCharPlaceholder(ch) { 1917 var token = elt("span", "\u2022", "cm-invalidchar"); 1918 token.title = "\\u" + ch.charCodeAt(0).toString(16); 1919 token.setAttribute("aria-label", token.title); 1920 return token 1921 } 1922 1923 // Build up the DOM representation for a single token, and add it to 1924 // the line map. Takes care to render special characters separately. 1925 function buildToken(builder, text, style, startStyle, endStyle, title, css) { 1926 if (!text) { return } 1927 var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; 1928 var special = builder.cm.state.specialChars, mustWrap = false; 1929 var content; 1930 if (!special.test(text)) { 1931 builder.col += text.length; 1932 content = document.createTextNode(displayText); 1933 builder.map.push(builder.pos, builder.pos + text.length, content); 1934 if (ie && ie_version < 9) { mustWrap = true; } 1935 builder.pos += text.length; 1936 } else { 1937 content = document.createDocumentFragment(); 1938 var pos = 0; 1939 while (true) { 1940 special.lastIndex = pos; 1941 var m = special.exec(text); 1942 var skipped = m ? m.index - pos : text.length - pos; 1943 if (skipped) { 1944 var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); 1945 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } 1946 else { content.appendChild(txt); } 1947 builder.map.push(builder.pos, builder.pos + skipped, txt); 1948 builder.col += skipped; 1949 builder.pos += skipped; 1950 } 1951 if (!m) { break } 1952 pos += skipped + 1; 1953 var txt$1 = (void 0); 1954 if (m[0] == "\t") { 1955 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 1956 txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 1957 txt$1.setAttribute("role", "presentation"); 1958 txt$1.setAttribute("cm-text", "\t"); 1959 builder.col += tabWidth; 1960 } else if (m[0] == "\r" || m[0] == "\n") { 1961 txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); 1962 txt$1.setAttribute("cm-text", m[0]); 1963 builder.col += 1; 1964 } else { 1965 txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); 1966 txt$1.setAttribute("cm-text", m[0]); 1967 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } 1968 else { content.appendChild(txt$1); } 1969 builder.col += 1; 1970 } 1971 builder.map.push(builder.pos, builder.pos + 1, txt$1); 1972 builder.pos++; 1973 } 1974 } 1975 builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; 1976 if (style || startStyle || endStyle || mustWrap || css) { 1977 var fullStyle = style || ""; 1978 if (startStyle) { fullStyle += startStyle; } 1979 if (endStyle) { fullStyle += endStyle; } 1980 var token = elt("span", [content], fullStyle, css); 1981 if (title) { token.title = title; } 1982 return builder.content.appendChild(token) 1983 } 1984 builder.content.appendChild(content); 1985 } 1986 1987 function splitSpaces(text, trailingBefore) { 1988 if (text.length > 1 && !/ /.test(text)) { return text } 1989 var spaceBefore = trailingBefore, result = ""; 1990 for (var i = 0; i < text.length; i++) { 1991 var ch = text.charAt(i); 1992 if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) 1993 { ch = "\u00a0"; } 1994 result += ch; 1995 spaceBefore = ch == " "; 1996 } 1997 return result 1998 } 1999 2000 // Work around nonsense dimensions being reported for stretches of 2001 // right-to-left text. 2002 function buildTokenBadBidi(inner, order) { 2003 return function (builder, text, style, startStyle, endStyle, title, css) { 2004 style = style ? style + " cm-force-border" : "cm-force-border"; 2005 var start = builder.pos, end = start + text.length; 2006 for (;;) { 2007 // Find the part that overlaps with the start of this text 2008 var part = (void 0); 2009 for (var i = 0; i < order.length; i++) { 2010 part = order[i]; 2011 if (part.to > start && part.from <= start) { break } 2012 } 2013 if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } 2014 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); 2015 startStyle = null; 2016 text = text.slice(part.to - start); 2017 start = part.to; 2018 } 2019 } 2020 } 2021 2022 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { 2023 var widget = !ignoreWidget && marker.widgetNode; 2024 if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } 2025 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { 2026 if (!widget) 2027 { widget = builder.content.appendChild(document.createElement("span")); } 2028 widget.setAttribute("cm-marker", marker.id); 2029 } 2030 if (widget) { 2031 builder.cm.display.input.setUneditable(widget); 2032 builder.content.appendChild(widget); 2033 } 2034 builder.pos += size; 2035 builder.trailingSpace = false; 2036 } 2037 2038 // Outputs a number of spans to make up a line, taking highlighting 2039 // and marked text into account. 2040 function insertLineContent(line, builder, styles) { 2041 var spans = line.markedSpans, allText = line.text, at = 0; 2042 if (!spans) { 2043 for (var i$1 = 1; i$1 < styles.length; i$1+=2) 2044 { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } 2045 return 2046 } 2047 2048 var len = allText.length, pos = 0, i = 1, text = "", style, css; 2049 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; 2050 for (;;) { 2051 if (nextChange == pos) { // Update current marker set 2052 spanStyle = spanEndStyle = spanStartStyle = title = css = ""; 2053 collapsed = null; nextChange = Infinity; 2054 var foundBookmarks = [], endStyles = (void 0); 2055 for (var j = 0; j < spans.length; ++j) { 2056 var sp = spans[j], m = sp.marker; 2057 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { 2058 foundBookmarks.push(m); 2059 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { 2060 if (sp.to != null && sp.to != pos && nextChange > sp.to) { 2061 nextChange = sp.to; 2062 spanEndStyle = ""; 2063 } 2064 if (m.className) { spanStyle += " " + m.className; } 2065 if (m.css) { css = (css ? css + ";" : "") + m.css; } 2066 if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } 2067 if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } 2068 if (m.title && !title) { title = m.title; } 2069 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) 2070 { collapsed = sp; } 2071 } else if (sp.from > pos && nextChange > sp.from) { 2072 nextChange = sp.from; 2073 } 2074 } 2075 if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) 2076 { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } 2077 2078 if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) 2079 { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } 2080 if (collapsed && (collapsed.from || 0) == pos) { 2081 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, 2082 collapsed.marker, collapsed.from == null); 2083 if (collapsed.to == null) { return } 2084 if (collapsed.to == pos) { collapsed = false; } 2085 } 2086 } 2087 if (pos >= len) { break } 2088 2089 var upto = Math.min(len, nextChange); 2090 while (true) { 2091 if (text) { 2092 var end = pos + text.length; 2093 if (!collapsed) { 2094 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 2095 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 2096 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); 2097 } 2098 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} 2099 pos = end; 2100 spanStartStyle = ""; 2101 } 2102 text = allText.slice(at, at = styles[i++]); 2103 style = interpretTokenStyle(styles[i++], builder.cm.options); 2104 } 2105 } 2106 } 2107 2108 2109 // These objects are used to represent the visible (currently drawn) 2110 // part of the document. A LineView may correspond to multiple 2111 // logical lines, if those are connected by collapsed ranges. 2112 function LineView(doc, line, lineN) { 2113 // The starting line 2114 this.line = line; 2115 // Continuing lines, if any 2116 this.rest = visualLineContinued(line); 2117 // Number of logical lines in this visual line 2118 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; 2119 this.node = this.text = null; 2120 this.hidden = lineIsHidden(doc, line); 2121 } 2122 2123 // Create a range of LineView objects for the given lines. 2124 function buildViewArray(cm, from, to) { 2125 var array = [], nextPos; 2126 for (var pos = from; pos < to; pos = nextPos) { 2127 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); 2128 nextPos = pos + view.size; 2129 array.push(view); 2130 } 2131 return array 2132 } 2133 2134 var operationGroup = null; 2135 2136 function pushOperation(op) { 2137 if (operationGroup) { 2138 operationGroup.ops.push(op); 2139 } else { 2140 op.ownsGroup = operationGroup = { 2141 ops: [op], 2142 delayedCallbacks: [] 2143 }; 2144 } 2145 } 2146 2147 function fireCallbacksForOps(group) { 2148 // Calls delayed callbacks and cursorActivity handlers until no 2149 // new ones appear 2150 var callbacks = group.delayedCallbacks, i = 0; 2151 do { 2152 for (; i < callbacks.length; i++) 2153 { callbacks[i].call(null); } 2154 for (var j = 0; j < group.ops.length; j++) { 2155 var op = group.ops[j]; 2156 if (op.cursorActivityHandlers) 2157 { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) 2158 { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } 2159 } 2160 } while (i < callbacks.length) 2161 } 2162 2163 function finishOperation(op, endCb) { 2164 var group = op.ownsGroup; 2165 if (!group) { return } 2166 2167 try { fireCallbacksForOps(group); } 2168 finally { 2169 operationGroup = null; 2170 endCb(group); 2171 } 2172 } 2173 2174 var orphanDelayedCallbacks = null; 2175 2176 // Often, we want to signal events at a point where we are in the 2177 // middle of some work, but don't want the handler to start calling 2178 // other methods on the editor, which might be in an inconsistent 2179 // state or simply not expect any other events to happen. 2180 // signalLater looks whether there are any handlers, and schedules 2181 // them to be executed when the last operation ends, or, if no 2182 // operation is active, when a timeout fires. 2183 function signalLater(emitter, type /*, values...*/) { 2184 var arr = getHandlers(emitter, type); 2185 if (!arr.length) { return } 2186 var args = Array.prototype.slice.call(arguments, 2), list; 2187 if (operationGroup) { 2188 list = operationGroup.delayedCallbacks; 2189 } else if (orphanDelayedCallbacks) { 2190 list = orphanDelayedCallbacks; 2191 } else { 2192 list = orphanDelayedCallbacks = []; 2193 setTimeout(fireOrphanDelayed, 0); 2194 } 2195 var loop = function ( i ) { 2196 list.push(function () { return arr[i].apply(null, args); }); 2197 }; 2198 2199 for (var i = 0; i < arr.length; ++i) 2200 loop( i ); 2201 } 2202 2203 function fireOrphanDelayed() { 2204 var delayed = orphanDelayedCallbacks; 2205 orphanDelayedCallbacks = null; 2206 for (var i = 0; i < delayed.length; ++i) { delayed[i](); } 2207 } 2208 2209 // When an aspect of a line changes, a string is added to 2210 // lineView.changes. This updates the relevant part of the line's 2211 // DOM structure. 2212 function updateLineForChanges(cm, lineView, lineN, dims) { 2213 for (var j = 0; j < lineView.changes.length; j++) { 2214 var type = lineView.changes[j]; 2215 if (type == "text") { updateLineText(cm, lineView); } 2216 else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } 2217 else if (type == "class") { updateLineClasses(cm, lineView); } 2218 else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } 2219 } 2220 lineView.changes = null; 2221 } 2222 2223 // Lines with gutter elements, widgets or a background class need to 2224 // be wrapped, and have the extra elements added to the wrapper div 2225 function ensureLineWrapped(lineView) { 2226 if (lineView.node == lineView.text) { 2227 lineView.node = elt("div", null, null, "position: relative"); 2228 if (lineView.text.parentNode) 2229 { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } 2230 lineView.node.appendChild(lineView.text); 2231 if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } 2232 } 2233 return lineView.node 2234 } 2235 2236 function updateLineBackground(cm, lineView) { 2237 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; 2238 if (cls) { cls += " CodeMirror-linebackground"; } 2239 if (lineView.background) { 2240 if (cls) { lineView.background.className = cls; } 2241 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } 2242 } else if (cls) { 2243 var wrap = ensureLineWrapped(lineView); 2244 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); 2245 cm.display.input.setUneditable(lineView.background); 2246 } 2247 } 2248 2249 // Wrapper around buildLineContent which will reuse the structure 2250 // in display.externalMeasured when possible. 2251 function getLineContent(cm, lineView) { 2252 var ext = cm.display.externalMeasured; 2253 if (ext && ext.line == lineView.line) { 2254 cm.display.externalMeasured = null; 2255 lineView.measure = ext.measure; 2256 return ext.built 2257 } 2258 return buildLineContent(cm, lineView) 2259 } 2260 2261 // Redraw the line's text. Interacts with the background and text 2262 // classes because the mode may output tokens that influence these 2263 // classes. 2264 function updateLineText(cm, lineView) { 2265 var cls = lineView.text.className; 2266 var built = getLineContent(cm, lineView); 2267 if (lineView.text == lineView.node) { lineView.node = built.pre; } 2268 lineView.text.parentNode.replaceChild(built.pre, lineView.text); 2269 lineView.text = built.pre; 2270 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { 2271 lineView.bgClass = built.bgClass; 2272 lineView.textClass = built.textClass; 2273 updateLineClasses(cm, lineView); 2274 } else if (cls) { 2275 lineView.text.className = cls; 2276 } 2277 } 2278 2279 function updateLineClasses(cm, lineView) { 2280 updateLineBackground(cm, lineView); 2281 if (lineView.line.wrapClass) 2282 { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } 2283 else if (lineView.node != lineView.text) 2284 { lineView.node.className = ""; } 2285 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; 2286 lineView.text.className = textClass || ""; 2287 } 2288 2289 function updateLineGutter(cm, lineView, lineN, dims) { 2290 if (lineView.gutter) { 2291 lineView.node.removeChild(lineView.gutter); 2292 lineView.gutter = null; 2293 } 2294 if (lineView.gutterBackground) { 2295 lineView.node.removeChild(lineView.gutterBackground); 2296 lineView.gutterBackground = null; 2297 } 2298 if (lineView.line.gutterClass) { 2299 var wrap = ensureLineWrapped(lineView); 2300 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, 2301 ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); 2302 cm.display.input.setUneditable(lineView.gutterBackground); 2303 wrap.insertBefore(lineView.gutterBackground, lineView.text); 2304 } 2305 var markers = lineView.line.gutterMarkers; 2306 if (cm.options.lineNumbers || markers) { 2307 var wrap$1 = ensureLineWrapped(lineView); 2308 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); 2309 cm.display.input.setUneditable(gutterWrap); 2310 wrap$1.insertBefore(gutterWrap, lineView.text); 2311 if (lineView.line.gutterClass) 2312 { gutterWrap.className += " " + lineView.line.gutterClass; } 2313 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 2314 { lineView.lineNumber = gutterWrap.appendChild( 2315 elt("div", lineNumberFor(cm.options, lineN), 2316 "CodeMirror-linenumber CodeMirror-gutter-elt", 2317 ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } 2318 if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { 2319 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 2320 if (found) 2321 { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", 2322 ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } 2323 } } 2324 } 2325 } 2326 2327 function updateLineWidgets(cm, lineView, dims) { 2328 if (lineView.alignable) { lineView.alignable = null; } 2329 for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { 2330 next = node.nextSibling; 2331 if (node.className == "CodeMirror-linewidget") 2332 { lineView.node.removeChild(node); } 2333 } 2334 insertLineWidgets(cm, lineView, dims); 2335 } 2336 2337 // Build a line's DOM representation from scratch 2338 function buildLineElement(cm, lineView, lineN, dims) { 2339 var built = getLineContent(cm, lineView); 2340 lineView.text = lineView.node = built.pre; 2341 if (built.bgClass) { lineView.bgClass = built.bgClass; } 2342 if (built.textClass) { lineView.textClass = built.textClass; } 2343 2344 updateLineClasses(cm, lineView); 2345 updateLineGutter(cm, lineView, lineN, dims); 2346 insertLineWidgets(cm, lineView, dims); 2347 return lineView.node 2348 } 2349 2350 // A lineView may contain multiple logical lines (when merged by 2351 // collapsed spans). The widgets for all of them need to be drawn. 2352 function insertLineWidgets(cm, lineView, dims) { 2353 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); 2354 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2355 { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } 2356 } 2357 2358 function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { 2359 if (!line.widgets) { return } 2360 var wrap = ensureLineWrapped(lineView); 2361 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 2362 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 2363 if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } 2364 positionLineWidget(widget, node, lineView, dims); 2365 cm.display.input.setUneditable(node); 2366 if (allowAbove && widget.above) 2367 { wrap.insertBefore(node, lineView.gutter || lineView.text); } 2368 else 2369 { wrap.appendChild(node); } 2370 signalLater(widget, "redraw"); 2371 } 2372 } 2373 2374 function positionLineWidget(widget, node, lineView, dims) { 2375 if (widget.noHScroll) { 2376 (lineView.alignable || (lineView.alignable = [])).push(node); 2377 var width = dims.wrapperWidth; 2378 node.style.left = dims.fixedPos + "px"; 2379 if (!widget.coverGutter) { 2380 width -= dims.gutterTotalWidth; 2381 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 2382 } 2383 node.style.width = width + "px"; 2384 } 2385 if (widget.coverGutter) { 2386 node.style.zIndex = 5; 2387 node.style.position = "relative"; 2388 if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } 2389 } 2390 } 2391 2392 function widgetHeight(widget) { 2393 if (widget.height != null) { return widget.height } 2394 var cm = widget.doc.cm; 2395 if (!cm) { return 0 } 2396 if (!contains(document.body, widget.node)) { 2397 var parentStyle = "position: relative;"; 2398 if (widget.coverGutter) 2399 { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } 2400 if (widget.noHScroll) 2401 { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } 2402 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); 2403 } 2404 return widget.height = widget.node.parentNode.offsetHeight 2405 } 2406 2407 // Return true when the given mouse event happened in a widget 2408 function eventInWidget(display, e) { 2409 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 2410 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || 2411 (n.parentNode == display.sizer && n != display.mover)) 2412 { return true } 2413 } 2414 } 2415 2416 // POSITION MEASUREMENT 2417 2418 function paddingTop(display) {return display.lineSpace.offsetTop} 2419 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} 2420 function paddingH(display) { 2421 if (display.cachedPaddingH) { return display.cachedPaddingH } 2422 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); 2423 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; 2424 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; 2425 if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } 2426 return data 2427 } 2428 2429 function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } 2430 function displayWidth(cm) { 2431 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth 2432 } 2433 function displayHeight(cm) { 2434 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight 2435 } 2436 2437 // Ensure the lineView.wrapping.heights array is populated. This is 2438 // an array of bottom offsets for the lines that make up a drawn 2439 // line. When lineWrapping is on, there might be more than one 2440 // height. 2441 function ensureLineHeights(cm, lineView, rect) { 2442 var wrapping = cm.options.lineWrapping; 2443 var curWidth = wrapping && displayWidth(cm); 2444 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { 2445 var heights = lineView.measure.heights = []; 2446 if (wrapping) { 2447 lineView.measure.width = curWidth; 2448 var rects = lineView.text.firstChild.getClientRects(); 2449 for (var i = 0; i < rects.length - 1; i++) { 2450 var cur = rects[i], next = rects[i + 1]; 2451 if (Math.abs(cur.bottom - next.bottom) > 2) 2452 { heights.push((cur.bottom + next.top) / 2 - rect.top); } 2453 } 2454 } 2455 heights.push(rect.bottom - rect.top); 2456 } 2457 } 2458 2459 // Find a line map (mapping character offsets to text nodes) and a 2460 // measurement cache for the given line number. (A line view might 2461 // contain multiple lines when collapsed ranges are present.) 2462 function mapFromLineView(lineView, line, lineN) { 2463 if (lineView.line == line) 2464 { return {map: lineView.measure.map, cache: lineView.measure.cache} } 2465 for (var i = 0; i < lineView.rest.length; i++) 2466 { if (lineView.rest[i] == line) 2467 { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } 2468 for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) 2469 { if (lineNo(lineView.rest[i$1]) > lineN) 2470 { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } 2471 } 2472 2473 // Render a line into the hidden node display.externalMeasured. Used 2474 // when measurement is needed for a line that's not in the viewport. 2475 function updateExternalMeasurement(cm, line) { 2476 line = visualLine(line); 2477 var lineN = lineNo(line); 2478 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); 2479 view.lineN = lineN; 2480 var built = view.built = buildLineContent(cm, view); 2481 view.text = built.pre; 2482 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); 2483 return view 2484 } 2485 2486 // Get a {top, bottom, left, right} box (in line-local coordinates) 2487 // for a given character. 2488 function measureChar(cm, line, ch, bias) { 2489 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) 2490 } 2491 2492 // Find a line view that corresponds to the given line number. 2493 function findViewForLine(cm, lineN) { 2494 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) 2495 { return cm.display.view[findViewIndex(cm, lineN)] } 2496 var ext = cm.display.externalMeasured; 2497 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) 2498 { return ext } 2499 } 2500 2501 // Measurement can be split in two steps, the set-up work that 2502 // applies to the whole line, and the measurement of the actual 2503 // character. Functions like coordsChar, that need to do a lot of 2504 // measurements in a row, can thus ensure that the set-up work is 2505 // only done once. 2506 function prepareMeasureForLine(cm, line) { 2507 var lineN = lineNo(line); 2508 var view = findViewForLine(cm, lineN); 2509 if (view && !view.text) { 2510 view = null; 2511 } else if (view && view.changes) { 2512 updateLineForChanges(cm, view, lineN, getDimensions(cm)); 2513 cm.curOp.forceUpdate = true; 2514 } 2515 if (!view) 2516 { view = updateExternalMeasurement(cm, line); } 2517 2518 var info = mapFromLineView(view, line, lineN); 2519 return { 2520 line: line, view: view, rect: null, 2521 map: info.map, cache: info.cache, before: info.before, 2522 hasHeights: false 2523 } 2524 } 2525 2526 // Given a prepared measurement object, measures the position of an 2527 // actual character (or fetches it from the cache). 2528 function measureCharPrepared(cm, prepared, ch, bias, varHeight) { 2529 if (prepared.before) { ch = -1; } 2530 var key = ch + (bias || ""), found; 2531 if (prepared.cache.hasOwnProperty(key)) { 2532 found = prepared.cache[key]; 2533 } else { 2534 if (!prepared.rect) 2535 { prepared.rect = prepared.view.text.getBoundingClientRect(); } 2536 if (!prepared.hasHeights) { 2537 ensureLineHeights(cm, prepared.view, prepared.rect); 2538 prepared.hasHeights = true; 2539 } 2540 found = measureCharInner(cm, prepared, ch, bias); 2541 if (!found.bogus) { prepared.cache[key] = found; } 2542 } 2543 return {left: found.left, right: found.right, 2544 top: varHeight ? found.rtop : found.top, 2545 bottom: varHeight ? found.rbottom : found.bottom} 2546 } 2547 2548 var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; 2549 2550 function nodeAndOffsetInLineMap(map$$1, ch, bias) { 2551 var node, start, end, collapse, mStart, mEnd; 2552 // First, search the line map for the text node corresponding to, 2553 // or closest to, the target character. 2554 for (var i = 0; i < map$$1.length; i += 3) { 2555 mStart = map$$1[i]; 2556 mEnd = map$$1[i + 1]; 2557 if (ch < mStart) { 2558 start = 0; end = 1; 2559 collapse = "left"; 2560 } else if (ch < mEnd) { 2561 start = ch - mStart; 2562 end = start + 1; 2563 } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { 2564 end = mEnd - mStart; 2565 start = end - 1; 2566 if (ch >= mEnd) { collapse = "right"; } 2567 } 2568 if (start != null) { 2569 node = map$$1[i + 2]; 2570 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) 2571 { collapse = bias; } 2572 if (bias == "left" && start == 0) 2573 { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { 2574 node = map$$1[(i -= 3) + 2]; 2575 collapse = "left"; 2576 } } 2577 if (bias == "right" && start == mEnd - mStart) 2578 { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { 2579 node = map$$1[(i += 3) + 2]; 2580 collapse = "right"; 2581 } } 2582 break 2583 } 2584 } 2585 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} 2586 } 2587 2588 function getUsefulRect(rects, bias) { 2589 var rect = nullRect; 2590 if (bias == "left") { for (var i = 0; i < rects.length; i++) { 2591 if ((rect = rects[i]).left != rect.right) { break } 2592 } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { 2593 if ((rect = rects[i$1]).left != rect.right) { break } 2594 } } 2595 return rect 2596 } 2597 2598 function measureCharInner(cm, prepared, ch, bias) { 2599 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); 2600 var node = place.node, start = place.start, end = place.end, collapse = place.collapse; 2601 2602 var rect; 2603 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. 2604 for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned 2605 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } 2606 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } 2607 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) 2608 { rect = node.parentNode.getBoundingClientRect(); } 2609 else 2610 { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } 2611 if (rect.left || rect.right || start == 0) { break } 2612 end = start; 2613 start = start - 1; 2614 collapse = "right"; 2615 } 2616 if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } 2617 } else { // If it is a widget, simply get the box for the whole widget. 2618 if (start > 0) { collapse = bias = "right"; } 2619 var rects; 2620 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) 2621 { rect = rects[bias == "right" ? rects.length - 1 : 0]; } 2622 else 2623 { rect = node.getBoundingClientRect(); } 2624 } 2625 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { 2626 var rSpan = node.parentNode.getClientRects()[0]; 2627 if (rSpan) 2628 { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } 2629 else 2630 { rect = nullRect; } 2631 } 2632 2633 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; 2634 var mid = (rtop + rbot) / 2; 2635 var heights = prepared.view.measure.heights; 2636 var i = 0; 2637 for (; i < heights.length - 1; i++) 2638 { if (mid < heights[i]) { break } } 2639 var top = i ? heights[i - 1] : 0, bot = heights[i]; 2640 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, 2641 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, 2642 top: top, bottom: bot}; 2643 if (!rect.left && !rect.right) { result.bogus = true; } 2644 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } 2645 2646 return result 2647 } 2648 2649 // Work around problem with bounding client rects on ranges being 2650 // returned incorrectly when zoomed on IE10 and below. 2651 function maybeUpdateRectForZooming(measure, rect) { 2652 if (!window.screen || screen.logicalXDPI == null || 2653 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) 2654 { return rect } 2655 var scaleX = screen.logicalXDPI / screen.deviceXDPI; 2656 var scaleY = screen.logicalYDPI / screen.deviceYDPI; 2657 return {left: rect.left * scaleX, right: rect.right * scaleX, 2658 top: rect.top * scaleY, bottom: rect.bottom * scaleY} 2659 } 2660 2661 function clearLineMeasurementCacheFor(lineView) { 2662 if (lineView.measure) { 2663 lineView.measure.cache = {}; 2664 lineView.measure.heights = null; 2665 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2666 { lineView.measure.caches[i] = {}; } } 2667 } 2668 } 2669 2670 function clearLineMeasurementCache(cm) { 2671 cm.display.externalMeasure = null; 2672 removeChildren(cm.display.lineMeasure); 2673 for (var i = 0; i < cm.display.view.length; i++) 2674 { clearLineMeasurementCacheFor(cm.display.view[i]); } 2675 } 2676 2677 function clearCaches(cm) { 2678 clearLineMeasurementCache(cm); 2679 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; 2680 if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } 2681 cm.display.lineNumChars = null; 2682 } 2683 2684 function pageScrollX() { 2685 // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 2686 // which causes page_Offset and bounding client rects to use 2687 // different reference viewports and invalidate our calculations. 2688 if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } 2689 return window.pageXOffset || (document.documentElement || document.body).scrollLeft 2690 } 2691 function pageScrollY() { 2692 if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } 2693 return window.pageYOffset || (document.documentElement || document.body).scrollTop 2694 } 2695 2696 function widgetTopHeight(lineObj) { 2697 var height = 0; 2698 if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) 2699 { height += widgetHeight(lineObj.widgets[i]); } } } 2700 return height 2701 } 2702 2703 // Converts a {top, bottom, left, right} box from line-local 2704 // coordinates into another coordinate system. Context may be one of 2705 // "line", "div" (display.lineDiv), "local"./null (editor), "window", 2706 // or "page". 2707 function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { 2708 if (!includeWidgets) { 2709 var height = widgetTopHeight(lineObj); 2710 rect.top += height; rect.bottom += height; 2711 } 2712 if (context == "line") { return rect } 2713 if (!context) { context = "local"; } 2714 var yOff = heightAtLine(lineObj); 2715 if (context == "local") { yOff += paddingTop(cm.display); } 2716 else { yOff -= cm.display.viewOffset; } 2717 if (context == "page" || context == "window") { 2718 var lOff = cm.display.lineSpace.getBoundingClientRect(); 2719 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); 2720 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); 2721 rect.left += xOff; rect.right += xOff; 2722 } 2723 rect.top += yOff; rect.bottom += yOff; 2724 return rect 2725 } 2726 2727 // Coverts a box from "div" coords to another coordinate system. 2728 // Context may be "window", "page", "div", or "local"./null. 2729 function fromCoordSystem(cm, coords, context) { 2730 if (context == "div") { return coords } 2731 var left = coords.left, top = coords.top; 2732 // First move into "page" coordinate system 2733 if (context == "page") { 2734 left -= pageScrollX(); 2735 top -= pageScrollY(); 2736 } else if (context == "local" || !context) { 2737 var localBox = cm.display.sizer.getBoundingClientRect(); 2738 left += localBox.left; 2739 top += localBox.top; 2740 } 2741 2742 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); 2743 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} 2744 } 2745 2746 function charCoords(cm, pos, context, lineObj, bias) { 2747 if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } 2748 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) 2749 } 2750 2751 // Returns a box for a given cursor position, which may have an 2752 // 'other' property containing the position of the secondary cursor 2753 // on a bidi boundary. 2754 // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` 2755 // and after `char - 1` in writing order of `char - 1` 2756 // A cursor Pos(line, char, "after") is on the same visual line as `char` 2757 // and before `char` in writing order of `char` 2758 // Examples (upper-case letters are RTL, lower-case are LTR): 2759 // Pos(0, 1, ...) 2760 // before after 2761 // ab a|b a|b 2762 // aB a|B aB| 2763 // Ab |Ab A|b 2764 // AB B|A B|A 2765 // Every position after the last character on a line is considered to stick 2766 // to the last character on the line. 2767 function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { 2768 lineObj = lineObj || getLine(cm.doc, pos.line); 2769 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } 2770 function get(ch, right) { 2771 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); 2772 if (right) { m.left = m.right; } else { m.right = m.left; } 2773 return intoCoordSystem(cm, lineObj, m, context) 2774 } 2775 var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; 2776 if (ch >= lineObj.text.length) { 2777 ch = lineObj.text.length; 2778 sticky = "before"; 2779 } else if (ch <= 0) { 2780 ch = 0; 2781 sticky = "after"; 2782 } 2783 if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } 2784 2785 function getBidi(ch, partPos, invert) { 2786 var part = order[partPos], right = part.level == 1; 2787 return get(invert ? ch - 1 : ch, right != invert) 2788 } 2789 var partPos = getBidiPartAt(order, ch, sticky); 2790 var other = bidiOther; 2791 var val = getBidi(ch, partPos, sticky == "before"); 2792 if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } 2793 return val 2794 } 2795 2796 // Used to cheaply estimate the coordinates for a position. Used for 2797 // intermediate scroll updates. 2798 function estimateCoords(cm, pos) { 2799 var left = 0; 2800 pos = clipPos(cm.doc, pos); 2801 if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } 2802 var lineObj = getLine(cm.doc, pos.line); 2803 var top = heightAtLine(lineObj) + paddingTop(cm.display); 2804 return {left: left, right: left, top: top, bottom: top + lineObj.height} 2805 } 2806 2807 // Positions returned by coordsChar contain some extra information. 2808 // xRel is the relative x position of the input coordinates compared 2809 // to the found position (so xRel > 0 means the coordinates are to 2810 // the right of the character position, for example). When outside 2811 // is true, that means the coordinates lie outside the line's 2812 // vertical range. 2813 function PosWithInfo(line, ch, sticky, outside, xRel) { 2814 var pos = Pos(line, ch, sticky); 2815 pos.xRel = xRel; 2816 if (outside) { pos.outside = true; } 2817 return pos 2818 } 2819 2820 // Compute the character position closest to the given coordinates. 2821 // Input must be lineSpace-local ("div" coordinate system). 2822 function coordsChar(cm, x, y) { 2823 var doc = cm.doc; 2824 y += cm.display.viewOffset; 2825 if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } 2826 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 2827 if (lineN > last) 2828 { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } 2829 if (x < 0) { x = 0; } 2830 2831 var lineObj = getLine(doc, lineN); 2832 for (;;) { 2833 var found = coordsCharInner(cm, lineObj, lineN, x, y); 2834 var merged = collapsedSpanAtEnd(lineObj); 2835 var mergedPos = merged && merged.find(0, true); 2836 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) 2837 { lineN = lineNo(lineObj = mergedPos.to.line); } 2838 else 2839 { return found } 2840 } 2841 } 2842 2843 function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { 2844 y -= widgetTopHeight(lineObj); 2845 var end = lineObj.text.length; 2846 var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); 2847 end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); 2848 return {begin: begin, end: end} 2849 } 2850 2851 function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { 2852 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } 2853 var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; 2854 return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) 2855 } 2856 2857 // Returns true if the given side of a box is after the given 2858 // coordinates, in top-to-bottom, left-to-right order. 2859 function boxIsAfter(box, x, y, left) { 2860 return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x 2861 } 2862 2863 function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { 2864 // Move y into line-local coordinate space 2865 y -= heightAtLine(lineObj); 2866 var preparedMeasure = prepareMeasureForLine(cm, lineObj); 2867 // When directly calling `measureCharPrepared`, we have to adjust 2868 // for the widgets at this line. 2869 var widgetHeight$$1 = widgetTopHeight(lineObj); 2870 var begin = 0, end = lineObj.text.length, ltr = true; 2871 2872 var order = getOrder(lineObj, cm.doc.direction); 2873 // If the line isn't plain left-to-right text, first figure out 2874 // which bidi section the coordinates fall into. 2875 if (order) { 2876 var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) 2877 (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); 2878 ltr = part.level != 1; 2879 // The awkward -1 offsets are needed because findFirst (called 2880 // on these below) will treat its first bound as inclusive, 2881 // second as exclusive, but we want to actually address the 2882 // characters in the part's range 2883 begin = ltr ? part.from : part.to - 1; 2884 end = ltr ? part.to : part.from - 1; 2885 } 2886 2887 // A binary search to find the first character whose bounding box 2888 // starts after the coordinates. If we run across any whose box wrap 2889 // the coordinates, store that. 2890 var chAround = null, boxAround = null; 2891 var ch = findFirst(function (ch) { 2892 var box = measureCharPrepared(cm, preparedMeasure, ch); 2893 box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; 2894 if (!boxIsAfter(box, x, y, false)) { return false } 2895 if (box.top <= y && box.left <= x) { 2896 chAround = ch; 2897 boxAround = box; 2898 } 2899 return true 2900 }, begin, end); 2901 2902 var baseX, sticky, outside = false; 2903 // If a box around the coordinates was found, use that 2904 if (boxAround) { 2905 // Distinguish coordinates nearer to the left or right side of the box 2906 var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; 2907 ch = chAround + (atStart ? 0 : 1); 2908 sticky = atStart ? "after" : "before"; 2909 baseX = atLeft ? boxAround.left : boxAround.right; 2910 } else { 2911 // (Adjust for extended bound, if necessary.) 2912 if (!ltr && (ch == end || ch == begin)) { ch++; } 2913 // To determine which side to associate with, get the box to the 2914 // left of the character and compare it's vertical position to the 2915 // coordinates 2916 sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : 2917 (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? 2918 "after" : "before"; 2919 // Now get accurate coordinates for this place, in order to get a 2920 // base X position 2921 var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); 2922 baseX = coords.left; 2923 outside = y < coords.top || y >= coords.bottom; 2924 } 2925 2926 ch = skipExtendingChars(lineObj.text, ch, 1); 2927 return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) 2928 } 2929 2930 function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { 2931 // Bidi parts are sorted left-to-right, and in a non-line-wrapping 2932 // situation, we can take this ordering to correspond to the visual 2933 // ordering. This finds the first part whose end is after the given 2934 // coordinates. 2935 var index = findFirst(function (i) { 2936 var part = order[i], ltr = part.level != 1; 2937 return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), 2938 "line", lineObj, preparedMeasure), x, y, true) 2939 }, 0, order.length - 1); 2940 var part = order[index]; 2941 // If this isn't the first part, the part's start is also after 2942 // the coordinates, and the coordinates aren't on the same line as 2943 // that start, move one part back. 2944 if (index > 0) { 2945 var ltr = part.level != 1; 2946 var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), 2947 "line", lineObj, preparedMeasure); 2948 if (boxIsAfter(start, x, y, true) && start.top > y) 2949 { part = order[index - 1]; } 2950 } 2951 return part 2952 } 2953 2954 function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { 2955 // In a wrapped line, rtl text on wrapping boundaries can do things 2956 // that don't correspond to the ordering in our `order` array at 2957 // all, so a binary search doesn't work, and we want to return a 2958 // part that only spans one line so that the binary search in 2959 // coordsCharInner is safe. As such, we first find the extent of the 2960 // wrapped line, and then do a flat search in which we discard any 2961 // spans that aren't on the line. 2962 var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); 2963 var begin = ref.begin; 2964 var end = ref.end; 2965 if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } 2966 var part = null, closestDist = null; 2967 for (var i = 0; i < order.length; i++) { 2968 var p = order[i]; 2969 if (p.from >= end || p.to <= begin) { continue } 2970 var ltr = p.level != 1; 2971 var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; 2972 // Weigh against spans ending before this, so that they are only 2973 // picked if nothing ends after 2974 var dist = endX < x ? x - endX + 1e9 : endX - x; 2975 if (!part || closestDist > dist) { 2976 part = p; 2977 closestDist = dist; 2978 } 2979 } 2980 if (!part) { part = order[order.length - 1]; } 2981 // Clip the part to the wrapped line. 2982 if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } 2983 if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } 2984 return part 2985 } 2986 2987 var measureText; 2988 // Compute the default text height. 2989 function textHeight(display) { 2990 if (display.cachedTextHeight != null) { return display.cachedTextHeight } 2991 if (measureText == null) { 2992 measureText = elt("pre"); 2993 // Measure a bunch of lines, for browsers that compute 2994 // fractional heights. 2995 for (var i = 0; i < 49; ++i) { 2996 measureText.appendChild(document.createTextNode("x")); 2997 measureText.appendChild(elt("br")); 2998 } 2999 measureText.appendChild(document.createTextNode("x")); 3000 } 3001 removeChildrenAndAdd(display.measure, measureText); 3002 var height = measureText.offsetHeight / 50; 3003 if (height > 3) { display.cachedTextHeight = height; } 3004 removeChildren(display.measure); 3005 return height || 1 3006 } 3007 3008 // Compute the default character width. 3009 function charWidth(display) { 3010 if (display.cachedCharWidth != null) { return display.cachedCharWidth } 3011 var anchor = elt("span", "xxxxxxxxxx"); 3012 var pre = elt("pre", [anchor]); 3013 removeChildrenAndAdd(display.measure, pre); 3014 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; 3015 if (width > 2) { display.cachedCharWidth = width; } 3016 return width || 10 3017 } 3018 3019 // Do a bulk-read of the DOM positions and sizes needed to draw the 3020 // view, so that we don't interleave reading and writing to the DOM. 3021 function getDimensions(cm) { 3022 var d = cm.display, left = {}, width = {}; 3023 var gutterLeft = d.gutters.clientLeft; 3024 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 3025 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; 3026 width[cm.options.gutters[i]] = n.clientWidth; 3027 } 3028 return {fixedPos: compensateForHScroll(d), 3029 gutterTotalWidth: d.gutters.offsetWidth, 3030 gutterLeft: left, 3031 gutterWidth: width, 3032 wrapperWidth: d.wrapper.clientWidth} 3033 } 3034 3035 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, 3036 // but using getBoundingClientRect to get a sub-pixel-accurate 3037 // result. 3038 function compensateForHScroll(display) { 3039 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left 3040 } 3041 3042 // Returns a function that estimates the height of a line, to use as 3043 // first approximation until the line becomes visible (and is thus 3044 // properly measurable). 3045 function estimateHeight(cm) { 3046 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; 3047 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); 3048 return function (line) { 3049 if (lineIsHidden(cm.doc, line)) { return 0 } 3050 3051 var widgetsHeight = 0; 3052 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { 3053 if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } 3054 } } 3055 3056 if (wrapping) 3057 { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } 3058 else 3059 { return widgetsHeight + th } 3060 } 3061 } 3062 3063 function estimateLineHeights(cm) { 3064 var doc = cm.doc, est = estimateHeight(cm); 3065 doc.iter(function (line) { 3066 var estHeight = est(line); 3067 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 3068 }); 3069 } 3070 3071 // Given a mouse event, find the corresponding position. If liberal 3072 // is false, it checks whether a gutter or scrollbar was clicked, 3073 // and returns null if it was. forRect is used by rectangular 3074 // selections, and tries to estimate a character position even for 3075 // coordinates beyond the right of the text. 3076 function posFromMouse(cm, e, liberal, forRect) { 3077 var display = cm.display; 3078 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } 3079 3080 var x, y, space = display.lineSpace.getBoundingClientRect(); 3081 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 3082 try { x = e.clientX - space.left; y = e.clientY - space.top; } 3083 catch (e) { return null } 3084 var coords = coordsChar(cm, x, y), line; 3085 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { 3086 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; 3087 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); 3088 } 3089 return coords 3090 } 3091 3092 // Find the view element corresponding to a given line. Return null 3093 // when the line isn't visible. 3094 function findViewIndex(cm, n) { 3095 if (n >= cm.display.viewTo) { return null } 3096 n -= cm.display.viewFrom; 3097 if (n < 0) { return null } 3098 var view = cm.display.view; 3099 for (var i = 0; i < view.length; i++) { 3100 n -= view[i].size; 3101 if (n < 0) { return i } 3102 } 3103 } 3104 3105 function updateSelection(cm) { 3106 cm.display.input.showSelection(cm.display.input.prepareSelection()); 3107 } 3108 3109 function prepareSelection(cm, primary) { 3110 if ( primary === void 0 ) primary = true; 3111 3112 var doc = cm.doc, result = {}; 3113 var curFragment = result.cursors = document.createDocumentFragment(); 3114 var selFragment = result.selection = document.createDocumentFragment(); 3115 3116 for (var i = 0; i < doc.sel.ranges.length; i++) { 3117 if (!primary && i == doc.sel.primIndex) { continue } 3118 var range$$1 = doc.sel.ranges[i]; 3119 if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } 3120 var collapsed = range$$1.empty(); 3121 if (collapsed || cm.options.showCursorWhenSelecting) 3122 { drawSelectionCursor(cm, range$$1.head, curFragment); } 3123 if (!collapsed) 3124 { drawSelectionRange(cm, range$$1, selFragment); } 3125 } 3126 return result 3127 } 3128 3129 // Draws a cursor for the given range 3130 function drawSelectionCursor(cm, head, output) { 3131 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); 3132 3133 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); 3134 cursor.style.left = pos.left + "px"; 3135 cursor.style.top = pos.top + "px"; 3136 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 3137 3138 if (pos.other) { 3139 // Secondary cursor, shown when on a 'jump' in bi-directional text 3140 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); 3141 otherCursor.style.display = ""; 3142 otherCursor.style.left = pos.other.left + "px"; 3143 otherCursor.style.top = pos.other.top + "px"; 3144 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 3145 } 3146 } 3147 3148 function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } 3149 3150 // Draws the given range as a highlighted selection 3151 function drawSelectionRange(cm, range$$1, output) { 3152 var display = cm.display, doc = cm.doc; 3153 var fragment = document.createDocumentFragment(); 3154 var padding = paddingH(cm.display), leftSide = padding.left; 3155 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; 3156 var docLTR = doc.direction == "ltr"; 3157 3158 function add(left, top, width, bottom) { 3159 if (top < 0) { top = 0; } 3160 top = Math.round(top); 3161 bottom = Math.round(bottom); 3162 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"))); 3163 } 3164 3165 function drawForLine(line, fromArg, toArg) { 3166 var lineObj = getLine(doc, line); 3167 var lineLen = lineObj.text.length; 3168 var start, end; 3169 function coords(ch, bias) { 3170 return charCoords(cm, Pos(line, ch), "div", lineObj, bias) 3171 } 3172 3173 function wrapX(pos, dir, side) { 3174 var extent = wrappedLineExtentChar(cm, lineObj, null, pos); 3175 var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; 3176 var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); 3177 return coords(ch, prop)[prop] 3178 } 3179 3180 var order = getOrder(lineObj, doc.direction); 3181 iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { 3182 var ltr = dir == "ltr"; 3183 var fromPos = coords(from, ltr ? "left" : "right"); 3184 var toPos = coords(to - 1, ltr ? "right" : "left"); 3185 3186 var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; 3187 var first = i == 0, last = !order || i == order.length - 1; 3188 if (toPos.top - fromPos.top <= 3) { // Single line 3189 var openLeft = (docLTR ? openStart : openEnd) && first; 3190 var openRight = (docLTR ? openEnd : openStart) && last; 3191 var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; 3192 var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; 3193 add(left, fromPos.top, right - left, fromPos.bottom); 3194 } else { // Multiple lines 3195 var topLeft, topRight, botLeft, botRight; 3196 if (ltr) { 3197 topLeft = docLTR && openStart && first ? leftSide : fromPos.left; 3198 topRight = docLTR ? rightSide : wrapX(from, dir, "before"); 3199 botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); 3200 botRight = docLTR && openEnd && last ? rightSide : toPos.right; 3201 } else { 3202 topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); 3203 topRight = !docLTR && openStart && first ? rightSide : fromPos.right; 3204 botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; 3205 botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); 3206 } 3207 add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); 3208 if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } 3209 add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); 3210 } 3211 3212 if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } 3213 if (cmpCoords(toPos, start) < 0) { start = toPos; } 3214 if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } 3215 if (cmpCoords(toPos, end) < 0) { end = toPos; } 3216 }); 3217 return {start: start, end: end} 3218 } 3219 3220 var sFrom = range$$1.from(), sTo = range$$1.to(); 3221 if (sFrom.line == sTo.line) { 3222 drawForLine(sFrom.line, sFrom.ch, sTo.ch); 3223 } else { 3224 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); 3225 var singleVLine = visualLine(fromLine) == visualLine(toLine); 3226 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; 3227 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; 3228 if (singleVLine) { 3229 if (leftEnd.top < rightStart.top - 2) { 3230 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); 3231 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); 3232 } else { 3233 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); 3234 } 3235 } 3236 if (leftEnd.bottom < rightStart.top) 3237 { add(leftSide, leftEnd.bottom, null, rightStart.top); } 3238 } 3239 3240 output.appendChild(fragment); 3241 } 3242 3243 // Cursor-blinking 3244 function restartBlink(cm) { 3245 if (!cm.state.focused) { return } 3246 var display = cm.display; 3247 clearInterval(display.blinker); 3248 var on = true; 3249 display.cursorDiv.style.visibility = ""; 3250 if (cm.options.cursorBlinkRate > 0) 3251 { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, 3252 cm.options.cursorBlinkRate); } 3253 else if (cm.options.cursorBlinkRate < 0) 3254 { display.cursorDiv.style.visibility = "hidden"; } 3255 } 3256 3257 function ensureFocus(cm) { 3258 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } 3259 } 3260 3261 function delayBlurEvent(cm) { 3262 cm.state.delayingBlurEvent = true; 3263 setTimeout(function () { if (cm.state.delayingBlurEvent) { 3264 cm.state.delayingBlurEvent = false; 3265 onBlur(cm); 3266 } }, 100); 3267 } 3268 3269 function onFocus(cm, e) { 3270 if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } 3271 3272 if (cm.options.readOnly == "nocursor") { return } 3273 if (!cm.state.focused) { 3274 signal(cm, "focus", cm, e); 3275 cm.state.focused = true; 3276 addClass(cm.display.wrapper, "CodeMirror-focused"); 3277 // This test prevents this from firing when a context 3278 // menu is closed (since the input reset would kill the 3279 // select-all detection hack) 3280 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { 3281 cm.display.input.reset(); 3282 if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 3283 } 3284 cm.display.input.receivedFocus(); 3285 } 3286 restartBlink(cm); 3287 } 3288 function onBlur(cm, e) { 3289 if (cm.state.delayingBlurEvent) { return } 3290 3291 if (cm.state.focused) { 3292 signal(cm, "blur", cm, e); 3293 cm.state.focused = false; 3294 rmClass(cm.display.wrapper, "CodeMirror-focused"); 3295 } 3296 clearInterval(cm.display.blinker); 3297 setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); 3298 } 3299 3300 // Read the actual heights of the rendered lines, and update their 3301 // stored heights to match. 3302 function updateHeightsInViewport(cm) { 3303 var display = cm.display; 3304 var prevBottom = display.lineDiv.offsetTop; 3305 for (var i = 0; i < display.view.length; i++) { 3306 var cur = display.view[i], height = (void 0); 3307 if (cur.hidden) { continue } 3308 if (ie && ie_version < 8) { 3309 var bot = cur.node.offsetTop + cur.node.offsetHeight; 3310 height = bot - prevBottom; 3311 prevBottom = bot; 3312 } else { 3313 var box = cur.node.getBoundingClientRect(); 3314 height = box.bottom - box.top; 3315 } 3316 var diff = cur.line.height - height; 3317 if (height < 2) { height = textHeight(display); } 3318 if (diff > .005 || diff < -.005) { 3319 updateLineHeight(cur.line, height); 3320 updateWidgetHeight(cur.line); 3321 if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) 3322 { updateWidgetHeight(cur.rest[j]); } } 3323 } 3324 } 3325 } 3326 3327 // Read and store the height of line widgets associated with the 3328 // given line. 3329 function updateWidgetHeight(line) { 3330 if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) 3331 { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } } 3332 } 3333 3334 // Compute the lines that are visible in a given viewport (defaults 3335 // the the current scroll position). viewport may contain top, 3336 // height, and ensure (see op.scrollToPos) properties. 3337 function visibleLines(display, doc, viewport) { 3338 var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; 3339 top = Math.floor(top - paddingTop(display)); 3340 var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; 3341 3342 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); 3343 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and 3344 // forces those lines into the viewport (if possible). 3345 if (viewport && viewport.ensure) { 3346 var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; 3347 if (ensureFrom < from) { 3348 from = ensureFrom; 3349 to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); 3350 } else if (Math.min(ensureTo, doc.lastLine()) >= to) { 3351 from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); 3352 to = ensureTo; 3353 } 3354 } 3355 return {from: from, to: Math.max(to, from + 1)} 3356 } 3357 3358 // Re-align line numbers and gutter marks to compensate for 3359 // horizontal scrolling. 3360 function alignHorizontally(cm) { 3361 var display = cm.display, view = display.view; 3362 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } 3363 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; 3364 var gutterW = display.gutters.offsetWidth, left = comp + "px"; 3365 for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { 3366 if (cm.options.fixedGutter) { 3367 if (view[i].gutter) 3368 { view[i].gutter.style.left = left; } 3369 if (view[i].gutterBackground) 3370 { view[i].gutterBackground.style.left = left; } 3371 } 3372 var align = view[i].alignable; 3373 if (align) { for (var j = 0; j < align.length; j++) 3374 { align[j].style.left = left; } } 3375 } } 3376 if (cm.options.fixedGutter) 3377 { display.gutters.style.left = (comp + gutterW) + "px"; } 3378 } 3379 3380 // Used to ensure that the line number gutter is still the right 3381 // size for the current document size. Returns true when an update 3382 // is needed. 3383 function maybeUpdateLineNumberWidth(cm) { 3384 if (!cm.options.lineNumbers) { return false } 3385 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 3386 if (last.length != display.lineNumChars) { 3387 var test = display.measure.appendChild(elt("div", [elt("div", last)], 3388 "CodeMirror-linenumber CodeMirror-gutter-elt")); 3389 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 3390 display.lineGutter.style.width = ""; 3391 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; 3392 display.lineNumWidth = display.lineNumInnerWidth + padding; 3393 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 3394 display.lineGutter.style.width = display.lineNumWidth + "px"; 3395 updateGutterSpace(cm); 3396 return true 3397 } 3398 return false 3399 } 3400 3401 // SCROLLING THINGS INTO VIEW 3402 3403 // If an editor sits on the top or bottom of the window, partially 3404 // scrolled out of view, this ensures that the cursor is visible. 3405 function maybeScrollWindow(cm, rect) { 3406 if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } 3407 3408 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; 3409 if (rect.top + box.top < 0) { doScroll = true; } 3410 else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } 3411 if (doScroll != null && !phantom) { 3412 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;")); 3413 cm.display.lineSpace.appendChild(scrollNode); 3414 scrollNode.scrollIntoView(doScroll); 3415 cm.display.lineSpace.removeChild(scrollNode); 3416 } 3417 } 3418 3419 // Scroll a given position into view (immediately), verifying that 3420 // it actually became visible (as line heights are accurately 3421 // measured, the position of something may 'drift' during drawing). 3422 function scrollPosIntoView(cm, pos, end, margin) { 3423 if (margin == null) { margin = 0; } 3424 var rect; 3425 if (!cm.options.lineWrapping && pos == end) { 3426 // Set pos and end to the cursor positions around the character pos sticks to 3427 // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch 3428 // If pos == Pos(_, 0, "before"), pos and end are unchanged 3429 pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; 3430 end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; 3431 } 3432 for (var limit = 0; limit < 5; limit++) { 3433 var changed = false; 3434 var coords = cursorCoords(cm, pos); 3435 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); 3436 rect = {left: Math.min(coords.left, endCoords.left), 3437 top: Math.min(coords.top, endCoords.top) - margin, 3438 right: Math.max(coords.left, endCoords.left), 3439 bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; 3440 var scrollPos = calculateScrollPos(cm, rect); 3441 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 3442 if (scrollPos.scrollTop != null) { 3443 updateScrollTop(cm, scrollPos.scrollTop); 3444 if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } 3445 } 3446 if (scrollPos.scrollLeft != null) { 3447 setScrollLeft(cm, scrollPos.scrollLeft); 3448 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } 3449 } 3450 if (!changed) { break } 3451 } 3452 return rect 3453 } 3454 3455 // Scroll a given set of coordinates into view (immediately). 3456 function scrollIntoView(cm, rect) { 3457 var scrollPos = calculateScrollPos(cm, rect); 3458 if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } 3459 if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } 3460 } 3461 3462 // Calculate a new scroll position needed to scroll the given 3463 // rectangle into view. Returns an object with scrollTop and 3464 // scrollLeft properties. When these are undefined, the 3465 // vertical/horizontal position does not need to be adjusted. 3466 function calculateScrollPos(cm, rect) { 3467 var display = cm.display, snapMargin = textHeight(cm.display); 3468 if (rect.top < 0) { rect.top = 0; } 3469 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; 3470 var screen = displayHeight(cm), result = {}; 3471 if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } 3472 var docBottom = cm.doc.height + paddingVert(display); 3473 var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; 3474 if (rect.top < screentop) { 3475 result.scrollTop = atTop ? 0 : rect.top; 3476 } else if (rect.bottom > screentop + screen) { 3477 var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); 3478 if (newTop != screentop) { result.scrollTop = newTop; } 3479 } 3480 3481 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; 3482 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); 3483 var tooWide = rect.right - rect.left > screenw; 3484 if (tooWide) { rect.right = rect.left + screenw; } 3485 if (rect.left < 10) 3486 { result.scrollLeft = 0; } 3487 else if (rect.left < screenleft) 3488 { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } 3489 else if (rect.right > screenw + screenleft - 3) 3490 { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } 3491 return result 3492 } 3493 3494 // Store a relative adjustment to the scroll position in the current 3495 // operation (to be applied when the operation finishes). 3496 function addToScrollTop(cm, top) { 3497 if (top == null) { return } 3498 resolveScrollToPos(cm); 3499 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; 3500 } 3501 3502 // Make sure that at the end of the operation the current cursor is 3503 // shown. 3504 function ensureCursorVisible(cm) { 3505 resolveScrollToPos(cm); 3506 var cur = cm.getCursor(); 3507 cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; 3508 } 3509 3510 function scrollToCoords(cm, x, y) { 3511 if (x != null || y != null) { resolveScrollToPos(cm); } 3512 if (x != null) { cm.curOp.scrollLeft = x; } 3513 if (y != null) { cm.curOp.scrollTop = y; } 3514 } 3515 3516 function scrollToRange(cm, range$$1) { 3517 resolveScrollToPos(cm); 3518 cm.curOp.scrollToPos = range$$1; 3519 } 3520 3521 // When an operation has its scrollToPos property set, and another 3522 // scroll action is applied before the end of the operation, this 3523 // 'simulates' scrolling that position into view in a cheap way, so 3524 // that the effect of intermediate scroll commands is not ignored. 3525 function resolveScrollToPos(cm) { 3526 var range$$1 = cm.curOp.scrollToPos; 3527 if (range$$1) { 3528 cm.curOp.scrollToPos = null; 3529 var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); 3530 scrollToCoordsRange(cm, from, to, range$$1.margin); 3531 } 3532 } 3533 3534 function scrollToCoordsRange(cm, from, to, margin) { 3535 var sPos = calculateScrollPos(cm, { 3536 left: Math.min(from.left, to.left), 3537 top: Math.min(from.top, to.top) - margin, 3538 right: Math.max(from.right, to.right), 3539 bottom: Math.max(from.bottom, to.bottom) + margin 3540 }); 3541 scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); 3542 } 3543 3544 // Sync the scrollable area and scrollbars, ensure the viewport 3545 // covers the visible area. 3546 function updateScrollTop(cm, val) { 3547 if (Math.abs(cm.doc.scrollTop - val) < 2) { return } 3548 if (!gecko) { updateDisplaySimple(cm, {top: val}); } 3549 setScrollTop(cm, val, true); 3550 if (gecko) { updateDisplaySimple(cm); } 3551 startWorker(cm, 100); 3552 } 3553 3554 function setScrollTop(cm, val, forceScroll) { 3555 val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); 3556 if (cm.display.scroller.scrollTop == val && !forceScroll) { return } 3557 cm.doc.scrollTop = val; 3558 cm.display.scrollbars.setScrollTop(val); 3559 if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } 3560 } 3561 3562 // Sync scroller and scrollbar, ensure the gutter elements are 3563 // aligned. 3564 function setScrollLeft(cm, val, isScroller, forceScroll) { 3565 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 3566 if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } 3567 cm.doc.scrollLeft = val; 3568 alignHorizontally(cm); 3569 if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } 3570 cm.display.scrollbars.setScrollLeft(val); 3571 } 3572 3573 // SCROLLBARS 3574 3575 // Prepare DOM reads needed to update the scrollbars. Done in one 3576 // shot to minimize update/measure roundtrips. 3577 function measureForScrollbars(cm) { 3578 var d = cm.display, gutterW = d.gutters.offsetWidth; 3579 var docH = Math.round(cm.doc.height + paddingVert(cm.display)); 3580 return { 3581 clientHeight: d.scroller.clientHeight, 3582 viewHeight: d.wrapper.clientHeight, 3583 scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, 3584 viewWidth: d.wrapper.clientWidth, 3585 barLeft: cm.options.fixedGutter ? gutterW : 0, 3586 docHeight: docH, 3587 scrollHeight: docH + scrollGap(cm) + d.barHeight, 3588 nativeBarWidth: d.nativeBarWidth, 3589 gutterWidth: gutterW 3590 } 3591 } 3592 3593 var NativeScrollbars = function(place, scroll, cm) { 3594 this.cm = cm; 3595 var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); 3596 var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); 3597 place(vert); place(horiz); 3598 3599 on(vert, "scroll", function () { 3600 if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } 3601 }); 3602 on(horiz, "scroll", function () { 3603 if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } 3604 }); 3605 3606 this.checkedZeroWidth = false; 3607 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). 3608 if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } 3609 }; 3610 3611 NativeScrollbars.prototype.update = function (measure) { 3612 var needsH = measure.scrollWidth > measure.clientWidth + 1; 3613 var needsV = measure.scrollHeight > measure.clientHeight + 1; 3614 var sWidth = measure.nativeBarWidth; 3615 3616 if (needsV) { 3617 this.vert.style.display = "block"; 3618 this.vert.style.bottom = needsH ? sWidth + "px" : "0"; 3619 var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); 3620 // A bug in IE8 can cause this value to be negative, so guard it. 3621 this.vert.firstChild.style.height = 3622 Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; 3623 } else { 3624 this.vert.style.display = ""; 3625 this.vert.firstChild.style.height = "0"; 3626 } 3627 3628 if (needsH) { 3629 this.horiz.style.display = "block"; 3630 this.horiz.style.right = needsV ? sWidth + "px" : "0"; 3631 this.horiz.style.left = measure.barLeft + "px"; 3632 var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); 3633 this.horiz.firstChild.style.width = 3634 Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; 3635 } else { 3636 this.horiz.style.display = ""; 3637 this.horiz.firstChild.style.width = "0"; 3638 } 3639 3640 if (!this.checkedZeroWidth && measure.clientHeight > 0) { 3641 if (sWidth == 0) { this.zeroWidthHack(); } 3642 this.checkedZeroWidth = true; 3643 } 3644 3645 return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} 3646 }; 3647 3648 NativeScrollbars.prototype.setScrollLeft = function (pos) { 3649 if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } 3650 if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } 3651 }; 3652 3653 NativeScrollbars.prototype.setScrollTop = function (pos) { 3654 if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } 3655 if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } 3656 }; 3657 3658 NativeScrollbars.prototype.zeroWidthHack = function () { 3659 var w = mac && !mac_geMountainLion ? "12px" : "18px"; 3660 this.horiz.style.height = this.vert.style.width = w; 3661 this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; 3662 this.disableHoriz = new Delayed; 3663 this.disableVert = new Delayed; 3664 }; 3665 3666 NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { 3667 bar.style.pointerEvents = "auto"; 3668 function maybeDisable() { 3669 // To find out whether the scrollbar is still visible, we 3670 // check whether the element under the pixel in the bottom 3671 // right corner of the scrollbar box is the scrollbar box 3672 // itself (when the bar is still visible) or its filler child 3673 // (when the bar is hidden). If it is still visible, we keep 3674 // it enabled, if it's hidden, we disable pointer events. 3675 var box = bar.getBoundingClientRect(); 3676 var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) 3677 : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); 3678 if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } 3679 else { delay.set(1000, maybeDisable); } 3680 } 3681 delay.set(1000, maybeDisable); 3682 }; 3683 3684 NativeScrollbars.prototype.clear = function () { 3685 var parent = this.horiz.parentNode; 3686 parent.removeChild(this.horiz); 3687 parent.removeChild(this.vert); 3688 }; 3689 3690 var NullScrollbars = function () {}; 3691 3692 NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; 3693 NullScrollbars.prototype.setScrollLeft = function () {}; 3694 NullScrollbars.prototype.setScrollTop = function () {}; 3695 NullScrollbars.prototype.clear = function () {}; 3696 3697 function updateScrollbars(cm, measure) { 3698 if (!measure) { measure = measureForScrollbars(cm); } 3699 var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; 3700 updateScrollbarsInner(cm, measure); 3701 for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { 3702 if (startWidth != cm.display.barWidth && cm.options.lineWrapping) 3703 { updateHeightsInViewport(cm); } 3704 updateScrollbarsInner(cm, measureForScrollbars(cm)); 3705 startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; 3706 } 3707 } 3708 3709 // Re-synchronize the fake scrollbars with the actual size of the 3710 // content. 3711 function updateScrollbarsInner(cm, measure) { 3712 var d = cm.display; 3713 var sizes = d.scrollbars.update(measure); 3714 3715 d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; 3716 d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; 3717 d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; 3718 3719 if (sizes.right && sizes.bottom) { 3720 d.scrollbarFiller.style.display = "block"; 3721 d.scrollbarFiller.style.height = sizes.bottom + "px"; 3722 d.scrollbarFiller.style.width = sizes.right + "px"; 3723 } else { d.scrollbarFiller.style.display = ""; } 3724 if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { 3725 d.gutterFiller.style.display = "block"; 3726 d.gutterFiller.style.height = sizes.bottom + "px"; 3727 d.gutterFiller.style.width = measure.gutterWidth + "px"; 3728 } else { d.gutterFiller.style.display = ""; } 3729 } 3730 3731 var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; 3732 3733 function initScrollbars(cm) { 3734 if (cm.display.scrollbars) { 3735 cm.display.scrollbars.clear(); 3736 if (cm.display.scrollbars.addClass) 3737 { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3738 } 3739 3740 cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { 3741 cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); 3742 // Prevent clicks in the scrollbars from killing focus 3743 on(node, "mousedown", function () { 3744 if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } 3745 }); 3746 node.setAttribute("cm-not-content", "true"); 3747 }, function (pos, axis) { 3748 if (axis == "horizontal") { setScrollLeft(cm, pos); } 3749 else { updateScrollTop(cm, pos); } 3750 }, cm); 3751 if (cm.display.scrollbars.addClass) 3752 { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3753 } 3754 3755 // Operations are used to wrap a series of changes to the editor 3756 // state in such a way that each change won't have to update the 3757 // cursor and display (which would be awkward, slow, and 3758 // error-prone). Instead, display updates are batched and then all 3759 // combined and executed at once. 3760 3761 var nextOpId = 0; 3762 // Start a new operation. 3763 function startOperation(cm) { 3764 cm.curOp = { 3765 cm: cm, 3766 viewChanged: false, // Flag that indicates that lines might need to be redrawn 3767 startHeight: cm.doc.height, // Used to detect need to update scrollbar 3768 forceUpdate: false, // Used to force a redraw 3769 updateInput: null, // Whether to reset the input textarea 3770 typing: false, // Whether this reset should be careful to leave existing text (for compositing) 3771 changeObjs: null, // Accumulated changes, for firing change events 3772 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on 3773 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already 3774 selectionChanged: false, // Whether the selection needs to be redrawn 3775 updateMaxLine: false, // Set when the widest line needs to be determined anew 3776 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet 3777 scrollToPos: null, // Used to scroll to a specific position 3778 focus: false, 3779 id: ++nextOpId // Unique ID 3780 }; 3781 pushOperation(cm.curOp); 3782 } 3783 3784 // Finish an operation, updating the display and signalling delayed events 3785 function endOperation(cm) { 3786 var op = cm.curOp; 3787 finishOperation(op, function (group) { 3788 for (var i = 0; i < group.ops.length; i++) 3789 { group.ops[i].cm.curOp = null; } 3790 endOperations(group); 3791 }); 3792 } 3793 3794 // The DOM updates done when an operation finishes are batched so 3795 // that the minimum number of relayouts are required. 3796 function endOperations(group) { 3797 var ops = group.ops; 3798 for (var i = 0; i < ops.length; i++) // Read DOM 3799 { endOperation_R1(ops[i]); } 3800 for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) 3801 { endOperation_W1(ops[i$1]); } 3802 for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM 3803 { endOperation_R2(ops[i$2]); } 3804 for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) 3805 { endOperation_W2(ops[i$3]); } 3806 for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM 3807 { endOperation_finish(ops[i$4]); } 3808 } 3809 3810 function endOperation_R1(op) { 3811 var cm = op.cm, display = cm.display; 3812 maybeClipScrollbars(cm); 3813 if (op.updateMaxLine) { findMaxLine(cm); } 3814 3815 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || 3816 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || 3817 op.scrollToPos.to.line >= display.viewTo) || 3818 display.maxLineChanged && cm.options.lineWrapping; 3819 op.update = op.mustUpdate && 3820 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); 3821 } 3822 3823 function endOperation_W1(op) { 3824 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); 3825 } 3826 3827 function endOperation_R2(op) { 3828 var cm = op.cm, display = cm.display; 3829 if (op.updatedDisplay) { updateHeightsInViewport(cm); } 3830 3831 op.barMeasure = measureForScrollbars(cm); 3832 3833 // If the max line changed since it was last measured, measure it, 3834 // and ensure the document's width matches it. 3835 // updateDisplay_W2 will use these properties to do the actual resizing 3836 if (display.maxLineChanged && !cm.options.lineWrapping) { 3837 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; 3838 cm.display.sizerWidth = op.adjustWidthTo; 3839 op.barMeasure.scrollWidth = 3840 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); 3841 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); 3842 } 3843 3844 if (op.updatedDisplay || op.selectionChanged) 3845 { op.preparedSelection = display.input.prepareSelection(); } 3846 } 3847 3848 function endOperation_W2(op) { 3849 var cm = op.cm; 3850 3851 if (op.adjustWidthTo != null) { 3852 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; 3853 if (op.maxScrollLeft < cm.doc.scrollLeft) 3854 { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } 3855 cm.display.maxLineChanged = false; 3856 } 3857 3858 var takeFocus = op.focus && op.focus == activeElt(); 3859 if (op.preparedSelection) 3860 { cm.display.input.showSelection(op.preparedSelection, takeFocus); } 3861 if (op.updatedDisplay || op.startHeight != cm.doc.height) 3862 { updateScrollbars(cm, op.barMeasure); } 3863 if (op.updatedDisplay) 3864 { setDocumentHeight(cm, op.barMeasure); } 3865 3866 if (op.selectionChanged) { restartBlink(cm); } 3867 3868 if (cm.state.focused && op.updateInput) 3869 { cm.display.input.reset(op.typing); } 3870 if (takeFocus) { ensureFocus(op.cm); } 3871 } 3872 3873 function endOperation_finish(op) { 3874 var cm = op.cm, display = cm.display, doc = cm.doc; 3875 3876 if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } 3877 3878 // Abort mouse wheel delta measurement, when scrolling explicitly 3879 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) 3880 { display.wheelStartX = display.wheelStartY = null; } 3881 3882 // Propagate the scroll position to the actual DOM scroller 3883 if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } 3884 3885 if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } 3886 // If we need to scroll a specific position into view, do so. 3887 if (op.scrollToPos) { 3888 var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), 3889 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); 3890 maybeScrollWindow(cm, rect); 3891 } 3892 3893 // Fire events for markers that are hidden/unidden by editing or 3894 // undoing 3895 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 3896 if (hidden) { for (var i = 0; i < hidden.length; ++i) 3897 { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } 3898 if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) 3899 { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } 3900 3901 if (display.wrapper.offsetHeight) 3902 { doc.scrollTop = cm.display.scroller.scrollTop; } 3903 3904 // Fire change events, and delayed event handlers 3905 if (op.changeObjs) 3906 { signal(cm, "changes", cm, op.changeObjs); } 3907 if (op.update) 3908 { op.update.finish(); } 3909 } 3910 3911 // Run the given function in an operation 3912 function runInOp(cm, f) { 3913 if (cm.curOp) { return f() } 3914 startOperation(cm); 3915 try { return f() } 3916 finally { endOperation(cm); } 3917 } 3918 // Wraps a function in an operation. Returns the wrapped function. 3919 function operation(cm, f) { 3920 return function() { 3921 if (cm.curOp) { return f.apply(cm, arguments) } 3922 startOperation(cm); 3923 try { return f.apply(cm, arguments) } 3924 finally { endOperation(cm); } 3925 } 3926 } 3927 // Used to add methods to editor and doc instances, wrapping them in 3928 // operations. 3929 function methodOp(f) { 3930 return function() { 3931 if (this.curOp) { return f.apply(this, arguments) } 3932 startOperation(this); 3933 try { return f.apply(this, arguments) } 3934 finally { endOperation(this); } 3935 } 3936 } 3937 function docMethodOp(f) { 3938 return function() { 3939 var cm = this.cm; 3940 if (!cm || cm.curOp) { return f.apply(this, arguments) } 3941 startOperation(cm); 3942 try { return f.apply(this, arguments) } 3943 finally { endOperation(cm); } 3944 } 3945 } 3946 3947 // Updates the display.view data structure for a given change to the 3948 // document. From and to are in pre-change coordinates. Lendiff is 3949 // the amount of lines added or subtracted by the change. This is 3950 // used for changes that span multiple lines, or change the way 3951 // lines are divided into visual lines. regLineChange (below) 3952 // registers single-line changes. 3953 function regChange(cm, from, to, lendiff) { 3954 if (from == null) { from = cm.doc.first; } 3955 if (to == null) { to = cm.doc.first + cm.doc.size; } 3956 if (!lendiff) { lendiff = 0; } 3957 3958 var display = cm.display; 3959 if (lendiff && to < display.viewTo && 3960 (display.updateLineNumbers == null || display.updateLineNumbers > from)) 3961 { display.updateLineNumbers = from; } 3962 3963 cm.curOp.viewChanged = true; 3964 3965 if (from >= display.viewTo) { // Change after 3966 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) 3967 { resetView(cm); } 3968 } else if (to <= display.viewFrom) { // Change before 3969 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { 3970 resetView(cm); 3971 } else { 3972 display.viewFrom += lendiff; 3973 display.viewTo += lendiff; 3974 } 3975 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap 3976 resetView(cm); 3977 } else if (from <= display.viewFrom) { // Top overlap 3978 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); 3979 if (cut) { 3980 display.view = display.view.slice(cut.index); 3981 display.viewFrom = cut.lineN; 3982 display.viewTo += lendiff; 3983 } else { 3984 resetView(cm); 3985 } 3986 } else if (to >= display.viewTo) { // Bottom overlap 3987 var cut$1 = viewCuttingPoint(cm, from, from, -1); 3988 if (cut$1) { 3989 display.view = display.view.slice(0, cut$1.index); 3990 display.viewTo = cut$1.lineN; 3991 } else { 3992 resetView(cm); 3993 } 3994 } else { // Gap in the middle 3995 var cutTop = viewCuttingPoint(cm, from, from, -1); 3996 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); 3997 if (cutTop && cutBot) { 3998 display.view = display.view.slice(0, cutTop.index) 3999 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) 4000 .concat(display.view.slice(cutBot.index)); 4001 display.viewTo += lendiff; 4002 } else { 4003 resetView(cm); 4004 } 4005 } 4006 4007 var ext = display.externalMeasured; 4008 if (ext) { 4009 if (to < ext.lineN) 4010 { ext.lineN += lendiff; } 4011 else if (from < ext.lineN + ext.size) 4012 { display.externalMeasured = null; } 4013 } 4014 } 4015 4016 // Register a change to a single line. Type must be one of "text", 4017 // "gutter", "class", "widget" 4018 function regLineChange(cm, line, type) { 4019 cm.curOp.viewChanged = true; 4020 var display = cm.display, ext = cm.display.externalMeasured; 4021 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) 4022 { display.externalMeasured = null; } 4023 4024 if (line < display.viewFrom || line >= display.viewTo) { return } 4025 var lineView = display.view[findViewIndex(cm, line)]; 4026 if (lineView.node == null) { return } 4027 var arr = lineView.changes || (lineView.changes = []); 4028 if (indexOf(arr, type) == -1) { arr.push(type); } 4029 } 4030 4031 // Clear the view. 4032 function resetView(cm) { 4033 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; 4034 cm.display.view = []; 4035 cm.display.viewOffset = 0; 4036 } 4037 4038 function viewCuttingPoint(cm, oldN, newN, dir) { 4039 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; 4040 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) 4041 { return {index: index, lineN: newN} } 4042 var n = cm.display.viewFrom; 4043 for (var i = 0; i < index; i++) 4044 { n += view[i].size; } 4045 if (n != oldN) { 4046 if (dir > 0) { 4047 if (index == view.length - 1) { return null } 4048 diff = (n + view[index].size) - oldN; 4049 index++; 4050 } else { 4051 diff = n - oldN; 4052 } 4053 oldN += diff; newN += diff; 4054 } 4055 while (visualLineNo(cm.doc, newN) != newN) { 4056 if (index == (dir < 0 ? 0 : view.length - 1)) { return null } 4057 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; 4058 index += dir; 4059 } 4060 return {index: index, lineN: newN} 4061 } 4062 4063 // Force the view to cover a given range, adding empty view element 4064 // or clipping off existing ones as needed. 4065 function adjustView(cm, from, to) { 4066 var display = cm.display, view = display.view; 4067 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { 4068 display.view = buildViewArray(cm, from, to); 4069 display.viewFrom = from; 4070 } else { 4071 if (display.viewFrom > from) 4072 { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } 4073 else if (display.viewFrom < from) 4074 { display.view = display.view.slice(findViewIndex(cm, from)); } 4075 display.viewFrom = from; 4076 if (display.viewTo < to) 4077 { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } 4078 else if (display.viewTo > to) 4079 { display.view = display.view.slice(0, findViewIndex(cm, to)); } 4080 } 4081 display.viewTo = to; 4082 } 4083 4084 // Count the number of lines in the view whose DOM representation is 4085 // out of date (or nonexistent). 4086 function countDirtyView(cm) { 4087 var view = cm.display.view, dirty = 0; 4088 for (var i = 0; i < view.length; i++) { 4089 var lineView = view[i]; 4090 if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } 4091 } 4092 return dirty 4093 } 4094 4095 // HIGHLIGHT WORKER 4096 4097 function startWorker(cm, time) { 4098 if (cm.doc.highlightFrontier < cm.display.viewTo) 4099 { cm.state.highlight.set(time, bind(highlightWorker, cm)); } 4100 } 4101 4102 function highlightWorker(cm) { 4103 var doc = cm.doc; 4104 if (doc.highlightFrontier >= cm.display.viewTo) { return } 4105 var end = +new Date + cm.options.workTime; 4106 var context = getContextBefore(cm, doc.highlightFrontier); 4107 var changedLines = []; 4108 4109 doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { 4110 if (context.line >= cm.display.viewFrom) { // Visible 4111 var oldStyles = line.styles; 4112 var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; 4113 var highlighted = highlightLine(cm, line, context, true); 4114 if (resetState) { context.state = resetState; } 4115 line.styles = highlighted.styles; 4116 var oldCls = line.styleClasses, newCls = highlighted.classes; 4117 if (newCls) { line.styleClasses = newCls; } 4118 else if (oldCls) { line.styleClasses = null; } 4119 var ischange = !oldStyles || oldStyles.length != line.styles.length || 4120 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); 4121 for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } 4122 if (ischange) { changedLines.push(context.line); } 4123 line.stateAfter = context.save(); 4124 context.nextLine(); 4125 } else { 4126 if (line.text.length <= cm.options.maxHighlightLength) 4127 { processLine(cm, line.text, context); } 4128 line.stateAfter = context.line % 5 == 0 ? context.save() : null; 4129 context.nextLine(); 4130 } 4131 if (+new Date > end) { 4132 startWorker(cm, cm.options.workDelay); 4133 return true 4134 } 4135 }); 4136 doc.highlightFrontier = context.line; 4137 doc.modeFrontier = Math.max(doc.modeFrontier, context.line); 4138 if (changedLines.length) { runInOp(cm, function () { 4139 for (var i = 0; i < changedLines.length; i++) 4140 { regLineChange(cm, changedLines[i], "text"); } 4141 }); } 4142 } 4143 4144 // DISPLAY DRAWING 4145 4146 var DisplayUpdate = function(cm, viewport, force) { 4147 var display = cm.display; 4148 4149 this.viewport = viewport; 4150 // Store some values that we'll need later (but don't want to force a relayout for) 4151 this.visible = visibleLines(display, cm.doc, viewport); 4152 this.editorIsHidden = !display.wrapper.offsetWidth; 4153 this.wrapperHeight = display.wrapper.clientHeight; 4154 this.wrapperWidth = display.wrapper.clientWidth; 4155 this.oldDisplayWidth = displayWidth(cm); 4156 this.force = force; 4157 this.dims = getDimensions(cm); 4158 this.events = []; 4159 }; 4160 4161 DisplayUpdate.prototype.signal = function (emitter, type) { 4162 if (hasHandler(emitter, type)) 4163 { this.events.push(arguments); } 4164 }; 4165 DisplayUpdate.prototype.finish = function () { 4166 var this$1 = this; 4167 4168 for (var i = 0; i < this.events.length; i++) 4169 { signal.apply(null, this$1.events[i]); } 4170 }; 4171 4172 function maybeClipScrollbars(cm) { 4173 var display = cm.display; 4174 if (!display.scrollbarsClipped && display.scroller.offsetWidth) { 4175 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; 4176 display.heightForcer.style.height = scrollGap(cm) + "px"; 4177 display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; 4178 display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; 4179 display.scrollbarsClipped = true; 4180 } 4181 } 4182 4183 function selectionSnapshot(cm) { 4184 if (cm.hasFocus()) { return null } 4185 var active = activeElt(); 4186 if (!active || !contains(cm.display.lineDiv, active)) { return null } 4187 var result = {activeElt: active}; 4188 if (window.getSelection) { 4189 var sel = window.getSelection(); 4190 if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { 4191 result.anchorNode = sel.anchorNode; 4192 result.anchorOffset = sel.anchorOffset; 4193 result.focusNode = sel.focusNode; 4194 result.focusOffset = sel.focusOffset; 4195 } 4196 } 4197 return result 4198 } 4199 4200 function restoreSelection(snapshot) { 4201 if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } 4202 snapshot.activeElt.focus(); 4203 if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { 4204 var sel = window.getSelection(), range$$1 = document.createRange(); 4205 range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); 4206 range$$1.collapse(false); 4207 sel.removeAllRanges(); 4208 sel.addRange(range$$1); 4209 sel.extend(snapshot.focusNode, snapshot.focusOffset); 4210 } 4211 } 4212 4213 // Does the actual updating of the line display. Bails out 4214 // (returning false) when there is nothing to be done and forced is 4215 // false. 4216 function updateDisplayIfNeeded(cm, update) { 4217 var display = cm.display, doc = cm.doc; 4218 4219 if (update.editorIsHidden) { 4220 resetView(cm); 4221 return false 4222 } 4223 4224 // Bail out if the visible area is already rendered and nothing changed. 4225 if (!update.force && 4226 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && 4227 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && 4228 display.renderedView == display.view && countDirtyView(cm) == 0) 4229 { return false } 4230 4231 if (maybeUpdateLineNumberWidth(cm)) { 4232 resetView(cm); 4233 update.dims = getDimensions(cm); 4234 } 4235 4236 // Compute a suitable new viewport (from & to) 4237 var end = doc.first + doc.size; 4238 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); 4239 var to = Math.min(end, update.visible.to + cm.options.viewportMargin); 4240 if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } 4241 if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } 4242 if (sawCollapsedSpans) { 4243 from = visualLineNo(cm.doc, from); 4244 to = visualLineEndNo(cm.doc, to); 4245 } 4246 4247 var different = from != display.viewFrom || to != display.viewTo || 4248 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; 4249 adjustView(cm, from, to); 4250 4251 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); 4252 // Position the mover div to align with the current scroll position 4253 cm.display.mover.style.top = display.viewOffset + "px"; 4254 4255 var toUpdate = countDirtyView(cm); 4256 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && 4257 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) 4258 { return false } 4259 4260 // For big changes, we hide the enclosing element during the 4261 // update, since that speeds up the operations on most browsers. 4262 var selSnapshot = selectionSnapshot(cm); 4263 if (toUpdate > 4) { display.lineDiv.style.display = "none"; } 4264 patchDisplay(cm, display.updateLineNumbers, update.dims); 4265 if (toUpdate > 4) { display.lineDiv.style.display = ""; } 4266 display.renderedView = display.view; 4267 // There might have been a widget with a focused element that got 4268 // hidden or updated, if so re-focus it. 4269 restoreSelection(selSnapshot); 4270 4271 // Prevent selection and cursors from interfering with the scroll 4272 // width and height. 4273 removeChildren(display.cursorDiv); 4274 removeChildren(display.selectionDiv); 4275 display.gutters.style.height = display.sizer.style.minHeight = 0; 4276 4277 if (different) { 4278 display.lastWrapHeight = update.wrapperHeight; 4279 display.lastWrapWidth = update.wrapperWidth; 4280 startWorker(cm, 400); 4281 } 4282 4283 display.updateLineNumbers = null; 4284 4285 return true 4286 } 4287 4288 function postUpdateDisplay(cm, update) { 4289 var viewport = update.viewport; 4290 4291 for (var first = true;; first = false) { 4292 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { 4293 // Clip forced viewport to actual scrollable area. 4294 if (viewport && viewport.top != null) 4295 { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } 4296 // Updated line heights might result in the drawn area not 4297 // actually covering the viewport. Keep looping until it does. 4298 update.visible = visibleLines(cm.display, cm.doc, viewport); 4299 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) 4300 { break } 4301 } 4302 if (!updateDisplayIfNeeded(cm, update)) { break } 4303 updateHeightsInViewport(cm); 4304 var barMeasure = measureForScrollbars(cm); 4305 updateSelection(cm); 4306 updateScrollbars(cm, barMeasure); 4307 setDocumentHeight(cm, barMeasure); 4308 update.force = false; 4309 } 4310 4311 update.signal(cm, "update", cm); 4312 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { 4313 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); 4314 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; 4315 } 4316 } 4317 4318 function updateDisplaySimple(cm, viewport) { 4319 var update = new DisplayUpdate(cm, viewport); 4320 if (updateDisplayIfNeeded(cm, update)) { 4321 updateHeightsInViewport(cm); 4322 postUpdateDisplay(cm, update); 4323 var barMeasure = measureForScrollbars(cm); 4324 updateSelection(cm); 4325 updateScrollbars(cm, barMeasure); 4326 setDocumentHeight(cm, barMeasure); 4327 update.finish(); 4328 } 4329 } 4330 4331 // Sync the actual display DOM structure with display.view, removing 4332 // nodes for lines that are no longer in view, and creating the ones 4333 // that are not there yet, and updating the ones that are out of 4334 // date. 4335 function patchDisplay(cm, updateNumbersFrom, dims) { 4336 var display = cm.display, lineNumbers = cm.options.lineNumbers; 4337 var container = display.lineDiv, cur = container.firstChild; 4338 4339 function rm(node) { 4340 var next = node.nextSibling; 4341 // Works around a throw-scroll bug in OS X Webkit 4342 if (webkit && mac && cm.display.currentWheelTarget == node) 4343 { node.style.display = "none"; } 4344 else 4345 { node.parentNode.removeChild(node); } 4346 return next 4347 } 4348 4349 var view = display.view, lineN = display.viewFrom; 4350 // Loop over the elements in the view, syncing cur (the DOM nodes 4351 // in display.lineDiv) with the view as we go. 4352 for (var i = 0; i < view.length; i++) { 4353 var lineView = view[i]; 4354 if (lineView.hidden) { 4355 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet 4356 var node = buildLineElement(cm, lineView, lineN, dims); 4357 container.insertBefore(node, cur); 4358 } else { // Already drawn 4359 while (cur != lineView.node) { cur = rm(cur); } 4360 var updateNumber = lineNumbers && updateNumbersFrom != null && 4361 updateNumbersFrom <= lineN && lineView.lineNumber; 4362 if (lineView.changes) { 4363 if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } 4364 updateLineForChanges(cm, lineView, lineN, dims); 4365 } 4366 if (updateNumber) { 4367 removeChildren(lineView.lineNumber); 4368 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); 4369 } 4370 cur = lineView.node.nextSibling; 4371 } 4372 lineN += lineView.size; 4373 } 4374 while (cur) { cur = rm(cur); } 4375 } 4376 4377 function updateGutterSpace(cm) { 4378 var width = cm.display.gutters.offsetWidth; 4379 cm.display.sizer.style.marginLeft = width + "px"; 4380 } 4381 4382 function setDocumentHeight(cm, measure) { 4383 cm.display.sizer.style.minHeight = measure.docHeight + "px"; 4384 cm.display.heightForcer.style.top = measure.docHeight + "px"; 4385 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; 4386 } 4387 4388 // Rebuild the gutter elements, ensure the margin to the left of the 4389 // code matches their width. 4390 function updateGutters(cm) { 4391 var gutters = cm.display.gutters, specs = cm.options.gutters; 4392 removeChildren(gutters); 4393 var i = 0; 4394 for (; i < specs.length; ++i) { 4395 var gutterClass = specs[i]; 4396 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); 4397 if (gutterClass == "CodeMirror-linenumbers") { 4398 cm.display.lineGutter = gElt; 4399 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; 4400 } 4401 } 4402 gutters.style.display = i ? "" : "none"; 4403 updateGutterSpace(cm); 4404 } 4405 4406 // Make sure the gutters options contains the element 4407 // "CodeMirror-linenumbers" when the lineNumbers option is true. 4408 function setGuttersForLineNumbers(options) { 4409 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); 4410 if (found == -1 && options.lineNumbers) { 4411 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); 4412 } else if (found > -1 && !options.lineNumbers) { 4413 options.gutters = options.gutters.slice(0); 4414 options.gutters.splice(found, 1); 4415 } 4416 } 4417 4418 // Since the delta values reported on mouse wheel events are 4419 // unstandardized between browsers and even browser versions, and 4420 // generally horribly unpredictable, this code starts by measuring 4421 // the scroll effect that the first few mouse wheel events have, 4422 // and, from that, detects the way it can convert deltas to pixel 4423 // offsets afterwards. 4424 // 4425 // The reason we want to know the amount a wheel event will scroll 4426 // is that it gives us a chance to update the display before the 4427 // actual scrolling happens, reducing flickering. 4428 4429 var wheelSamples = 0; 4430 var wheelPixelsPerUnit = null; 4431 // Fill in a browser-detected starting value on browsers where we 4432 // know one. These don't have to be accurate -- the result of them 4433 // being wrong would just be a slight flicker on the first wheel 4434 // scroll (if it is large enough). 4435 if (ie) { wheelPixelsPerUnit = -.53; } 4436 else if (gecko) { wheelPixelsPerUnit = 15; } 4437 else if (chrome) { wheelPixelsPerUnit = -.7; } 4438 else if (safari) { wheelPixelsPerUnit = -1/3; } 4439 4440 function wheelEventDelta(e) { 4441 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 4442 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } 4443 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } 4444 else if (dy == null) { dy = e.wheelDelta; } 4445 return {x: dx, y: dy} 4446 } 4447 function wheelEventPixels(e) { 4448 var delta = wheelEventDelta(e); 4449 delta.x *= wheelPixelsPerUnit; 4450 delta.y *= wheelPixelsPerUnit; 4451 return delta 4452 } 4453 4454 function onScrollWheel(cm, e) { 4455 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; 4456 4457 var display = cm.display, scroll = display.scroller; 4458 // Quit if there's nothing to scroll here 4459 var canScrollX = scroll.scrollWidth > scroll.clientWidth; 4460 var canScrollY = scroll.scrollHeight > scroll.clientHeight; 4461 if (!(dx && canScrollX || dy && canScrollY)) { return } 4462 4463 // Webkit browsers on OS X abort momentum scrolls when the target 4464 // of the scroll event is removed from the scrollable element. 4465 // This hack (see related code in patchDisplay) makes sure the 4466 // element is kept around. 4467 if (dy && mac && webkit) { 4468 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { 4469 for (var i = 0; i < view.length; i++) { 4470 if (view[i].node == cur) { 4471 cm.display.currentWheelTarget = cur; 4472 break outer 4473 } 4474 } 4475 } 4476 } 4477 4478 // On some browsers, horizontal scrolling will cause redraws to 4479 // happen before the gutter has been realigned, causing it to 4480 // wriggle around in a most unseemly way. When we have an 4481 // estimated pixels/delta value, we just handle horizontal 4482 // scrolling entirely here. It'll be slightly off from native, but 4483 // better than glitching out. 4484 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { 4485 if (dy && canScrollY) 4486 { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } 4487 setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); 4488 // Only prevent default scrolling if vertical scrolling is 4489 // actually possible. Otherwise, it causes vertical scroll 4490 // jitter on OSX trackpads when deltaX is small and deltaY 4491 // is large (issue #3579) 4492 if (!dy || (dy && canScrollY)) 4493 { e_preventDefault(e); } 4494 display.wheelStartX = null; // Abort measurement, if in progress 4495 return 4496 } 4497 4498 // 'Project' the visible viewport to cover the area that is being 4499 // scrolled into view (if we know enough to estimate it). 4500 if (dy && wheelPixelsPerUnit != null) { 4501 var pixels = dy * wheelPixelsPerUnit; 4502 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 4503 if (pixels < 0) { top = Math.max(0, top + pixels - 50); } 4504 else { bot = Math.min(cm.doc.height, bot + pixels + 50); } 4505 updateDisplaySimple(cm, {top: top, bottom: bot}); 4506 } 4507 4508 if (wheelSamples < 20) { 4509 if (display.wheelStartX == null) { 4510 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 4511 display.wheelDX = dx; display.wheelDY = dy; 4512 setTimeout(function () { 4513 if (display.wheelStartX == null) { return } 4514 var movedX = scroll.scrollLeft - display.wheelStartX; 4515 var movedY = scroll.scrollTop - display.wheelStartY; 4516 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 4517 (movedX && display.wheelDX && movedX / display.wheelDX); 4518 display.wheelStartX = display.wheelStartY = null; 4519 if (!sample) { return } 4520 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 4521 ++wheelSamples; 4522 }, 200); 4523 } else { 4524 display.wheelDX += dx; display.wheelDY += dy; 4525 } 4526 } 4527 } 4528 4529 // Selection objects are immutable. A new one is created every time 4530 // the selection changes. A selection is one or more non-overlapping 4531 // (and non-touching) ranges, sorted, and an integer that indicates 4532 // which one is the primary selection (the one that's scrolled into 4533 // view, that getCursor returns, etc). 4534 var Selection = function(ranges, primIndex) { 4535 this.ranges = ranges; 4536 this.primIndex = primIndex; 4537 }; 4538 4539 Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; 4540 4541 Selection.prototype.equals = function (other) { 4542 var this$1 = this; 4543 4544 if (other == this) { return true } 4545 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } 4546 for (var i = 0; i < this.ranges.length; i++) { 4547 var here = this$1.ranges[i], there = other.ranges[i]; 4548 if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } 4549 } 4550 return true 4551 }; 4552 4553 Selection.prototype.deepCopy = function () { 4554 var this$1 = this; 4555 4556 var out = []; 4557 for (var i = 0; i < this.ranges.length; i++) 4558 { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } 4559 return new Selection(out, this.primIndex) 4560 }; 4561 4562 Selection.prototype.somethingSelected = function () { 4563 var this$1 = this; 4564 4565 for (var i = 0; i < this.ranges.length; i++) 4566 { if (!this$1.ranges[i].empty()) { return true } } 4567 return false 4568 }; 4569 4570 Selection.prototype.contains = function (pos, end) { 4571 var this$1 = this; 4572 4573 if (!end) { end = pos; } 4574 for (var i = 0; i < this.ranges.length; i++) { 4575 var range = this$1.ranges[i]; 4576 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) 4577 { return i } 4578 } 4579 return -1 4580 }; 4581 4582 var Range = function(anchor, head) { 4583 this.anchor = anchor; this.head = head; 4584 }; 4585 4586 Range.prototype.from = function () { return minPos(this.anchor, this.head) }; 4587 Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; 4588 Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; 4589 4590 // Take an unsorted, potentially overlapping set of ranges, and 4591 // build a selection out of it. 'Consumes' ranges array (modifying 4592 // it). 4593 function normalizeSelection(ranges, primIndex) { 4594 var prim = ranges[primIndex]; 4595 ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); 4596 primIndex = indexOf(ranges, prim); 4597 for (var i = 1; i < ranges.length; i++) { 4598 var cur = ranges[i], prev = ranges[i - 1]; 4599 if (cmp(prev.to(), cur.from()) >= 0) { 4600 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); 4601 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; 4602 if (i <= primIndex) { --primIndex; } 4603 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); 4604 } 4605 } 4606 return new Selection(ranges, primIndex) 4607 } 4608 4609 function simpleSelection(anchor, head) { 4610 return new Selection([new Range(anchor, head || anchor)], 0) 4611 } 4612 4613 // Compute the position of the end of a change (its 'to' property 4614 // refers to the pre-change end). 4615 function changeEnd(change) { 4616 if (!change.text) { return change.to } 4617 return Pos(change.from.line + change.text.length - 1, 4618 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) 4619 } 4620 4621 // Adjust a position to refer to the post-change position of the 4622 // same text, or the end of the change if the change covers it. 4623 function adjustForChange(pos, change) { 4624 if (cmp(pos, change.from) < 0) { return pos } 4625 if (cmp(pos, change.to) <= 0) { return changeEnd(change) } 4626 4627 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 4628 if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } 4629 return Pos(line, ch) 4630 } 4631 4632 function computeSelAfterChange(doc, change) { 4633 var out = []; 4634 for (var i = 0; i < doc.sel.ranges.length; i++) { 4635 var range = doc.sel.ranges[i]; 4636 out.push(new Range(adjustForChange(range.anchor, change), 4637 adjustForChange(range.head, change))); 4638 } 4639 return normalizeSelection(out, doc.sel.primIndex) 4640 } 4641 4642 function offsetPos(pos, old, nw) { 4643 if (pos.line == old.line) 4644 { return Pos(nw.line, pos.ch - old.ch + nw.ch) } 4645 else 4646 { return Pos(nw.line + (pos.line - old.line), pos.ch) } 4647 } 4648 4649 // Used by replaceSelections to allow moving the selection to the 4650 // start or around the replaced test. Hint may be "start" or "around". 4651 function computeReplacedSel(doc, changes, hint) { 4652 var out = []; 4653 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; 4654 for (var i = 0; i < changes.length; i++) { 4655 var change = changes[i]; 4656 var from = offsetPos(change.from, oldPrev, newPrev); 4657 var to = offsetPos(changeEnd(change), oldPrev, newPrev); 4658 oldPrev = change.to; 4659 newPrev = to; 4660 if (hint == "around") { 4661 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; 4662 out[i] = new Range(inv ? to : from, inv ? from : to); 4663 } else { 4664 out[i] = new Range(from, from); 4665 } 4666 } 4667 return new Selection(out, doc.sel.primIndex) 4668 } 4669 4670 // Used to get the editor into a consistent state again when options change. 4671 4672 function loadMode(cm) { 4673 cm.doc.mode = getMode(cm.options, cm.doc.modeOption); 4674 resetModeState(cm); 4675 } 4676 4677 function resetModeState(cm) { 4678 cm.doc.iter(function (line) { 4679 if (line.stateAfter) { line.stateAfter = null; } 4680 if (line.styles) { line.styles = null; } 4681 }); 4682 cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; 4683 startWorker(cm, 100); 4684 cm.state.modeGen++; 4685 if (cm.curOp) { regChange(cm); } 4686 } 4687 4688 // DOCUMENT DATA STRUCTURE 4689 4690 // By default, updates that start and end at the beginning of a line 4691 // are treated specially, in order to make the association of line 4692 // widgets and marker elements with the text behave more intuitive. 4693 function isWholeLineUpdate(doc, change) { 4694 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && 4695 (!doc.cm || doc.cm.options.wholeLineUpdateBefore) 4696 } 4697 4698 // Perform a change on the document data structure. 4699 function updateDoc(doc, change, markedSpans, estimateHeight$$1) { 4700 function spansFor(n) {return markedSpans ? markedSpans[n] : null} 4701 function update(line, text, spans) { 4702 updateLine(line, text, spans, estimateHeight$$1); 4703 signalLater(line, "change", line, change); 4704 } 4705 function linesFor(start, end) { 4706 var result = []; 4707 for (var i = start; i < end; ++i) 4708 { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } 4709 return result 4710 } 4711 4712 var from = change.from, to = change.to, text = change.text; 4713 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 4714 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 4715 4716 // Adjust the line structure 4717 if (change.full) { 4718 doc.insert(0, linesFor(0, text.length)); 4719 doc.remove(text.length, doc.size - text.length); 4720 } else if (isWholeLineUpdate(doc, change)) { 4721 // This is a whole-line replace. Treated specially to make 4722 // sure line objects move the way they are supposed to. 4723 var added = linesFor(0, text.length - 1); 4724 update(lastLine, lastLine.text, lastSpans); 4725 if (nlines) { doc.remove(from.line, nlines); } 4726 if (added.length) { doc.insert(from.line, added); } 4727 } else if (firstLine == lastLine) { 4728 if (text.length == 1) { 4729 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); 4730 } else { 4731 var added$1 = linesFor(1, text.length - 1); 4732 added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); 4733 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4734 doc.insert(from.line + 1, added$1); 4735 } 4736 } else if (text.length == 1) { 4737 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); 4738 doc.remove(from.line + 1, nlines); 4739 } else { 4740 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4741 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); 4742 var added$2 = linesFor(1, text.length - 1); 4743 if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } 4744 doc.insert(from.line + 1, added$2); 4745 } 4746 4747 signalLater(doc, "change", doc, change); 4748 } 4749 4750 // Call f for all linked documents. 4751 function linkedDocs(doc, f, sharedHistOnly) { 4752 function propagate(doc, skip, sharedHist) { 4753 if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { 4754 var rel = doc.linked[i]; 4755 if (rel.doc == skip) { continue } 4756 var shared = sharedHist && rel.sharedHist; 4757 if (sharedHistOnly && !shared) { continue } 4758 f(rel.doc, shared); 4759 propagate(rel.doc, doc, shared); 4760 } } 4761 } 4762 propagate(doc, null, true); 4763 } 4764 4765 // Attach a document to an editor. 4766 function attachDoc(cm, doc) { 4767 if (doc.cm) { throw new Error("This document is already in use.") } 4768 cm.doc = doc; 4769 doc.cm = cm; 4770 estimateLineHeights(cm); 4771 loadMode(cm); 4772 setDirectionClass(cm); 4773 if (!cm.options.lineWrapping) { findMaxLine(cm); } 4774 cm.options.mode = doc.modeOption; 4775 regChange(cm); 4776 } 4777 4778 function setDirectionClass(cm) { 4779 (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); 4780 } 4781 4782 function directionChanged(cm) { 4783 runInOp(cm, function () { 4784 setDirectionClass(cm); 4785 regChange(cm); 4786 }); 4787 } 4788 4789 function History(startGen) { 4790 // Arrays of change events and selections. Doing something adds an 4791 // event to done and clears undo. Undoing moves events from done 4792 // to undone, redoing moves them in the other direction. 4793 this.done = []; this.undone = []; 4794 this.undoDepth = Infinity; 4795 // Used to track when changes can be merged into a single undo 4796 // event 4797 this.lastModTime = this.lastSelTime = 0; 4798 this.lastOp = this.lastSelOp = null; 4799 this.lastOrigin = this.lastSelOrigin = null; 4800 // Used by the isClean() method 4801 this.generation = this.maxGeneration = startGen || 1; 4802 } 4803 4804 // Create a history change event from an updateDoc-style change 4805 // object. 4806 function historyChangeFromChange(doc, change) { 4807 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 4808 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 4809 linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); 4810 return histChange 4811 } 4812 4813 // Pop all selection events off the end of a history array. Stop at 4814 // a change event. 4815 function clearSelectionEvents(array) { 4816 while (array.length) { 4817 var last = lst(array); 4818 if (last.ranges) { array.pop(); } 4819 else { break } 4820 } 4821 } 4822 4823 // Find the top change event in the history. Pop off selection 4824 // events that are in the way. 4825 function lastChangeEvent(hist, force) { 4826 if (force) { 4827 clearSelectionEvents(hist.done); 4828 return lst(hist.done) 4829 } else if (hist.done.length && !lst(hist.done).ranges) { 4830 return lst(hist.done) 4831 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { 4832 hist.done.pop(); 4833 return lst(hist.done) 4834 } 4835 } 4836 4837 // Register a change in the history. Merges changes that are within 4838 // a single operation, or are close together with an origin that 4839 // allows merging (starting with "+") into a single event. 4840 function addChangeToHistory(doc, change, selAfter, opId) { 4841 var hist = doc.history; 4842 hist.undone.length = 0; 4843 var time = +new Date, cur; 4844 var last; 4845 4846 if ((hist.lastOp == opId || 4847 hist.lastOrigin == change.origin && change.origin && 4848 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || 4849 change.origin.charAt(0) == "*")) && 4850 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { 4851 // Merge this change into the last event 4852 last = lst(cur.changes); 4853 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { 4854 // Optimized case for simple insertion -- don't want to add 4855 // new changesets for every character typed 4856 last.to = changeEnd(change); 4857 } else { 4858 // Add new sub-event 4859 cur.changes.push(historyChangeFromChange(doc, change)); 4860 } 4861 } else { 4862 // Can not be merged, start a new event. 4863 var before = lst(hist.done); 4864 if (!before || !before.ranges) 4865 { pushSelectionToHistory(doc.sel, hist.done); } 4866 cur = {changes: [historyChangeFromChange(doc, change)], 4867 generation: hist.generation}; 4868 hist.done.push(cur); 4869 while (hist.done.length > hist.undoDepth) { 4870 hist.done.shift(); 4871 if (!hist.done[0].ranges) { hist.done.shift(); } 4872 } 4873 } 4874 hist.done.push(selAfter); 4875 hist.generation = ++hist.maxGeneration; 4876 hist.lastModTime = hist.lastSelTime = time; 4877 hist.lastOp = hist.lastSelOp = opId; 4878 hist.lastOrigin = hist.lastSelOrigin = change.origin; 4879 4880 if (!last) { signal(doc, "historyAdded"); } 4881 } 4882 4883 function selectionEventCanBeMerged(doc, origin, prev, sel) { 4884 var ch = origin.charAt(0); 4885 return ch == "*" || 4886 ch == "+" && 4887 prev.ranges.length == sel.ranges.length && 4888 prev.somethingSelected() == sel.somethingSelected() && 4889 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) 4890 } 4891 4892 // Called whenever the selection changes, sets the new selection as 4893 // the pending selection in the history, and pushes the old pending 4894 // selection into the 'done' array when it was significantly 4895 // different (in number of selected ranges, emptiness, or time). 4896 function addSelectionToHistory(doc, sel, opId, options) { 4897 var hist = doc.history, origin = options && options.origin; 4898 4899 // A new event is started when the previous origin does not match 4900 // the current, or the origins don't allow matching. Origins 4901 // starting with * are always merged, those starting with + are 4902 // merged when similar and close together in time. 4903 if (opId == hist.lastSelOp || 4904 (origin && hist.lastSelOrigin == origin && 4905 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || 4906 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) 4907 { hist.done[hist.done.length - 1] = sel; } 4908 else 4909 { pushSelectionToHistory(sel, hist.done); } 4910 4911 hist.lastSelTime = +new Date; 4912 hist.lastSelOrigin = origin; 4913 hist.lastSelOp = opId; 4914 if (options && options.clearRedo !== false) 4915 { clearSelectionEvents(hist.undone); } 4916 } 4917 4918 function pushSelectionToHistory(sel, dest) { 4919 var top = lst(dest); 4920 if (!(top && top.ranges && top.equals(sel))) 4921 { dest.push(sel); } 4922 } 4923 4924 // Used to store marked span information in the history. 4925 function attachLocalSpans(doc, change, from, to) { 4926 var existing = change["spans_" + doc.id], n = 0; 4927 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { 4928 if (line.markedSpans) 4929 { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } 4930 ++n; 4931 }); 4932 } 4933 4934 // When un/re-doing restores text containing marked spans, those 4935 // that have been explicitly cleared should not be restored. 4936 function removeClearedSpans(spans) { 4937 if (!spans) { return null } 4938 var out; 4939 for (var i = 0; i < spans.length; ++i) { 4940 if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } 4941 else if (out) { out.push(spans[i]); } 4942 } 4943 return !out ? spans : out.length ? out : null 4944 } 4945 4946 // Retrieve and filter the old marked spans stored in a change event. 4947 function getOldSpans(doc, change) { 4948 var found = change["spans_" + doc.id]; 4949 if (!found) { return null } 4950 var nw = []; 4951 for (var i = 0; i < change.text.length; ++i) 4952 { nw.push(removeClearedSpans(found[i])); } 4953 return nw 4954 } 4955 4956 // Used for un/re-doing changes from the history. Combines the 4957 // result of computing the existing spans with the set of spans that 4958 // existed in the history (so that deleting around a span and then 4959 // undoing brings back the span). 4960 function mergeOldSpans(doc, change) { 4961 var old = getOldSpans(doc, change); 4962 var stretched = stretchSpansOverChange(doc, change); 4963 if (!old) { return stretched } 4964 if (!stretched) { return old } 4965 4966 for (var i = 0; i < old.length; ++i) { 4967 var oldCur = old[i], stretchCur = stretched[i]; 4968 if (oldCur && stretchCur) { 4969 spans: for (var j = 0; j < stretchCur.length; ++j) { 4970 var span = stretchCur[j]; 4971 for (var k = 0; k < oldCur.length; ++k) 4972 { if (oldCur[k].marker == span.marker) { continue spans } } 4973 oldCur.push(span); 4974 } 4975 } else if (stretchCur) { 4976 old[i] = stretchCur; 4977 } 4978 } 4979 return old 4980 } 4981 4982 // Used both to provide a JSON-safe object in .getHistory, and, when 4983 // detaching a document, to split the history in two 4984 function copyHistoryArray(events, newGroup, instantiateSel) { 4985 var copy = []; 4986 for (var i = 0; i < events.length; ++i) { 4987 var event = events[i]; 4988 if (event.ranges) { 4989 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); 4990 continue 4991 } 4992 var changes = event.changes, newChanges = []; 4993 copy.push({changes: newChanges}); 4994 for (var j = 0; j < changes.length; ++j) { 4995 var change = changes[j], m = (void 0); 4996 newChanges.push({from: change.from, to: change.to, text: change.text}); 4997 if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { 4998 if (indexOf(newGroup, Number(m[1])) > -1) { 4999 lst(newChanges)[prop] = change[prop]; 5000 delete change[prop]; 5001 } 5002 } } } 5003 } 5004 } 5005 return copy 5006 } 5007 5008 // The 'scroll' parameter given to many of these indicated whether 5009 // the new cursor position should be scrolled into view after 5010 // modifying the selection. 5011 5012 // If shift is held or the extend flag is set, extends a range to 5013 // include a given position (and optionally a second position). 5014 // Otherwise, simply returns the range between the given positions. 5015 // Used for cursor motion and such. 5016 function extendRange(range, head, other, extend) { 5017 if (extend) { 5018 var anchor = range.anchor; 5019 if (other) { 5020 var posBefore = cmp(head, anchor) < 0; 5021 if (posBefore != (cmp(other, anchor) < 0)) { 5022 anchor = head; 5023 head = other; 5024 } else if (posBefore != (cmp(head, other) < 0)) { 5025 head = other; 5026 } 5027 } 5028 return new Range(anchor, head) 5029 } else { 5030 return new Range(other || head, head) 5031 } 5032 } 5033 5034 // Extend the primary selection range, discard the rest. 5035 function extendSelection(doc, head, other, options, extend) { 5036 if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } 5037 setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); 5038 } 5039 5040 // Extend all selections (pos is an array of selections with length 5041 // equal the number of selections) 5042 function extendSelections(doc, heads, options) { 5043 var out = []; 5044 var extend = doc.cm && (doc.cm.display.shift || doc.extend); 5045 for (var i = 0; i < doc.sel.ranges.length; i++) 5046 { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } 5047 var newSel = normalizeSelection(out, doc.sel.primIndex); 5048 setSelection(doc, newSel, options); 5049 } 5050 5051 // Updates a single range in the selection. 5052 function replaceOneSelection(doc, i, range, options) { 5053 var ranges = doc.sel.ranges.slice(0); 5054 ranges[i] = range; 5055 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); 5056 } 5057 5058 // Reset the selection to a single range. 5059 function setSimpleSelection(doc, anchor, head, options) { 5060 setSelection(doc, simpleSelection(anchor, head), options); 5061 } 5062 5063 // Give beforeSelectionChange handlers a change to influence a 5064 // selection update. 5065 function filterSelectionChange(doc, sel, options) { 5066 var obj = { 5067 ranges: sel.ranges, 5068 update: function(ranges) { 5069 var this$1 = this; 5070 5071 this.ranges = []; 5072 for (var i = 0; i < ranges.length; i++) 5073 { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), 5074 clipPos(doc, ranges[i].head)); } 5075 }, 5076 origin: options && options.origin 5077 }; 5078 signal(doc, "beforeSelectionChange", doc, obj); 5079 if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } 5080 if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } 5081 else { return sel } 5082 } 5083 5084 function setSelectionReplaceHistory(doc, sel, options) { 5085 var done = doc.history.done, last = lst(done); 5086 if (last && last.ranges) { 5087 done[done.length - 1] = sel; 5088 setSelectionNoUndo(doc, sel, options); 5089 } else { 5090 setSelection(doc, sel, options); 5091 } 5092 } 5093 5094 // Set a new selection. 5095 function setSelection(doc, sel, options) { 5096 setSelectionNoUndo(doc, sel, options); 5097 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); 5098 } 5099 5100 function setSelectionNoUndo(doc, sel, options) { 5101 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) 5102 { sel = filterSelectionChange(doc, sel, options); } 5103 5104 var bias = options && options.bias || 5105 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); 5106 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); 5107 5108 if (!(options && options.scroll === false) && doc.cm) 5109 { ensureCursorVisible(doc.cm); } 5110 } 5111 5112 function setSelectionInner(doc, sel) { 5113 if (sel.equals(doc.sel)) { return } 5114 5115 doc.sel = sel; 5116 5117 if (doc.cm) { 5118 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 5119 signalCursorActivity(doc.cm); 5120 } 5121 signalLater(doc, "cursorActivity", doc); 5122 } 5123 5124 // Verify that the selection does not partially select any atomic 5125 // marked ranges. 5126 function reCheckSelection(doc) { 5127 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); 5128 } 5129 5130 // Return a selection that does not partially select any atomic 5131 // ranges. 5132 function skipAtomicInSelection(doc, sel, bias, mayClear) { 5133 var out; 5134 for (var i = 0; i < sel.ranges.length; i++) { 5135 var range = sel.ranges[i]; 5136 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; 5137 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); 5138 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); 5139 if (out || newAnchor != range.anchor || newHead != range.head) { 5140 if (!out) { out = sel.ranges.slice(0, i); } 5141 out[i] = new Range(newAnchor, newHead); 5142 } 5143 } 5144 return out ? normalizeSelection(out, sel.primIndex) : sel 5145 } 5146 5147 function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { 5148 var line = getLine(doc, pos.line); 5149 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 5150 var sp = line.markedSpans[i], m = sp.marker; 5151 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && 5152 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { 5153 if (mayClear) { 5154 signal(m, "beforeCursorEnter"); 5155 if (m.explicitlyCleared) { 5156 if (!line.markedSpans) { break } 5157 else {--i; continue} 5158 } 5159 } 5160 if (!m.atomic) { continue } 5161 5162 if (oldPos) { 5163 var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); 5164 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) 5165 { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } 5166 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) 5167 { return skipAtomicInner(doc, near, pos, dir, mayClear) } 5168 } 5169 5170 var far = m.find(dir < 0 ? -1 : 1); 5171 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) 5172 { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } 5173 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null 5174 } 5175 } } 5176 return pos 5177 } 5178 5179 // Ensure a given position is not inside an atomic range. 5180 function skipAtomic(doc, pos, oldPos, bias, mayClear) { 5181 var dir = bias || 1; 5182 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || 5183 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || 5184 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || 5185 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); 5186 if (!found) { 5187 doc.cantEdit = true; 5188 return Pos(doc.first, 0) 5189 } 5190 return found 5191 } 5192 5193 function movePos(doc, pos, dir, line) { 5194 if (dir < 0 && pos.ch == 0) { 5195 if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } 5196 else { return null } 5197 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { 5198 if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } 5199 else { return null } 5200 } else { 5201 return new Pos(pos.line, pos.ch + dir) 5202 } 5203 } 5204 5205 function selectAll(cm) { 5206 cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); 5207 } 5208 5209 // UPDATING 5210 5211 // Allow "beforeChange" event handlers to influence a change 5212 function filterChange(doc, change, update) { 5213 var obj = { 5214 canceled: false, 5215 from: change.from, 5216 to: change.to, 5217 text: change.text, 5218 origin: change.origin, 5219 cancel: function () { return obj.canceled = true; } 5220 }; 5221 if (update) { obj.update = function (from, to, text, origin) { 5222 if (from) { obj.from = clipPos(doc, from); } 5223 if (to) { obj.to = clipPos(doc, to); } 5224 if (text) { obj.text = text; } 5225 if (origin !== undefined) { obj.origin = origin; } 5226 }; } 5227 signal(doc, "beforeChange", doc, obj); 5228 if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } 5229 5230 if (obj.canceled) { return null } 5231 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} 5232 } 5233 5234 // Apply a change to a document, and add it to the document's 5235 // history, and propagating it to all linked documents. 5236 function makeChange(doc, change, ignoreReadOnly) { 5237 if (doc.cm) { 5238 if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } 5239 if (doc.cm.state.suppressEdits) { return } 5240 } 5241 5242 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 5243 change = filterChange(doc, change, true); 5244 if (!change) { return } 5245 } 5246 5247 // Possibly split or suppress the update based on the presence 5248 // of read-only spans in its range. 5249 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 5250 if (split) { 5251 for (var i = split.length - 1; i >= 0; --i) 5252 { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } 5253 } else { 5254 makeChangeInner(doc, change); 5255 } 5256 } 5257 5258 function makeChangeInner(doc, change) { 5259 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } 5260 var selAfter = computeSelAfterChange(doc, change); 5261 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 5262 5263 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 5264 var rebased = []; 5265 5266 linkedDocs(doc, function (doc, sharedHist) { 5267 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5268 rebaseHist(doc.history, change); 5269 rebased.push(doc.history); 5270 } 5271 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 5272 }); 5273 } 5274 5275 // Revert a change stored in a document's history. 5276 function makeChangeFromHistory(doc, type, allowSelectionOnly) { 5277 if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } 5278 5279 var hist = doc.history, event, selAfter = doc.sel; 5280 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; 5281 5282 // Verify that there is a useable event (so that ctrl-z won't 5283 // needlessly clear selection events) 5284 var i = 0; 5285 for (; i < source.length; i++) { 5286 event = source[i]; 5287 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) 5288 { break } 5289 } 5290 if (i == source.length) { return } 5291 hist.lastOrigin = hist.lastSelOrigin = null; 5292 5293 for (;;) { 5294 event = source.pop(); 5295 if (event.ranges) { 5296 pushSelectionToHistory(event, dest); 5297 if (allowSelectionOnly && !event.equals(doc.sel)) { 5298 setSelection(doc, event, {clearRedo: false}); 5299 return 5300 } 5301 selAfter = event; 5302 } 5303 else { break } 5304 } 5305 5306 // Build up a reverse change object to add to the opposite history 5307 // stack (redo when undoing, and vice versa). 5308 var antiChanges = []; 5309 pushSelectionToHistory(selAfter, dest); 5310 dest.push({changes: antiChanges, generation: hist.generation}); 5311 hist.generation = event.generation || ++hist.maxGeneration; 5312 5313 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); 5314 5315 var loop = function ( i ) { 5316 var change = event.changes[i]; 5317 change.origin = type; 5318 if (filter && !filterChange(doc, change, false)) { 5319 source.length = 0; 5320 return {} 5321 } 5322 5323 antiChanges.push(historyChangeFromChange(doc, change)); 5324 5325 var after = i ? computeSelAfterChange(doc, change) : lst(source); 5326 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 5327 if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } 5328 var rebased = []; 5329 5330 // Propagate to the linked documents 5331 linkedDocs(doc, function (doc, sharedHist) { 5332 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5333 rebaseHist(doc.history, change); 5334 rebased.push(doc.history); 5335 } 5336 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 5337 }); 5338 }; 5339 5340 for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { 5341 var returned = loop( i$1 ); 5342 5343 if ( returned ) return returned.v; 5344 } 5345 } 5346 5347 // Sub-views need their line numbers shifted when text is added 5348 // above or below them in the parent document. 5349 function shiftDoc(doc, distance) { 5350 if (distance == 0) { return } 5351 doc.first += distance; 5352 doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( 5353 Pos(range.anchor.line + distance, range.anchor.ch), 5354 Pos(range.head.line + distance, range.head.ch) 5355 ); }), doc.sel.primIndex); 5356 if (doc.cm) { 5357 regChange(doc.cm, doc.first, doc.first - distance, distance); 5358 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) 5359 { regLineChange(doc.cm, l, "gutter"); } 5360 } 5361 } 5362 5363 // More lower-level change function, handling only a single document 5364 // (not linked ones). 5365 function makeChangeSingleDoc(doc, change, selAfter, spans) { 5366 if (doc.cm && !doc.cm.curOp) 5367 { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } 5368 5369 if (change.to.line < doc.first) { 5370 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 5371 return 5372 } 5373 if (change.from.line > doc.lastLine()) { return } 5374 5375 // Clip the change to the size of this doc 5376 if (change.from.line < doc.first) { 5377 var shift = change.text.length - 1 - (doc.first - change.from.line); 5378 shiftDoc(doc, shift); 5379 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 5380 text: [lst(change.text)], origin: change.origin}; 5381 } 5382 var last = doc.lastLine(); 5383 if (change.to.line > last) { 5384 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 5385 text: [change.text[0]], origin: change.origin}; 5386 } 5387 5388 change.removed = getBetween(doc, change.from, change.to); 5389 5390 if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } 5391 if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } 5392 else { updateDoc(doc, change, spans); } 5393 setSelectionNoUndo(doc, selAfter, sel_dontScroll); 5394 } 5395 5396 // Handle the interaction of a change to a document with the editor 5397 // that this document is part of. 5398 function makeChangeSingleDocInEditor(cm, change, spans) { 5399 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 5400 5401 var recomputeMaxLength = false, checkWidthStart = from.line; 5402 if (!cm.options.lineWrapping) { 5403 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); 5404 doc.iter(checkWidthStart, to.line + 1, function (line) { 5405 if (line == display.maxLine) { 5406 recomputeMaxLength = true; 5407 return true 5408 } 5409 }); 5410 } 5411 5412 if (doc.sel.contains(change.from, change.to) > -1) 5413 { signalCursorActivity(cm); } 5414 5415 updateDoc(doc, change, spans, estimateHeight(cm)); 5416 5417 if (!cm.options.lineWrapping) { 5418 doc.iter(checkWidthStart, from.line + change.text.length, function (line) { 5419 var len = lineLength(line); 5420 if (len > display.maxLineLength) { 5421 display.maxLine = line; 5422 display.maxLineLength = len; 5423 display.maxLineChanged = true; 5424 recomputeMaxLength = false; 5425 } 5426 }); 5427 if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } 5428 } 5429 5430 retreatFrontier(doc, from.line); 5431 startWorker(cm, 400); 5432 5433 var lendiff = change.text.length - (to.line - from.line) - 1; 5434 // Remember that these lines changed, for updating the display 5435 if (change.full) 5436 { regChange(cm); } 5437 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) 5438 { regLineChange(cm, from.line, "text"); } 5439 else 5440 { regChange(cm, from.line, to.line + 1, lendiff); } 5441 5442 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); 5443 if (changeHandler || changesHandler) { 5444 var obj = { 5445 from: from, to: to, 5446 text: change.text, 5447 removed: change.removed, 5448 origin: change.origin 5449 }; 5450 if (changeHandler) { signalLater(cm, "change", cm, obj); } 5451 if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } 5452 } 5453 cm.display.selForContextMenu = null; 5454 } 5455 5456 function replaceRange(doc, code, from, to, origin) { 5457 if (!to) { to = from; } 5458 if (cmp(to, from) < 0) { var assign; 5459 (assign = [to, from], from = assign[0], to = assign[1], assign); } 5460 if (typeof code == "string") { code = doc.splitLines(code); } 5461 makeChange(doc, {from: from, to: to, text: code, origin: origin}); 5462 } 5463 5464 // Rebasing/resetting history to deal with externally-sourced changes 5465 5466 function rebaseHistSelSingle(pos, from, to, diff) { 5467 if (to < pos.line) { 5468 pos.line += diff; 5469 } else if (from < pos.line) { 5470 pos.line = from; 5471 pos.ch = 0; 5472 } 5473 } 5474 5475 // Tries to rebase an array of history events given a change in the 5476 // document. If the change touches the same lines as the event, the 5477 // event, and everything 'behind' it, is discarded. If the change is 5478 // before the event, the event's positions are updated. Uses a 5479 // copy-on-write scheme for the positions, to avoid having to 5480 // reallocate them all on every rebase, but also avoid problems with 5481 // shared position objects being unsafely updated. 5482 function rebaseHistArray(array, from, to, diff) { 5483 for (var i = 0; i < array.length; ++i) { 5484 var sub = array[i], ok = true; 5485 if (sub.ranges) { 5486 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } 5487 for (var j = 0; j < sub.ranges.length; j++) { 5488 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); 5489 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); 5490 } 5491 continue 5492 } 5493 for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { 5494 var cur = sub.changes[j$1]; 5495 if (to < cur.from.line) { 5496 cur.from = Pos(cur.from.line + diff, cur.from.ch); 5497 cur.to = Pos(cur.to.line + diff, cur.to.ch); 5498 } else if (from <= cur.to.line) { 5499 ok = false; 5500 break 5501 } 5502 } 5503 if (!ok) { 5504 array.splice(0, i + 1); 5505 i = 0; 5506 } 5507 } 5508 } 5509 5510 function rebaseHist(hist, change) { 5511 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 5512 rebaseHistArray(hist.done, from, to, diff); 5513 rebaseHistArray(hist.undone, from, to, diff); 5514 } 5515 5516 // Utility for applying a change to a line by handle or number, 5517 // returning the number and optionally registering the line as 5518 // changed. 5519 function changeLine(doc, handle, changeType, op) { 5520 var no = handle, line = handle; 5521 if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } 5522 else { no = lineNo(handle); } 5523 if (no == null) { return null } 5524 if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } 5525 return line 5526 } 5527 5528 // The document is represented as a BTree consisting of leaves, with 5529 // chunk of lines in them, and branches, with up to ten leaves or 5530 // other branch nodes below them. The top node is always a branch 5531 // node, and is the document object itself (meaning it has 5532 // additional methods and properties). 5533 // 5534 // All nodes have parent links. The tree is used both to go from 5535 // line numbers to line objects, and to go from objects to numbers. 5536 // It also indexes by height, and is used to convert between height 5537 // and line object, and to find the total height of the document. 5538 // 5539 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html 5540 5541 function LeafChunk(lines) { 5542 var this$1 = this; 5543 5544 this.lines = lines; 5545 this.parent = null; 5546 var height = 0; 5547 for (var i = 0; i < lines.length; ++i) { 5548 lines[i].parent = this$1; 5549 height += lines[i].height; 5550 } 5551 this.height = height; 5552 } 5553 5554 LeafChunk.prototype = { 5555 chunkSize: function chunkSize() { return this.lines.length }, 5556 5557 // Remove the n lines at offset 'at'. 5558 removeInner: function removeInner(at, n) { 5559 var this$1 = this; 5560 5561 for (var i = at, e = at + n; i < e; ++i) { 5562 var line = this$1.lines[i]; 5563 this$1.height -= line.height; 5564 cleanUpLine(line); 5565 signalLater(line, "delete"); 5566 } 5567 this.lines.splice(at, n); 5568 }, 5569 5570 // Helper used to collapse a small branch into a single leaf. 5571 collapse: function collapse(lines) { 5572 lines.push.apply(lines, this.lines); 5573 }, 5574 5575 // Insert the given array of lines at offset 'at', count them as 5576 // having the given height. 5577 insertInner: function insertInner(at, lines, height) { 5578 var this$1 = this; 5579 5580 this.height += height; 5581 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 5582 for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } 5583 }, 5584 5585 // Used to iterate over a part of the tree. 5586 iterN: function iterN(at, n, op) { 5587 var this$1 = this; 5588 5589 for (var e = at + n; at < e; ++at) 5590 { if (op(this$1.lines[at])) { return true } } 5591 } 5592 }; 5593 5594 function BranchChunk(children) { 5595 var this$1 = this; 5596 5597 this.children = children; 5598 var size = 0, height = 0; 5599 for (var i = 0; i < children.length; ++i) { 5600 var ch = children[i]; 5601 size += ch.chunkSize(); height += ch.height; 5602 ch.parent = this$1; 5603 } 5604 this.size = size; 5605 this.height = height; 5606 this.parent = null; 5607 } 5608 5609 BranchChunk.prototype = { 5610 chunkSize: function chunkSize() { return this.size }, 5611 5612 removeInner: function removeInner(at, n) { 5613 var this$1 = this; 5614 5615 this.size -= n; 5616 for (var i = 0; i < this.children.length; ++i) { 5617 var child = this$1.children[i], sz = child.chunkSize(); 5618 if (at < sz) { 5619 var rm = Math.min(n, sz - at), oldHeight = child.height; 5620 child.removeInner(at, rm); 5621 this$1.height -= oldHeight - child.height; 5622 if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } 5623 if ((n -= rm) == 0) { break } 5624 at = 0; 5625 } else { at -= sz; } 5626 } 5627 // If the result is smaller than 25 lines, ensure that it is a 5628 // single leaf node. 5629 if (this.size - n < 25 && 5630 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { 5631 var lines = []; 5632 this.collapse(lines); 5633 this.children = [new LeafChunk(lines)]; 5634 this.children[0].parent = this; 5635 } 5636 }, 5637 5638 collapse: function collapse(lines) { 5639 var this$1 = this; 5640 5641 for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } 5642 }, 5643 5644 insertInner: function insertInner(at, lines, height) { 5645 var this$1 = this; 5646 5647 this.size += lines.length; 5648 this.height += height; 5649 for (var i = 0; i < this.children.length; ++i) { 5650 var child = this$1.children[i], sz = child.chunkSize(); 5651 if (at <= sz) { 5652 child.insertInner(at, lines, height); 5653 if (child.lines && child.lines.length > 50) { 5654 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. 5655 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. 5656 var remaining = child.lines.length % 25 + 25; 5657 for (var pos = remaining; pos < child.lines.length;) { 5658 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); 5659 child.height -= leaf.height; 5660 this$1.children.splice(++i, 0, leaf); 5661 leaf.parent = this$1; 5662 } 5663 child.lines = child.lines.slice(0, remaining); 5664 this$1.maybeSpill(); 5665 } 5666 break 5667 } 5668 at -= sz; 5669 } 5670 }, 5671 5672 // When a node has grown, check whether it should be split. 5673 maybeSpill: function maybeSpill() { 5674 if (this.children.length <= 10) { return } 5675 var me = this; 5676 do { 5677 var spilled = me.children.splice(me.children.length - 5, 5); 5678 var sibling = new BranchChunk(spilled); 5679 if (!me.parent) { // Become the parent node 5680 var copy = new BranchChunk(me.children); 5681 copy.parent = me; 5682 me.children = [copy, sibling]; 5683 me = copy; 5684 } else { 5685 me.size -= sibling.size; 5686 me.height -= sibling.height; 5687 var myIndex = indexOf(me.parent.children, me); 5688 me.parent.children.splice(myIndex + 1, 0, sibling); 5689 } 5690 sibling.parent = me.parent; 5691 } while (me.children.length > 10) 5692 me.parent.maybeSpill(); 5693 }, 5694 5695 iterN: function iterN(at, n, op) { 5696 var this$1 = this; 5697 5698 for (var i = 0; i < this.children.length; ++i) { 5699 var child = this$1.children[i], sz = child.chunkSize(); 5700 if (at < sz) { 5701 var used = Math.min(n, sz - at); 5702 if (child.iterN(at, used, op)) { return true } 5703 if ((n -= used) == 0) { break } 5704 at = 0; 5705 } else { at -= sz; } 5706 } 5707 } 5708 }; 5709 5710 // Line widgets are block elements displayed above or below a line. 5711 5712 var LineWidget = function(doc, node, options) { 5713 var this$1 = this; 5714 5715 if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) 5716 { this$1[opt] = options[opt]; } } } 5717 this.doc = doc; 5718 this.node = node; 5719 }; 5720 5721 LineWidget.prototype.clear = function () { 5722 var this$1 = this; 5723 5724 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); 5725 if (no == null || !ws) { return } 5726 for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } 5727 if (!ws.length) { line.widgets = null; } 5728 var height = widgetHeight(this); 5729 updateLineHeight(line, Math.max(0, line.height - height)); 5730 if (cm) { 5731 runInOp(cm, function () { 5732 adjustScrollWhenAboveVisible(cm, line, -height); 5733 regLineChange(cm, no, "widget"); 5734 }); 5735 signalLater(cm, "lineWidgetCleared", cm, this, no); 5736 } 5737 }; 5738 5739 LineWidget.prototype.changed = function () { 5740 var this$1 = this; 5741 5742 var oldH = this.height, cm = this.doc.cm, line = this.line; 5743 this.height = null; 5744 var diff = widgetHeight(this) - oldH; 5745 if (!diff) { return } 5746 updateLineHeight(line, line.height + diff); 5747 if (cm) { 5748 runInOp(cm, function () { 5749 cm.curOp.forceUpdate = true; 5750 adjustScrollWhenAboveVisible(cm, line, diff); 5751 signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); 5752 }); 5753 } 5754 }; 5755 eventMixin(LineWidget); 5756 5757 function adjustScrollWhenAboveVisible(cm, line, diff) { 5758 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) 5759 { addToScrollTop(cm, diff); } 5760 } 5761 5762 function addLineWidget(doc, handle, node, options) { 5763 var widget = new LineWidget(doc, node, options); 5764 var cm = doc.cm; 5765 if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } 5766 changeLine(doc, handle, "widget", function (line) { 5767 var widgets = line.widgets || (line.widgets = []); 5768 if (widget.insertAt == null) { widgets.push(widget); } 5769 else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } 5770 widget.line = line; 5771 if (cm && !lineIsHidden(doc, line)) { 5772 var aboveVisible = heightAtLine(line) < doc.scrollTop; 5773 updateLineHeight(line, line.height + widgetHeight(widget)); 5774 if (aboveVisible) { addToScrollTop(cm, widget.height); } 5775 cm.curOp.forceUpdate = true; 5776 } 5777 return true 5778 }); 5779 signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); 5780 return widget 5781 } 5782 5783 // TEXTMARKERS 5784 5785 // Created with markText and setBookmark methods. A TextMarker is a 5786 // handle that can be used to clear or find a marked position in the 5787 // document. Line objects hold arrays (markedSpans) containing 5788 // {from, to, marker} object pointing to such marker objects, and 5789 // indicating that such a marker is present on that line. Multiple 5790 // lines may point to the same marker when it spans across lines. 5791 // The spans will have null for their from/to properties when the 5792 // marker continues beyond the start/end of the line. Markers have 5793 // links back to the lines they currently touch. 5794 5795 // Collapsed markers have unique ids, in order to be able to order 5796 // them, which is needed for uniquely determining an outer marker 5797 // when they overlap (they may nest, but not partially overlap). 5798 var nextMarkerId = 0; 5799 5800 var TextMarker = function(doc, type) { 5801 this.lines = []; 5802 this.type = type; 5803 this.doc = doc; 5804 this.id = ++nextMarkerId; 5805 }; 5806 5807 // Clear the marker. 5808 TextMarker.prototype.clear = function () { 5809 var this$1 = this; 5810 5811 if (this.explicitlyCleared) { return } 5812 var cm = this.doc.cm, withOp = cm && !cm.curOp; 5813 if (withOp) { startOperation(cm); } 5814 if (hasHandler(this, "clear")) { 5815 var found = this.find(); 5816 if (found) { signalLater(this, "clear", found.from, found.to); } 5817 } 5818 var min = null, max = null; 5819 for (var i = 0; i < this.lines.length; ++i) { 5820 var line = this$1.lines[i]; 5821 var span = getMarkedSpanFor(line.markedSpans, this$1); 5822 if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } 5823 else if (cm) { 5824 if (span.to != null) { max = lineNo(line); } 5825 if (span.from != null) { min = lineNo(line); } 5826 } 5827 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 5828 if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) 5829 { updateLineHeight(line, textHeight(cm.display)); } 5830 } 5831 if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { 5832 var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); 5833 if (len > cm.display.maxLineLength) { 5834 cm.display.maxLine = visual; 5835 cm.display.maxLineLength = len; 5836 cm.display.maxLineChanged = true; 5837 } 5838 } } 5839 5840 if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } 5841 this.lines.length = 0; 5842 this.explicitlyCleared = true; 5843 if (this.atomic && this.doc.cantEdit) { 5844 this.doc.cantEdit = false; 5845 if (cm) { reCheckSelection(cm.doc); } 5846 } 5847 if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } 5848 if (withOp) { endOperation(cm); } 5849 if (this.parent) { this.parent.clear(); } 5850 }; 5851 5852 // Find the position of the marker in the document. Returns a {from, 5853 // to} object by default. Side can be passed to get a specific side 5854 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the 5855 // Pos objects returned contain a line object, rather than a line 5856 // number (used to prevent looking up the same line twice). 5857 TextMarker.prototype.find = function (side, lineObj) { 5858 var this$1 = this; 5859 5860 if (side == null && this.type == "bookmark") { side = 1; } 5861 var from, to; 5862 for (var i = 0; i < this.lines.length; ++i) { 5863 var line = this$1.lines[i]; 5864 var span = getMarkedSpanFor(line.markedSpans, this$1); 5865 if (span.from != null) { 5866 from = Pos(lineObj ? line : lineNo(line), span.from); 5867 if (side == -1) { return from } 5868 } 5869 if (span.to != null) { 5870 to = Pos(lineObj ? line : lineNo(line), span.to); 5871 if (side == 1) { return to } 5872 } 5873 } 5874 return from && {from: from, to: to} 5875 }; 5876 5877 // Signals that the marker's widget changed, and surrounding layout 5878 // should be recomputed. 5879 TextMarker.prototype.changed = function () { 5880 var this$1 = this; 5881 5882 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; 5883 if (!pos || !cm) { return } 5884 runInOp(cm, function () { 5885 var line = pos.line, lineN = lineNo(pos.line); 5886 var view = findViewForLine(cm, lineN); 5887 if (view) { 5888 clearLineMeasurementCacheFor(view); 5889 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; 5890 } 5891 cm.curOp.updateMaxLine = true; 5892 if (!lineIsHidden(widget.doc, line) && widget.height != null) { 5893 var oldHeight = widget.height; 5894 widget.height = null; 5895 var dHeight = widgetHeight(widget) - oldHeight; 5896 if (dHeight) 5897 { updateLineHeight(line, line.height + dHeight); } 5898 } 5899 signalLater(cm, "markerChanged", cm, this$1); 5900 }); 5901 }; 5902 5903 TextMarker.prototype.attachLine = function (line) { 5904 if (!this.lines.length && this.doc.cm) { 5905 var op = this.doc.cm.curOp; 5906 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 5907 { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } 5908 } 5909 this.lines.push(line); 5910 }; 5911 5912 TextMarker.prototype.detachLine = function (line) { 5913 this.lines.splice(indexOf(this.lines, line), 1); 5914 if (!this.lines.length && this.doc.cm) { 5915 var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 5916 } 5917 }; 5918 eventMixin(TextMarker); 5919 5920 // Create a marker, wire it up to the right lines, and 5921 function markText(doc, from, to, options, type) { 5922 // Shared markers (across linked documents) are handled separately 5923 // (markTextShared will call out to this again, once per 5924 // document). 5925 if (options && options.shared) { return markTextShared(doc, from, to, options, type) } 5926 // Ensure we are in an operation. 5927 if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } 5928 5929 var marker = new TextMarker(doc, type), diff = cmp(from, to); 5930 if (options) { copyObj(options, marker, false); } 5931 // Don't connect empty markers unless clearWhenEmpty is false 5932 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) 5933 { return marker } 5934 if (marker.replacedWith) { 5935 // Showing up as a widget implies collapsed (widget replaces text) 5936 marker.collapsed = true; 5937 marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); 5938 if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } 5939 if (options.insertLeft) { marker.widgetNode.insertLeft = true; } 5940 } 5941 if (marker.collapsed) { 5942 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || 5943 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) 5944 { throw new Error("Inserting collapsed marker partially overlapping an existing one") } 5945 seeCollapsedSpans(); 5946 } 5947 5948 if (marker.addToHistory) 5949 { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } 5950 5951 var curLine = from.line, cm = doc.cm, updateMaxLine; 5952 doc.iter(curLine, to.line + 1, function (line) { 5953 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) 5954 { updateMaxLine = true; } 5955 if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } 5956 addMarkedSpan(line, new MarkedSpan(marker, 5957 curLine == from.line ? from.ch : null, 5958 curLine == to.line ? to.ch : null)); 5959 ++curLine; 5960 }); 5961 // lineIsHidden depends on the presence of the spans, so needs a second pass 5962 if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { 5963 if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } 5964 }); } 5965 5966 if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } 5967 5968 if (marker.readOnly) { 5969 seeReadOnlySpans(); 5970 if (doc.history.done.length || doc.history.undone.length) 5971 { doc.clearHistory(); } 5972 } 5973 if (marker.collapsed) { 5974 marker.id = ++nextMarkerId; 5975 marker.atomic = true; 5976 } 5977 if (cm) { 5978 // Sync editor state 5979 if (updateMaxLine) { cm.curOp.updateMaxLine = true; } 5980 if (marker.collapsed) 5981 { regChange(cm, from.line, to.line + 1); } 5982 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) 5983 { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } 5984 if (marker.atomic) { reCheckSelection(cm.doc); } 5985 signalLater(cm, "markerAdded", cm, marker); 5986 } 5987 return marker 5988 } 5989 5990 // SHARED TEXTMARKERS 5991 5992 // A shared marker spans multiple linked documents. It is 5993 // implemented as a meta-marker-object controlling multiple normal 5994 // markers. 5995 var SharedTextMarker = function(markers, primary) { 5996 var this$1 = this; 5997 5998 this.markers = markers; 5999 this.primary = primary; 6000 for (var i = 0; i < markers.length; ++i) 6001 { markers[i].parent = this$1; } 6002 }; 6003 6004 SharedTextMarker.prototype.clear = function () { 6005 var this$1 = this; 6006 6007 if (this.explicitlyCleared) { return } 6008 this.explicitlyCleared = true; 6009 for (var i = 0; i < this.markers.length; ++i) 6010 { this$1.markers[i].clear(); } 6011 signalLater(this, "clear"); 6012 }; 6013 6014 SharedTextMarker.prototype.find = function (side, lineObj) { 6015 return this.primary.find(side, lineObj) 6016 }; 6017 eventMixin(SharedTextMarker); 6018 6019 function markTextShared(doc, from, to, options, type) { 6020 options = copyObj(options); 6021 options.shared = false; 6022 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 6023 var widget = options.widgetNode; 6024 linkedDocs(doc, function (doc) { 6025 if (widget) { options.widgetNode = widget.cloneNode(true); } 6026 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 6027 for (var i = 0; i < doc.linked.length; ++i) 6028 { if (doc.linked[i].isParent) { return } } 6029 primary = lst(markers); 6030 }); 6031 return new SharedTextMarker(markers, primary) 6032 } 6033 6034 function findSharedMarkers(doc) { 6035 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) 6036 } 6037 6038 function copySharedMarkers(doc, markers) { 6039 for (var i = 0; i < markers.length; i++) { 6040 var marker = markers[i], pos = marker.find(); 6041 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); 6042 if (cmp(mFrom, mTo)) { 6043 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); 6044 marker.markers.push(subMark); 6045 subMark.parent = marker; 6046 } 6047 } 6048 } 6049 6050 function detachSharedMarkers(markers) { 6051 var loop = function ( i ) { 6052 var marker = markers[i], linked = [marker.primary.doc]; 6053 linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); 6054 for (var j = 0; j < marker.markers.length; j++) { 6055 var subMarker = marker.markers[j]; 6056 if (indexOf(linked, subMarker.doc) == -1) { 6057 subMarker.parent = null; 6058 marker.markers.splice(j--, 1); 6059 } 6060 } 6061 }; 6062 6063 for (var i = 0; i < markers.length; i++) loop( i ); 6064 } 6065 6066 var nextDocId = 0; 6067 var Doc = function(text, mode, firstLine, lineSep, direction) { 6068 if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } 6069 if (firstLine == null) { firstLine = 0; } 6070 6071 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); 6072 this.first = firstLine; 6073 this.scrollTop = this.scrollLeft = 0; 6074 this.cantEdit = false; 6075 this.cleanGeneration = 1; 6076 this.modeFrontier = this.highlightFrontier = firstLine; 6077 var start = Pos(firstLine, 0); 6078 this.sel = simpleSelection(start); 6079 this.history = new History(null); 6080 this.id = ++nextDocId; 6081 this.modeOption = mode; 6082 this.lineSep = lineSep; 6083 this.direction = (direction == "rtl") ? "rtl" : "ltr"; 6084 this.extend = false; 6085 6086 if (typeof text == "string") { text = this.splitLines(text); } 6087 updateDoc(this, {from: start, to: start, text: text}); 6088 setSelection(this, simpleSelection(start), sel_dontScroll); 6089 }; 6090 6091 Doc.prototype = createObj(BranchChunk.prototype, { 6092 constructor: Doc, 6093 // Iterate over the document. Supports two forms -- with only one 6094 // argument, it calls that for each line in the document. With 6095 // three, it iterates over the range given by the first two (with 6096 // the second being non-inclusive). 6097 iter: function(from, to, op) { 6098 if (op) { this.iterN(from - this.first, to - from, op); } 6099 else { this.iterN(this.first, this.first + this.size, from); } 6100 }, 6101 6102 // Non-public interface for adding and removing lines. 6103 insert: function(at, lines) { 6104 var height = 0; 6105 for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } 6106 this.insertInner(at - this.first, lines, height); 6107 }, 6108 remove: function(at, n) { this.removeInner(at - this.first, n); }, 6109 6110 // From here, the methods are part of the public interface. Most 6111 // are also available from CodeMirror (editor) instances. 6112 6113 getValue: function(lineSep) { 6114 var lines = getLines(this, this.first, this.first + this.size); 6115 if (lineSep === false) { return lines } 6116 return lines.join(lineSep || this.lineSeparator()) 6117 }, 6118 setValue: docMethodOp(function(code) { 6119 var top = Pos(this.first, 0), last = this.first + this.size - 1; 6120 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 6121 text: this.splitLines(code), origin: "setValue", full: true}, true); 6122 if (this.cm) { scrollToCoords(this.cm, 0, 0); } 6123 setSelection(this, simpleSelection(top), sel_dontScroll); 6124 }), 6125 replaceRange: function(code, from, to, origin) { 6126 from = clipPos(this, from); 6127 to = to ? clipPos(this, to) : from; 6128 replaceRange(this, code, from, to, origin); 6129 }, 6130 getRange: function(from, to, lineSep) { 6131 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 6132 if (lineSep === false) { return lines } 6133 return lines.join(lineSep || this.lineSeparator()) 6134 }, 6135 6136 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, 6137 6138 getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, 6139 getLineNumber: function(line) {return lineNo(line)}, 6140 6141 getLineHandleVisualStart: function(line) { 6142 if (typeof line == "number") { line = getLine(this, line); } 6143 return visualLine(line) 6144 }, 6145 6146 lineCount: function() {return this.size}, 6147 firstLine: function() {return this.first}, 6148 lastLine: function() {return this.first + this.size - 1}, 6149 6150 clipPos: function(pos) {return clipPos(this, pos)}, 6151 6152 getCursor: function(start) { 6153 var range$$1 = this.sel.primary(), pos; 6154 if (start == null || start == "head") { pos = range$$1.head; } 6155 else if (start == "anchor") { pos = range$$1.anchor; } 6156 else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } 6157 else { pos = range$$1.from(); } 6158 return pos 6159 }, 6160 listSelections: function() { return this.sel.ranges }, 6161 somethingSelected: function() {return this.sel.somethingSelected()}, 6162 6163 setCursor: docMethodOp(function(line, ch, options) { 6164 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); 6165 }), 6166 setSelection: docMethodOp(function(anchor, head, options) { 6167 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); 6168 }), 6169 extendSelection: docMethodOp(function(head, other, options) { 6170 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); 6171 }), 6172 extendSelections: docMethodOp(function(heads, options) { 6173 extendSelections(this, clipPosArray(this, heads), options); 6174 }), 6175 extendSelectionsBy: docMethodOp(function(f, options) { 6176 var heads = map(this.sel.ranges, f); 6177 extendSelections(this, clipPosArray(this, heads), options); 6178 }), 6179 setSelections: docMethodOp(function(ranges, primary, options) { 6180 var this$1 = this; 6181 6182 if (!ranges.length) { return } 6183 var out = []; 6184 for (var i = 0; i < ranges.length; i++) 6185 { out[i] = new Range(clipPos(this$1, ranges[i].anchor), 6186 clipPos(this$1, ranges[i].head)); } 6187 if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } 6188 setSelection(this, normalizeSelection(out, primary), options); 6189 }), 6190 addSelection: docMethodOp(function(anchor, head, options) { 6191 var ranges = this.sel.ranges.slice(0); 6192 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); 6193 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); 6194 }), 6195 6196 getSelection: function(lineSep) { 6197 var this$1 = this; 6198 6199 var ranges = this.sel.ranges, lines; 6200 for (var i = 0; i < ranges.length; i++) { 6201 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6202 lines = lines ? lines.concat(sel) : sel; 6203 } 6204 if (lineSep === false) { return lines } 6205 else { return lines.join(lineSep || this.lineSeparator()) } 6206 }, 6207 getSelections: function(lineSep) { 6208 var this$1 = this; 6209 6210 var parts = [], ranges = this.sel.ranges; 6211 for (var i = 0; i < ranges.length; i++) { 6212 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6213 if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } 6214 parts[i] = sel; 6215 } 6216 return parts 6217 }, 6218 replaceSelection: function(code, collapse, origin) { 6219 var dup = []; 6220 for (var i = 0; i < this.sel.ranges.length; i++) 6221 { dup[i] = code; } 6222 this.replaceSelections(dup, collapse, origin || "+input"); 6223 }, 6224 replaceSelections: docMethodOp(function(code, collapse, origin) { 6225 var this$1 = this; 6226 6227 var changes = [], sel = this.sel; 6228 for (var i = 0; i < sel.ranges.length; i++) { 6229 var range$$1 = sel.ranges[i]; 6230 changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; 6231 } 6232 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); 6233 for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) 6234 { makeChange(this$1, changes[i$1]); } 6235 if (newSel) { setSelectionReplaceHistory(this, newSel); } 6236 else if (this.cm) { ensureCursorVisible(this.cm); } 6237 }), 6238 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), 6239 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), 6240 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), 6241 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), 6242 6243 setExtending: function(val) {this.extend = val;}, 6244 getExtending: function() {return this.extend}, 6245 6246 historySize: function() { 6247 var hist = this.history, done = 0, undone = 0; 6248 for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } 6249 for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } 6250 return {undo: done, redo: undone} 6251 }, 6252 clearHistory: function() {this.history = new History(this.history.maxGeneration);}, 6253 6254 markClean: function() { 6255 this.cleanGeneration = this.changeGeneration(true); 6256 }, 6257 changeGeneration: function(forceSplit) { 6258 if (forceSplit) 6259 { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } 6260 return this.history.generation 6261 }, 6262 isClean: function (gen) { 6263 return this.history.generation == (gen || this.cleanGeneration) 6264 }, 6265 6266 getHistory: function() { 6267 return {done: copyHistoryArray(this.history.done), 6268 undone: copyHistoryArray(this.history.undone)} 6269 }, 6270 setHistory: function(histData) { 6271 var hist = this.history = new History(this.history.maxGeneration); 6272 hist.done = copyHistoryArray(histData.done.slice(0), null, true); 6273 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); 6274 }, 6275 6276 setGutterMarker: docMethodOp(function(line, gutterID, value) { 6277 return changeLine(this, line, "gutter", function (line) { 6278 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 6279 markers[gutterID] = value; 6280 if (!value && isEmpty(markers)) { line.gutterMarkers = null; } 6281 return true 6282 }) 6283 }), 6284 6285 clearGutter: docMethodOp(function(gutterID) { 6286 var this$1 = this; 6287 6288 this.iter(function (line) { 6289 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 6290 changeLine(this$1, line, "gutter", function () { 6291 line.gutterMarkers[gutterID] = null; 6292 if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } 6293 return true 6294 }); 6295 } 6296 }); 6297 }), 6298 6299 lineInfo: function(line) { 6300 var n; 6301 if (typeof line == "number") { 6302 if (!isLine(this, line)) { return null } 6303 n = line; 6304 line = getLine(this, line); 6305 if (!line) { return null } 6306 } else { 6307 n = lineNo(line); 6308 if (n == null) { return null } 6309 } 6310 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 6311 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 6312 widgets: line.widgets} 6313 }, 6314 6315 addLineClass: docMethodOp(function(handle, where, cls) { 6316 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6317 var prop = where == "text" ? "textClass" 6318 : where == "background" ? "bgClass" 6319 : where == "gutter" ? "gutterClass" : "wrapClass"; 6320 if (!line[prop]) { line[prop] = cls; } 6321 else if (classTest(cls).test(line[prop])) { return false } 6322 else { line[prop] += " " + cls; } 6323 return true 6324 }) 6325 }), 6326 removeLineClass: docMethodOp(function(handle, where, cls) { 6327 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6328 var prop = where == "text" ? "textClass" 6329 : where == "background" ? "bgClass" 6330 : where == "gutter" ? "gutterClass" : "wrapClass"; 6331 var cur = line[prop]; 6332 if (!cur) { return false } 6333 else if (cls == null) { line[prop] = null; } 6334 else { 6335 var found = cur.match(classTest(cls)); 6336 if (!found) { return false } 6337 var end = found.index + found[0].length; 6338 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; 6339 } 6340 return true 6341 }) 6342 }), 6343 6344 addLineWidget: docMethodOp(function(handle, node, options) { 6345 return addLineWidget(this, handle, node, options) 6346 }), 6347 removeLineWidget: function(widget) { widget.clear(); }, 6348 6349 markText: function(from, to, options) { 6350 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") 6351 }, 6352 setBookmark: function(pos, options) { 6353 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 6354 insertLeft: options && options.insertLeft, 6355 clearWhenEmpty: false, shared: options && options.shared, 6356 handleMouseEvents: options && options.handleMouseEvents}; 6357 pos = clipPos(this, pos); 6358 return markText(this, pos, pos, realOpts, "bookmark") 6359 }, 6360 findMarksAt: function(pos) { 6361 pos = clipPos(this, pos); 6362 var markers = [], spans = getLine(this, pos.line).markedSpans; 6363 if (spans) { for (var i = 0; i < spans.length; ++i) { 6364 var span = spans[i]; 6365 if ((span.from == null || span.from <= pos.ch) && 6366 (span.to == null || span.to >= pos.ch)) 6367 { markers.push(span.marker.parent || span.marker); } 6368 } } 6369 return markers 6370 }, 6371 findMarks: function(from, to, filter) { 6372 from = clipPos(this, from); to = clipPos(this, to); 6373 var found = [], lineNo$$1 = from.line; 6374 this.iter(from.line, to.line + 1, function (line) { 6375 var spans = line.markedSpans; 6376 if (spans) { for (var i = 0; i < spans.length; i++) { 6377 var span = spans[i]; 6378 if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || 6379 span.from == null && lineNo$$1 != from.line || 6380 span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && 6381 (!filter || filter(span.marker))) 6382 { found.push(span.marker.parent || span.marker); } 6383 } } 6384 ++lineNo$$1; 6385 }); 6386 return found 6387 }, 6388 getAllMarks: function() { 6389 var markers = []; 6390 this.iter(function (line) { 6391 var sps = line.markedSpans; 6392 if (sps) { for (var i = 0; i < sps.length; ++i) 6393 { if (sps[i].from != null) { markers.push(sps[i].marker); } } } 6394 }); 6395 return markers 6396 }, 6397 6398 posFromIndex: function(off) { 6399 var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; 6400 this.iter(function (line) { 6401 var sz = line.text.length + sepSize; 6402 if (sz > off) { ch = off; return true } 6403 off -= sz; 6404 ++lineNo$$1; 6405 }); 6406 return clipPos(this, Pos(lineNo$$1, ch)) 6407 }, 6408 indexFromPos: function (coords) { 6409 coords = clipPos(this, coords); 6410 var index = coords.ch; 6411 if (coords.line < this.first || coords.ch < 0) { return 0 } 6412 var sepSize = this.lineSeparator().length; 6413 this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value 6414 index += line.text.length + sepSize; 6415 }); 6416 return index 6417 }, 6418 6419 copy: function(copyHistory) { 6420 var doc = new Doc(getLines(this, this.first, this.first + this.size), 6421 this.modeOption, this.first, this.lineSep, this.direction); 6422 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 6423 doc.sel = this.sel; 6424 doc.extend = false; 6425 if (copyHistory) { 6426 doc.history.undoDepth = this.history.undoDepth; 6427 doc.setHistory(this.getHistory()); 6428 } 6429 return doc 6430 }, 6431 6432 linkedDoc: function(options) { 6433 if (!options) { options = {}; } 6434 var from = this.first, to = this.first + this.size; 6435 if (options.from != null && options.from > from) { from = options.from; } 6436 if (options.to != null && options.to < to) { to = options.to; } 6437 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); 6438 if (options.sharedHist) { copy.history = this.history 6439 ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 6440 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 6441 copySharedMarkers(copy, findSharedMarkers(this)); 6442 return copy 6443 }, 6444 unlinkDoc: function(other) { 6445 var this$1 = this; 6446 6447 if (other instanceof CodeMirror$1) { other = other.doc; } 6448 if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { 6449 var link = this$1.linked[i]; 6450 if (link.doc != other) { continue } 6451 this$1.linked.splice(i, 1); 6452 other.unlinkDoc(this$1); 6453 detachSharedMarkers(findSharedMarkers(this$1)); 6454 break 6455 } } 6456 // If the histories were shared, split them again 6457 if (other.history == this.history) { 6458 var splitIds = [other.id]; 6459 linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); 6460 other.history = new History(null); 6461 other.history.done = copyHistoryArray(this.history.done, splitIds); 6462 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 6463 } 6464 }, 6465 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 6466 6467 getMode: function() {return this.mode}, 6468 getEditor: function() {return this.cm}, 6469 6470 splitLines: function(str) { 6471 if (this.lineSep) { return str.split(this.lineSep) } 6472 return splitLinesAuto(str) 6473 }, 6474 lineSeparator: function() { return this.lineSep || "\n" }, 6475 6476 setDirection: docMethodOp(function (dir) { 6477 if (dir != "rtl") { dir = "ltr"; } 6478 if (dir == this.direction) { return } 6479 this.direction = dir; 6480 this.iter(function (line) { return line.order = null; }); 6481 if (this.cm) { directionChanged(this.cm); } 6482 }) 6483 }); 6484 6485 // Public alias. 6486 Doc.prototype.eachLine = Doc.prototype.iter; 6487 6488 // Kludge to work around strange IE behavior where it'll sometimes 6489 // re-fire a series of drag-related events right after the drop (#1551) 6490 var lastDrop = 0; 6491 6492 function onDrop(e) { 6493 var cm = this; 6494 clearDragCursor(cm); 6495 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) 6496 { return } 6497 e_preventDefault(e); 6498 if (ie) { lastDrop = +new Date; } 6499 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 6500 if (!pos || cm.isReadOnly()) { return } 6501 // Might be a file drop, in which case we simply extract the text 6502 // and insert it. 6503 if (files && files.length && window.FileReader && window.File) { 6504 var n = files.length, text = Array(n), read = 0; 6505 var loadFile = function (file, i) { 6506 if (cm.options.allowDropFileTypes && 6507 indexOf(cm.options.allowDropFileTypes, file.type) == -1) 6508 { return } 6509 6510 var reader = new FileReader; 6511 reader.onload = operation(cm, function () { 6512 var content = reader.result; 6513 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } 6514 text[i] = content; 6515 if (++read == n) { 6516 pos = clipPos(cm.doc, pos); 6517 var change = {from: pos, to: pos, 6518 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), 6519 origin: "paste"}; 6520 makeChange(cm.doc, change); 6521 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); 6522 } 6523 }); 6524 reader.readAsText(file); 6525 }; 6526 for (var i = 0; i < n; ++i) { loadFile(files[i], i); } 6527 } else { // Normal drop 6528 // Don't do a replace if the drop happened inside of the selected text. 6529 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { 6530 cm.state.draggingText(e); 6531 // Ensure the editor is re-focused 6532 setTimeout(function () { return cm.display.input.focus(); }, 20); 6533 return 6534 } 6535 try { 6536 var text$1 = e.dataTransfer.getData("Text"); 6537 if (text$1) { 6538 var selected; 6539 if (cm.state.draggingText && !cm.state.draggingText.copy) 6540 { selected = cm.listSelections(); } 6541 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); 6542 if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) 6543 { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } 6544 cm.replaceSelection(text$1, "around", "paste"); 6545 cm.display.input.focus(); 6546 } 6547 } 6548 catch(e){} 6549 } 6550 } 6551 6552 function onDragStart(cm, e) { 6553 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } 6554 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } 6555 6556 e.dataTransfer.setData("Text", cm.getSelection()); 6557 e.dataTransfer.effectAllowed = "copyMove"; 6558 6559 // Use dummy image instead of default browsers image. 6560 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 6561 if (e.dataTransfer.setDragImage && !safari) { 6562 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 6563 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; 6564 if (presto) { 6565 img.width = img.height = 1; 6566 cm.display.wrapper.appendChild(img); 6567 // Force a relayout, or Opera won't use our image for some obscure reason 6568 img._top = img.offsetTop; 6569 } 6570 e.dataTransfer.setDragImage(img, 0, 0); 6571 if (presto) { img.parentNode.removeChild(img); } 6572 } 6573 } 6574 6575 function onDragOver(cm, e) { 6576 var pos = posFromMouse(cm, e); 6577 if (!pos) { return } 6578 var frag = document.createDocumentFragment(); 6579 drawSelectionCursor(cm, pos, frag); 6580 if (!cm.display.dragCursor) { 6581 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); 6582 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); 6583 } 6584 removeChildrenAndAdd(cm.display.dragCursor, frag); 6585 } 6586 6587 function clearDragCursor(cm) { 6588 if (cm.display.dragCursor) { 6589 cm.display.lineSpace.removeChild(cm.display.dragCursor); 6590 cm.display.dragCursor = null; 6591 } 6592 } 6593 6594 // These must be handled carefully, because naively registering a 6595 // handler for each editor will cause the editors to never be 6596 // garbage collected. 6597 6598 function forEachCodeMirror(f) { 6599 if (!document.getElementsByClassName) { return } 6600 var byClass = document.getElementsByClassName("CodeMirror"); 6601 for (var i = 0; i < byClass.length; i++) { 6602 var cm = byClass[i].CodeMirror; 6603 if (cm) { f(cm); } 6604 } 6605 } 6606 6607 var globalsRegistered = false; 6608 function ensureGlobalHandlers() { 6609 if (globalsRegistered) { return } 6610 registerGlobalHandlers(); 6611 globalsRegistered = true; 6612 } 6613 function registerGlobalHandlers() { 6614 // When the window resizes, we need to refresh active editors. 6615 var resizeTimer; 6616 on(window, "resize", function () { 6617 if (resizeTimer == null) { resizeTimer = setTimeout(function () { 6618 resizeTimer = null; 6619 forEachCodeMirror(onResize); 6620 }, 100); } 6621 }); 6622 // When the window loses focus, we want to show the editor as blurred 6623 on(window, "blur", function () { return forEachCodeMirror(onBlur); }); 6624 } 6625 // Called when the window resizes 6626 function onResize(cm) { 6627 var d = cm.display; 6628 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) 6629 { return } 6630 // Might be a text scaling operation, clear size caches. 6631 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 6632 d.scrollbarsClipped = false; 6633 cm.setSize(); 6634 } 6635 6636 var keyNames = { 6637 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 6638 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 6639 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 6640 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 6641 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 6642 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 6643 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 6644 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 6645 }; 6646 6647 // Number keys 6648 for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } 6649 // Alphabetic keys 6650 for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } 6651 // Function keys 6652 for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } 6653 6654 var keyMap = {}; 6655 6656 keyMap.basic = { 6657 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 6658 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 6659 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", 6660 "Tab": "defaultTab", "Shift-Tab": "indentAuto", 6661 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", 6662 "Esc": "singleSelection" 6663 }; 6664 // Note that the save and find-related commands aren't defined by 6665 // default. User code or addons can define them. Unknown commands 6666 // are simply ignored. 6667 keyMap.pcDefault = { 6668 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 6669 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", 6670 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 6671 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", 6672 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 6673 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 6674 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", 6675 fallthrough: "basic" 6676 }; 6677 // Very basic readline/emacs-style bindings, which are standard on Mac. 6678 keyMap.emacsy = { 6679 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 6680 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 6681 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 6682 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", 6683 "Ctrl-O": "openLine" 6684 }; 6685 keyMap.macDefault = { 6686 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 6687 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", 6688 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", 6689 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", 6690 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 6691 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", 6692 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", 6693 fallthrough: ["basic", "emacsy"] 6694 }; 6695 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 6696 6697 // KEYMAP DISPATCH 6698 6699 function normalizeKeyName(name) { 6700 var parts = name.split(/-(?!$)/); 6701 name = parts[parts.length - 1]; 6702 var alt, ctrl, shift, cmd; 6703 for (var i = 0; i < parts.length - 1; i++) { 6704 var mod = parts[i]; 6705 if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } 6706 else if (/^a(lt)?$/i.test(mod)) { alt = true; } 6707 else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } 6708 else if (/^s(hift)?$/i.test(mod)) { shift = true; } 6709 else { throw new Error("Unrecognized modifier name: " + mod) } 6710 } 6711 if (alt) { name = "Alt-" + name; } 6712 if (ctrl) { name = "Ctrl-" + name; } 6713 if (cmd) { name = "Cmd-" + name; } 6714 if (shift) { name = "Shift-" + name; } 6715 return name 6716 } 6717 6718 // This is a kludge to keep keymaps mostly working as raw objects 6719 // (backwards compatibility) while at the same time support features 6720 // like normalization and multi-stroke key bindings. It compiles a 6721 // new normalized keymap, and then updates the old object to reflect 6722 // this. 6723 function normalizeKeyMap(keymap) { 6724 var copy = {}; 6725 for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { 6726 var value = keymap[keyname]; 6727 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } 6728 if (value == "...") { delete keymap[keyname]; continue } 6729 6730 var keys = map(keyname.split(" "), normalizeKeyName); 6731 for (var i = 0; i < keys.length; i++) { 6732 var val = (void 0), name = (void 0); 6733 if (i == keys.length - 1) { 6734 name = keys.join(" "); 6735 val = value; 6736 } else { 6737 name = keys.slice(0, i + 1).join(" "); 6738 val = "..."; 6739 } 6740 var prev = copy[name]; 6741 if (!prev) { copy[name] = val; } 6742 else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } 6743 } 6744 delete keymap[keyname]; 6745 } } 6746 for (var prop in copy) { keymap[prop] = copy[prop]; } 6747 return keymap 6748 } 6749 6750 function lookupKey(key, map$$1, handle, context) { 6751 map$$1 = getKeyMap(map$$1); 6752 var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; 6753 if (found === false) { return "nothing" } 6754 if (found === "...") { return "multi" } 6755 if (found != null && handle(found)) { return "handled" } 6756 6757 if (map$$1.fallthrough) { 6758 if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") 6759 { return lookupKey(key, map$$1.fallthrough, handle, context) } 6760 for (var i = 0; i < map$$1.fallthrough.length; i++) { 6761 var result = lookupKey(key, map$$1.fallthrough[i], handle, context); 6762 if (result) { return result } 6763 } 6764 } 6765 } 6766 6767 // Modifier key presses don't count as 'real' key presses for the 6768 // purpose of keymap fallthrough. 6769 function isModifierKey(value) { 6770 var name = typeof value == "string" ? value : keyNames[value.keyCode]; 6771 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" 6772 } 6773 6774 function addModifierNames(name, event, noShift) { 6775 var base = name; 6776 if (event.altKey && base != "Alt") { name = "Alt-" + name; } 6777 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } 6778 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } 6779 if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } 6780 return name 6781 } 6782 6783 // Look up the name of a key as indicated by an event object. 6784 function keyName(event, noShift) { 6785 if (presto && event.keyCode == 34 && event["char"]) { return false } 6786 var name = keyNames[event.keyCode]; 6787 if (name == null || event.altGraphKey) { return false } 6788 return addModifierNames(name, event, noShift) 6789 } 6790 6791 function getKeyMap(val) { 6792 return typeof val == "string" ? keyMap[val] : val 6793 } 6794 6795 // Helper for deleting text near the selection(s), used to implement 6796 // backspace, delete, and similar functionality. 6797 function deleteNearSelection(cm, compute) { 6798 var ranges = cm.doc.sel.ranges, kill = []; 6799 // Build up a set of ranges to kill first, merging overlapping 6800 // ranges. 6801 for (var i = 0; i < ranges.length; i++) { 6802 var toKill = compute(ranges[i]); 6803 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { 6804 var replaced = kill.pop(); 6805 if (cmp(replaced.from, toKill.from) < 0) { 6806 toKill.from = replaced.from; 6807 break 6808 } 6809 } 6810 kill.push(toKill); 6811 } 6812 // Next, remove those actual ranges. 6813 runInOp(cm, function () { 6814 for (var i = kill.length - 1; i >= 0; i--) 6815 { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } 6816 ensureCursorVisible(cm); 6817 }); 6818 } 6819 6820 function moveCharLogically(line, ch, dir) { 6821 var target = skipExtendingChars(line.text, ch + dir, dir); 6822 return target < 0 || target > line.text.length ? null : target 6823 } 6824 6825 function moveLogically(line, start, dir) { 6826 var ch = moveCharLogically(line, start.ch, dir); 6827 return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") 6828 } 6829 6830 function endOfLine(visually, cm, lineObj, lineNo, dir) { 6831 if (visually) { 6832 var order = getOrder(lineObj, cm.doc.direction); 6833 if (order) { 6834 var part = dir < 0 ? lst(order) : order[0]; 6835 var moveInStorageOrder = (dir < 0) == (part.level == 1); 6836 var sticky = moveInStorageOrder ? "after" : "before"; 6837 var ch; 6838 // With a wrapped rtl chunk (possibly spanning multiple bidi parts), 6839 // it could be that the last bidi part is not on the last visual line, 6840 // since visual lines contain content order-consecutive chunks. 6841 // Thus, in rtl, we are looking for the first (content-order) character 6842 // in the rtl chunk that is on the last line (that is, the same line 6843 // as the last (content-order) character). 6844 if (part.level > 0 || cm.doc.direction == "rtl") { 6845 var prep = prepareMeasureForLine(cm, lineObj); 6846 ch = dir < 0 ? lineObj.text.length - 1 : 0; 6847 var targetTop = measureCharPrepared(cm, prep, ch).top; 6848 ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); 6849 if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } 6850 } else { ch = dir < 0 ? part.to : part.from; } 6851 return new Pos(lineNo, ch, sticky) 6852 } 6853 } 6854 return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") 6855 } 6856 6857 function moveVisually(cm, line, start, dir) { 6858 var bidi = getOrder(line, cm.doc.direction); 6859 if (!bidi) { return moveLogically(line, start, dir) } 6860 if (start.ch >= line.text.length) { 6861 start.ch = line.text.length; 6862 start.sticky = "before"; 6863 } else if (start.ch <= 0) { 6864 start.ch = 0; 6865 start.sticky = "after"; 6866 } 6867 var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; 6868 if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { 6869 // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, 6870 // nothing interesting happens. 6871 return moveLogically(line, start, dir) 6872 } 6873 6874 var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; 6875 var prep; 6876 var getWrappedLineExtent = function (ch) { 6877 if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } 6878 prep = prep || prepareMeasureForLine(cm, line); 6879 return wrappedLineExtentChar(cm, line, prep, ch) 6880 }; 6881 var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); 6882 6883 if (cm.doc.direction == "rtl" || part.level == 1) { 6884 var moveInStorageOrder = (part.level == 1) == (dir < 0); 6885 var ch = mv(start, moveInStorageOrder ? 1 : -1); 6886 if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { 6887 // Case 2: We move within an rtl part or in an rtl editor on the same visual line 6888 var sticky = moveInStorageOrder ? "before" : "after"; 6889 return new Pos(start.line, ch, sticky) 6890 } 6891 } 6892 6893 // Case 3: Could not move within this bidi part in this visual line, so leave 6894 // the current bidi part 6895 6896 var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { 6897 var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder 6898 ? new Pos(start.line, mv(ch, 1), "before") 6899 : new Pos(start.line, ch, "after"); }; 6900 6901 for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { 6902 var part = bidi[partPos]; 6903 var moveInStorageOrder = (dir > 0) == (part.level != 1); 6904 var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); 6905 if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } 6906 ch = moveInStorageOrder ? part.from : mv(part.to, -1); 6907 if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } 6908 } 6909 }; 6910 6911 // Case 3a: Look for other bidi parts on the same visual line 6912 var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); 6913 if (res) { return res } 6914 6915 // Case 3b: Look for other bidi parts on the next visual line 6916 var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); 6917 if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { 6918 res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); 6919 if (res) { return res } 6920 } 6921 6922 // Case 4: Nowhere to move 6923 return null 6924 } 6925 6926 // Commands are parameter-less actions that can be performed on an 6927 // editor, mostly used for keybindings. 6928 var commands = { 6929 selectAll: selectAll, 6930 singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, 6931 killLine: function (cm) { return deleteNearSelection(cm, function (range) { 6932 if (range.empty()) { 6933 var len = getLine(cm.doc, range.head.line).text.length; 6934 if (range.head.ch == len && range.head.line < cm.lastLine()) 6935 { return {from: range.head, to: Pos(range.head.line + 1, 0)} } 6936 else 6937 { return {from: range.head, to: Pos(range.head.line, len)} } 6938 } else { 6939 return {from: range.from(), to: range.to()} 6940 } 6941 }); }, 6942 deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6943 from: Pos(range.from().line, 0), 6944 to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) 6945 }); }); }, 6946 delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6947 from: Pos(range.from().line, 0), to: range.from() 6948 }); }); }, 6949 delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { 6950 var top = cm.charCoords(range.head, "div").top + 5; 6951 var leftPos = cm.coordsChar({left: 0, top: top}, "div"); 6952 return {from: leftPos, to: range.from()} 6953 }); }, 6954 delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { 6955 var top = cm.charCoords(range.head, "div").top + 5; 6956 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 6957 return {from: range.from(), to: rightPos } 6958 }); }, 6959 undo: function (cm) { return cm.undo(); }, 6960 redo: function (cm) { return cm.redo(); }, 6961 undoSelection: function (cm) { return cm.undoSelection(); }, 6962 redoSelection: function (cm) { return cm.redoSelection(); }, 6963 goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, 6964 goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, 6965 goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, 6966 {origin: "+move", bias: 1} 6967 ); }, 6968 goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, 6969 {origin: "+move", bias: 1} 6970 ); }, 6971 goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, 6972 {origin: "+move", bias: -1} 6973 ); }, 6974 goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { 6975 var top = cm.cursorCoords(range.head, "div").top + 5; 6976 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") 6977 }, sel_move); }, 6978 goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { 6979 var top = cm.cursorCoords(range.head, "div").top + 5; 6980 return cm.coordsChar({left: 0, top: top}, "div") 6981 }, sel_move); }, 6982 goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { 6983 var top = cm.cursorCoords(range.head, "div").top + 5; 6984 var pos = cm.coordsChar({left: 0, top: top}, "div"); 6985 if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } 6986 return pos 6987 }, sel_move); }, 6988 goLineUp: function (cm) { return cm.moveV(-1, "line"); }, 6989 goLineDown: function (cm) { return cm.moveV(1, "line"); }, 6990 goPageUp: function (cm) { return cm.moveV(-1, "page"); }, 6991 goPageDown: function (cm) { return cm.moveV(1, "page"); }, 6992 goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, 6993 goCharRight: function (cm) { return cm.moveH(1, "char"); }, 6994 goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, 6995 goColumnRight: function (cm) { return cm.moveH(1, "column"); }, 6996 goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, 6997 goGroupRight: function (cm) { return cm.moveH(1, "group"); }, 6998 goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, 6999 goWordRight: function (cm) { return cm.moveH(1, "word"); }, 7000 delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, 7001 delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, 7002 delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, 7003 delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, 7004 delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, 7005 delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, 7006 indentAuto: function (cm) { return cm.indentSelection("smart"); }, 7007 indentMore: function (cm) { return cm.indentSelection("add"); }, 7008 indentLess: function (cm) { return cm.indentSelection("subtract"); }, 7009 insertTab: function (cm) { return cm.replaceSelection("\t"); }, 7010 insertSoftTab: function (cm) { 7011 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; 7012 for (var i = 0; i < ranges.length; i++) { 7013 var pos = ranges[i].from(); 7014 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); 7015 spaces.push(spaceStr(tabSize - col % tabSize)); 7016 } 7017 cm.replaceSelections(spaces); 7018 }, 7019 defaultTab: function (cm) { 7020 if (cm.somethingSelected()) { cm.indentSelection("add"); } 7021 else { cm.execCommand("insertTab"); } 7022 }, 7023 // Swap the two chars left and right of each selection's head. 7024 // Move cursor behind the two swapped characters afterwards. 7025 // 7026 // Doesn't consider line feeds a character. 7027 // Doesn't scan more than one line above to find a character. 7028 // Doesn't do anything on an empty line. 7029 // Doesn't do anything with non-empty selections. 7030 transposeChars: function (cm) { return runInOp(cm, function () { 7031 var ranges = cm.listSelections(), newSel = []; 7032 for (var i = 0; i < ranges.length; i++) { 7033 if (!ranges[i].empty()) { continue } 7034 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; 7035 if (line) { 7036 if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } 7037 if (cur.ch > 0) { 7038 cur = new Pos(cur.line, cur.ch + 1); 7039 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), 7040 Pos(cur.line, cur.ch - 2), cur, "+transpose"); 7041 } else if (cur.line > cm.doc.first) { 7042 var prev = getLine(cm.doc, cur.line - 1).text; 7043 if (prev) { 7044 cur = new Pos(cur.line, 1); 7045 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + 7046 prev.charAt(prev.length - 1), 7047 Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); 7048 } 7049 } 7050 } 7051 newSel.push(new Range(cur, cur)); 7052 } 7053 cm.setSelections(newSel); 7054 }); }, 7055 newlineAndIndent: function (cm) { return runInOp(cm, function () { 7056 var sels = cm.listSelections(); 7057 for (var i = sels.length - 1; i >= 0; i--) 7058 { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } 7059 sels = cm.listSelections(); 7060 for (var i$1 = 0; i$1 < sels.length; i$1++) 7061 { cm.indentLine(sels[i$1].from().line, null, true); } 7062 ensureCursorVisible(cm); 7063 }); }, 7064 openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, 7065 toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } 7066 }; 7067 7068 7069 function lineStart(cm, lineN) { 7070 var line = getLine(cm.doc, lineN); 7071 var visual = visualLine(line); 7072 if (visual != line) { lineN = lineNo(visual); } 7073 return endOfLine(true, cm, visual, lineN, 1) 7074 } 7075 function lineEnd(cm, lineN) { 7076 var line = getLine(cm.doc, lineN); 7077 var visual = visualLineEnd(line); 7078 if (visual != line) { lineN = lineNo(visual); } 7079 return endOfLine(true, cm, line, lineN, -1) 7080 } 7081 function lineStartSmart(cm, pos) { 7082 var start = lineStart(cm, pos.line); 7083 var line = getLine(cm.doc, start.line); 7084 var order = getOrder(line, cm.doc.direction); 7085 if (!order || order[0].level == 0) { 7086 var firstNonWS = Math.max(0, line.text.search(/\S/)); 7087 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; 7088 return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) 7089 } 7090 return start 7091 } 7092 7093 // Run a handler that was bound to a key. 7094 function doHandleBinding(cm, bound, dropShift) { 7095 if (typeof bound == "string") { 7096 bound = commands[bound]; 7097 if (!bound) { return false } 7098 } 7099 // Ensure previous input has been read, so that the handler sees a 7100 // consistent view of the document 7101 cm.display.input.ensurePolled(); 7102 var prevShift = cm.display.shift, done = false; 7103 try { 7104 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 7105 if (dropShift) { cm.display.shift = false; } 7106 done = bound(cm) != Pass; 7107 } finally { 7108 cm.display.shift = prevShift; 7109 cm.state.suppressEdits = false; 7110 } 7111 return done 7112 } 7113 7114 function lookupKeyForEditor(cm, name, handle) { 7115 for (var i = 0; i < cm.state.keyMaps.length; i++) { 7116 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); 7117 if (result) { return result } 7118 } 7119 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) 7120 || lookupKey(name, cm.options.keyMap, handle, cm) 7121 } 7122 7123 // Note that, despite the name, this function is also used to check 7124 // for bound mouse clicks. 7125 7126 var stopSeq = new Delayed; 7127 function dispatchKey(cm, name, e, handle) { 7128 var seq = cm.state.keySeq; 7129 if (seq) { 7130 if (isModifierKey(name)) { return "handled" } 7131 stopSeq.set(50, function () { 7132 if (cm.state.keySeq == seq) { 7133 cm.state.keySeq = null; 7134 cm.display.input.reset(); 7135 } 7136 }); 7137 name = seq + " " + name; 7138 } 7139 var result = lookupKeyForEditor(cm, name, handle); 7140 7141 if (result == "multi") 7142 { cm.state.keySeq = name; } 7143 if (result == "handled") 7144 { signalLater(cm, "keyHandled", cm, name, e); } 7145 7146 if (result == "handled" || result == "multi") { 7147 e_preventDefault(e); 7148 restartBlink(cm); 7149 } 7150 7151 if (seq && !result && /\'$/.test(name)) { 7152 e_preventDefault(e); 7153 return true 7154 } 7155 return !!result 7156 } 7157 7158 // Handle a key from the keydown event. 7159 function handleKeyBinding(cm, e) { 7160 var name = keyName(e, true); 7161 if (!name) { return false } 7162 7163 if (e.shiftKey && !cm.state.keySeq) { 7164 // First try to resolve full name (including 'Shift-'). Failing 7165 // that, see if there is a cursor-motion command (starting with 7166 // 'go') bound to the keyname without 'Shift-'. 7167 return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) 7168 || dispatchKey(cm, name, e, function (b) { 7169 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) 7170 { return doHandleBinding(cm, b) } 7171 }) 7172 } else { 7173 return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) 7174 } 7175 } 7176 7177 // Handle a key from the keypress event 7178 function handleCharBinding(cm, e, ch) { 7179 return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) 7180 } 7181 7182 var lastStoppedKey = null; 7183 function onKeyDown(e) { 7184 var cm = this; 7185 cm.curOp.focus = activeElt(); 7186 if (signalDOMEvent(cm, e)) { return } 7187 // IE does strange things with escape. 7188 if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } 7189 var code = e.keyCode; 7190 cm.display.shift = code == 16 || e.shiftKey; 7191 var handled = handleKeyBinding(cm, e); 7192 if (presto) { 7193 lastStoppedKey = handled ? code : null; 7194 // Opera has no cut event... we try to at least catch the key combo 7195 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 7196 { cm.replaceSelection("", null, "cut"); } 7197 } 7198 7199 // Turn mouse into crosshair when Alt is held on Mac. 7200 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) 7201 { showCrossHair(cm); } 7202 } 7203 7204 function showCrossHair(cm) { 7205 var lineDiv = cm.display.lineDiv; 7206 addClass(lineDiv, "CodeMirror-crosshair"); 7207 7208 function up(e) { 7209 if (e.keyCode == 18 || !e.altKey) { 7210 rmClass(lineDiv, "CodeMirror-crosshair"); 7211 off(document, "keyup", up); 7212 off(document, "mouseover", up); 7213 } 7214 } 7215 on(document, "keyup", up); 7216 on(document, "mouseover", up); 7217 } 7218 7219 function onKeyUp(e) { 7220 if (e.keyCode == 16) { this.doc.sel.shift = false; } 7221 signalDOMEvent(this, e); 7222 } 7223 7224 function onKeyPress(e) { 7225 var cm = this; 7226 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } 7227 var keyCode = e.keyCode, charCode = e.charCode; 7228 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} 7229 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } 7230 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 7231 // Some browsers fire keypress events for backspace 7232 if (ch == "\x08") { return } 7233 if (handleCharBinding(cm, e, ch)) { return } 7234 cm.display.input.onKeyPress(e); 7235 } 7236 7237 var DOUBLECLICK_DELAY = 400; 7238 7239 var PastClick = function(time, pos, button) { 7240 this.time = time; 7241 this.pos = pos; 7242 this.button = button; 7243 }; 7244 7245 PastClick.prototype.compare = function (time, pos, button) { 7246 return this.time + DOUBLECLICK_DELAY > time && 7247 cmp(pos, this.pos) == 0 && button == this.button 7248 }; 7249 7250 var lastClick; 7251 var lastDoubleClick; 7252 function clickRepeat(pos, button) { 7253 var now = +new Date; 7254 if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { 7255 lastClick = lastDoubleClick = null; 7256 return "triple" 7257 } else if (lastClick && lastClick.compare(now, pos, button)) { 7258 lastDoubleClick = new PastClick(now, pos, button); 7259 lastClick = null; 7260 return "double" 7261 } else { 7262 lastClick = new PastClick(now, pos, button); 7263 lastDoubleClick = null; 7264 return "single" 7265 } 7266 } 7267 7268 // A mouse down can be a single click, double click, triple click, 7269 // start of selection drag, start of text drag, new cursor 7270 // (ctrl-click), rectangle drag (alt-drag), or xwin 7271 // middle-click-paste. Or it might be a click on something we should 7272 // not interfere with, such as a scrollbar or widget. 7273 function onMouseDown(e) { 7274 var cm = this, display = cm.display; 7275 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } 7276 display.input.ensurePolled(); 7277 display.shift = e.shiftKey; 7278 7279 if (eventInWidget(display, e)) { 7280 if (!webkit) { 7281 // Briefly turn off draggability, to allow widgets to do 7282 // normal dragging things. 7283 display.scroller.draggable = false; 7284 setTimeout(function () { return display.scroller.draggable = true; }, 100); 7285 } 7286 return 7287 } 7288 if (clickInGutter(cm, e)) { return } 7289 var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; 7290 window.focus(); 7291 7292 // #3261: make sure, that we're not starting a second selection 7293 if (button == 1 && cm.state.selectingText) 7294 { cm.state.selectingText(e); } 7295 7296 if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } 7297 7298 if (button == 1) { 7299 if (pos) { leftButtonDown(cm, pos, repeat, e); } 7300 else if (e_target(e) == display.scroller) { e_preventDefault(e); } 7301 } else if (button == 2) { 7302 if (pos) { extendSelection(cm.doc, pos); } 7303 setTimeout(function () { return display.input.focus(); }, 20); 7304 } else if (button == 3) { 7305 if (captureRightClick) { onContextMenu(cm, e); } 7306 else { delayBlurEvent(cm); } 7307 } 7308 } 7309 7310 function handleMappedButton(cm, button, pos, repeat, event) { 7311 var name = "Click"; 7312 if (repeat == "double") { name = "Double" + name; } 7313 else if (repeat == "triple") { name = "Triple" + name; } 7314 name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; 7315 7316 return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { 7317 if (typeof bound == "string") { bound = commands[bound]; } 7318 if (!bound) { return false } 7319 var done = false; 7320 try { 7321 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 7322 done = bound(cm, pos) != Pass; 7323 } finally { 7324 cm.state.suppressEdits = false; 7325 } 7326 return done 7327 }) 7328 } 7329 7330 function configureMouse(cm, repeat, event) { 7331 var option = cm.getOption("configureMouse"); 7332 var value = option ? option(cm, repeat, event) : {}; 7333 if (value.unit == null) { 7334 var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; 7335 value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; 7336 } 7337 if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } 7338 if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } 7339 if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } 7340 return value 7341 } 7342 7343 function leftButtonDown(cm, pos, repeat, event) { 7344 if (ie) { setTimeout(bind(ensureFocus, cm), 0); } 7345 else { cm.curOp.focus = activeElt(); } 7346 7347 var behavior = configureMouse(cm, repeat, event); 7348 7349 var sel = cm.doc.sel, contained; 7350 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && 7351 repeat == "single" && (contained = sel.contains(pos)) > -1 && 7352 (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && 7353 (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) 7354 { leftButtonStartDrag(cm, event, pos, behavior); } 7355 else 7356 { leftButtonSelect(cm, event, pos, behavior); } 7357 } 7358 7359 // Start a text drag. When it ends, see if any dragging actually 7360 // happen, and treat as a click if it didn't. 7361 function leftButtonStartDrag(cm, event, pos, behavior) { 7362 var display = cm.display, moved = false; 7363 var dragEnd = operation(cm, function (e) { 7364 if (webkit) { display.scroller.draggable = false; } 7365 cm.state.draggingText = false; 7366 off(document, "mouseup", dragEnd); 7367 off(document, "mousemove", mouseMove); 7368 off(display.scroller, "dragstart", dragStart); 7369 off(display.scroller, "drop", dragEnd); 7370 if (!moved) { 7371 e_preventDefault(e); 7372 if (!behavior.addNew) 7373 { extendSelection(cm.doc, pos, null, null, behavior.extend); } 7374 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) 7375 if (webkit || ie && ie_version == 9) 7376 { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); } 7377 else 7378 { display.input.focus(); } 7379 } 7380 }); 7381 var mouseMove = function(e2) { 7382 moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; 7383 }; 7384 var dragStart = function () { return moved = true; }; 7385 // Let the drag handler handle this. 7386 if (webkit) { display.scroller.draggable = true; } 7387 cm.state.draggingText = dragEnd; 7388 dragEnd.copy = !behavior.moveOnDrag; 7389 // IE's approach to draggable 7390 if (display.scroller.dragDrop) { display.scroller.dragDrop(); } 7391 on(document, "mouseup", dragEnd); 7392 on(document, "mousemove", mouseMove); 7393 on(display.scroller, "dragstart", dragStart); 7394 on(display.scroller, "drop", dragEnd); 7395 7396 delayBlurEvent(cm); 7397 setTimeout(function () { return display.input.focus(); }, 20); 7398 } 7399 7400 function rangeForUnit(cm, pos, unit) { 7401 if (unit == "char") { return new Range(pos, pos) } 7402 if (unit == "word") { return cm.findWordAt(pos) } 7403 if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } 7404 var result = unit(cm, pos); 7405 return new Range(result.from, result.to) 7406 } 7407 7408 // Normal selection, as opposed to text dragging. 7409 function leftButtonSelect(cm, event, start, behavior) { 7410 var display = cm.display, doc = cm.doc; 7411 e_preventDefault(event); 7412 7413 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; 7414 if (behavior.addNew && !behavior.extend) { 7415 ourIndex = doc.sel.contains(start); 7416 if (ourIndex > -1) 7417 { ourRange = ranges[ourIndex]; } 7418 else 7419 { ourRange = new Range(start, start); } 7420 } else { 7421 ourRange = doc.sel.primary(); 7422 ourIndex = doc.sel.primIndex; 7423 } 7424 7425 if (behavior.unit == "rectangle") { 7426 if (!behavior.addNew) { ourRange = new Range(start, start); } 7427 start = posFromMouse(cm, event, true, true); 7428 ourIndex = -1; 7429 } else { 7430 var range$$1 = rangeForUnit(cm, start, behavior.unit); 7431 if (behavior.extend) 7432 { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } 7433 else 7434 { ourRange = range$$1; } 7435 } 7436 7437 if (!behavior.addNew) { 7438 ourIndex = 0; 7439 setSelection(doc, new Selection([ourRange], 0), sel_mouse); 7440 startSel = doc.sel; 7441 } else if (ourIndex == -1) { 7442 ourIndex = ranges.length; 7443 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), 7444 {scroll: false, origin: "*mouse"}); 7445 } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { 7446 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), 7447 {scroll: false, origin: "*mouse"}); 7448 startSel = doc.sel; 7449 } else { 7450 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); 7451 } 7452 7453 var lastPos = start; 7454 function extendTo(pos) { 7455 if (cmp(lastPos, pos) == 0) { return } 7456 lastPos = pos; 7457 7458 if (behavior.unit == "rectangle") { 7459 var ranges = [], tabSize = cm.options.tabSize; 7460 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); 7461 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); 7462 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); 7463 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); 7464 line <= end; line++) { 7465 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); 7466 if (left == right) 7467 { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } 7468 else if (text.length > leftPos) 7469 { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } 7470 } 7471 if (!ranges.length) { ranges.push(new Range(start, start)); } 7472 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), 7473 {origin: "*mouse", scroll: false}); 7474 cm.scrollIntoView(pos); 7475 } else { 7476 var oldRange = ourRange; 7477 var range$$1 = rangeForUnit(cm, pos, behavior.unit); 7478 var anchor = oldRange.anchor, head; 7479 if (cmp(range$$1.anchor, anchor) > 0) { 7480 head = range$$1.head; 7481 anchor = minPos(oldRange.from(), range$$1.anchor); 7482 } else { 7483 head = range$$1.anchor; 7484 anchor = maxPos(oldRange.to(), range$$1.head); 7485 } 7486 var ranges$1 = startSel.ranges.slice(0); 7487 ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); 7488 setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse); 7489 } 7490 } 7491 7492 var editorSize = display.wrapper.getBoundingClientRect(); 7493 // Used to ensure timeout re-tries don't fire when another extend 7494 // happened in the meantime (clearTimeout isn't reliable -- at 7495 // least on Chrome, the timeouts still happen even when cleared, 7496 // if the clear happens after their scheduled firing time). 7497 var counter = 0; 7498 7499 function extend(e) { 7500 var curCount = ++counter; 7501 var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); 7502 if (!cur) { return } 7503 if (cmp(cur, lastPos) != 0) { 7504 cm.curOp.focus = activeElt(); 7505 extendTo(cur); 7506 var visible = visibleLines(display, doc); 7507 if (cur.line >= visible.to || cur.line < visible.from) 7508 { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } 7509 } else { 7510 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 7511 if (outside) { setTimeout(operation(cm, function () { 7512 if (counter != curCount) { return } 7513 display.scroller.scrollTop += outside; 7514 extend(e); 7515 }), 50); } 7516 } 7517 } 7518 7519 function done(e) { 7520 cm.state.selectingText = false; 7521 counter = Infinity; 7522 e_preventDefault(e); 7523 display.input.focus(); 7524 off(document, "mousemove", move); 7525 off(document, "mouseup", up); 7526 doc.history.lastSelOrigin = null; 7527 } 7528 7529 var move = operation(cm, function (e) { 7530 if (!e_button(e)) { done(e); } 7531 else { extend(e); } 7532 }); 7533 var up = operation(cm, done); 7534 cm.state.selectingText = up; 7535 on(document, "mousemove", move); 7536 on(document, "mouseup", up); 7537 } 7538 7539 // Used when mouse-selecting to adjust the anchor to the proper side 7540 // of a bidi jump depending on the visual position of the head. 7541 function bidiSimplify(cm, range$$1) { 7542 var anchor = range$$1.anchor; 7543 var head = range$$1.head; 7544 var anchorLine = getLine(cm.doc, anchor.line); 7545 if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } 7546 var order = getOrder(anchorLine); 7547 if (!order) { return range$$1 } 7548 var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; 7549 if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } 7550 var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); 7551 if (boundary == 0 || boundary == order.length) { return range$$1 } 7552 7553 // Compute the relative visual position of the head compared to the 7554 // anchor (<0 is to the left, >0 to the right) 7555 var leftSide; 7556 if (head.line != anchor.line) { 7557 leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; 7558 } else { 7559 var headIndex = getBidiPartAt(order, head.ch, head.sticky); 7560 var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); 7561 if (headIndex == boundary - 1 || headIndex == boundary) 7562 { leftSide = dir < 0; } 7563 else 7564 { leftSide = dir > 0; } 7565 } 7566 7567 var usePart = order[boundary + (leftSide ? -1 : 0)]; 7568 var from = leftSide == (usePart.level == 1); 7569 var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; 7570 return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) 7571 } 7572 7573 7574 // Determines whether an event happened in the gutter, and fires the 7575 // handlers for the corresponding event. 7576 function gutterEvent(cm, e, type, prevent) { 7577 var mX, mY; 7578 if (e.touches) { 7579 mX = e.touches[0].clientX; 7580 mY = e.touches[0].clientY; 7581 } else { 7582 try { mX = e.clientX; mY = e.clientY; } 7583 catch(e) { return false } 7584 } 7585 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } 7586 if (prevent) { e_preventDefault(e); } 7587 7588 var display = cm.display; 7589 var lineBox = display.lineDiv.getBoundingClientRect(); 7590 7591 if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } 7592 mY -= lineBox.top - display.viewOffset; 7593 7594 for (var i = 0; i < cm.options.gutters.length; ++i) { 7595 var g = display.gutters.childNodes[i]; 7596 if (g && g.getBoundingClientRect().right >= mX) { 7597 var line = lineAtHeight(cm.doc, mY); 7598 var gutter = cm.options.gutters[i]; 7599 signal(cm, type, cm, line, gutter, e); 7600 return e_defaultPrevented(e) 7601 } 7602 } 7603 } 7604 7605 function clickInGutter(cm, e) { 7606 return gutterEvent(cm, e, "gutterClick", true) 7607 } 7608 7609 // CONTEXT MENU HANDLING 7610 7611 // To make the context menu work, we need to briefly unhide the 7612 // textarea (making it as unobtrusive as possible) to let the 7613 // right-click take effect on it. 7614 function onContextMenu(cm, e) { 7615 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } 7616 if (signalDOMEvent(cm, e, "contextmenu")) { return } 7617 cm.display.input.onContextMenu(e); 7618 } 7619 7620 function contextMenuInGutter(cm, e) { 7621 if (!hasHandler(cm, "gutterContextMenu")) { return false } 7622 return gutterEvent(cm, e, "gutterContextMenu", false) 7623 } 7624 7625 function themeChanged(cm) { 7626 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + 7627 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); 7628 clearCaches(cm); 7629 } 7630 7631 var Init = {toString: function(){return "CodeMirror.Init"}}; 7632 7633 var defaults = {}; 7634 var optionHandlers = {}; 7635 7636 function defineOptions(CodeMirror) { 7637 var optionHandlers = CodeMirror.optionHandlers; 7638 7639 function option(name, deflt, handle, notOnInit) { 7640 CodeMirror.defaults[name] = deflt; 7641 if (handle) { optionHandlers[name] = 7642 notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } 7643 } 7644 7645 CodeMirror.defineOption = option; 7646 7647 // Passed to option handlers when there is no old value. 7648 CodeMirror.Init = Init; 7649 7650 // These two are, on init, called from the constructor because they 7651 // have to be initialized before the editor can start at all. 7652 option("value", "", function (cm, val) { return cm.setValue(val); }, true); 7653 option("mode", null, function (cm, val) { 7654 cm.doc.modeOption = val; 7655 loadMode(cm); 7656 }, true); 7657 7658 option("indentUnit", 2, loadMode, true); 7659 option("indentWithTabs", false); 7660 option("smartIndent", true); 7661 option("tabSize", 4, function (cm) { 7662 resetModeState(cm); 7663 clearCaches(cm); 7664 regChange(cm); 7665 }, true); 7666 option("lineSeparator", null, function (cm, val) { 7667 cm.doc.lineSep = val; 7668 if (!val) { return } 7669 var newBreaks = [], lineNo = cm.doc.first; 7670 cm.doc.iter(function (line) { 7671 for (var pos = 0;;) { 7672 var found = line.text.indexOf(val, pos); 7673 if (found == -1) { break } 7674 pos = found + val.length; 7675 newBreaks.push(Pos(lineNo, found)); 7676 } 7677 lineNo++; 7678 }); 7679 for (var i = newBreaks.length - 1; i >= 0; i--) 7680 { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } 7681 }); 7682 option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { 7683 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); 7684 if (old != Init) { cm.refresh(); } 7685 }); 7686 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); 7687 option("electricChars", true); 7688 option("inputStyle", mobile ? "contenteditable" : "textarea", function () { 7689 throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME 7690 }, true); 7691 option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); 7692 option("rtlMoveVisually", !windows); 7693 option("wholeLineUpdateBefore", true); 7694 7695 option("theme", "default", function (cm) { 7696 themeChanged(cm); 7697 guttersChanged(cm); 7698 }, true); 7699 option("keyMap", "default", function (cm, val, old) { 7700 var next = getKeyMap(val); 7701 var prev = old != Init && getKeyMap(old); 7702 if (prev && prev.detach) { prev.detach(cm, next); } 7703 if (next.attach) { next.attach(cm, prev || null); } 7704 }); 7705 option("extraKeys", null); 7706 option("configureMouse", null); 7707 7708 option("lineWrapping", false, wrappingChanged, true); 7709 option("gutters", [], function (cm) { 7710 setGuttersForLineNumbers(cm.options); 7711 guttersChanged(cm); 7712 }, true); 7713 option("fixedGutter", true, function (cm, val) { 7714 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 7715 cm.refresh(); 7716 }, true); 7717 option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); 7718 option("scrollbarStyle", "native", function (cm) { 7719 initScrollbars(cm); 7720 updateScrollbars(cm); 7721 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); 7722 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); 7723 }, true); 7724 option("lineNumbers", false, function (cm) { 7725 setGuttersForLineNumbers(cm.options); 7726 guttersChanged(cm); 7727 }, true); 7728 option("firstLineNumber", 1, guttersChanged, true); 7729 option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true); 7730 option("showCursorWhenSelecting", false, updateSelection, true); 7731 7732 option("resetSelectionOnContextMenu", true); 7733 option("lineWiseCopyCut", true); 7734 option("pasteLinesPerSelection", true); 7735 7736 option("readOnly", false, function (cm, val) { 7737 if (val == "nocursor") { 7738 onBlur(cm); 7739 cm.display.input.blur(); 7740 } 7741 cm.display.input.readOnlyChanged(val); 7742 }); 7743 option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); 7744 option("dragDrop", true, dragDropChanged); 7745 option("allowDropFileTypes", null); 7746 7747 option("cursorBlinkRate", 530); 7748 option("cursorScrollMargin", 0); 7749 option("cursorHeight", 1, updateSelection, true); 7750 option("singleCursorHeightPerLine", true, updateSelection, true); 7751 option("workTime", 100); 7752 option("workDelay", 100); 7753 option("flattenSpans", true, resetModeState, true); 7754 option("addModeClass", false, resetModeState, true); 7755 option("pollInterval", 100); 7756 option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); 7757 option("historyEventDelay", 1250); 7758 option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); 7759 option("maxHighlightLength", 10000, resetModeState, true); 7760 option("moveInputWithCursor", true, function (cm, val) { 7761 if (!val) { cm.display.input.resetPosition(); } 7762 }); 7763 7764 option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); 7765 option("autofocus", null); 7766 option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); 7767 } 7768 7769 function guttersChanged(cm) { 7770 updateGutters(cm); 7771 regChange(cm); 7772 alignHorizontally(cm); 7773 } 7774 7775 function dragDropChanged(cm, value, old) { 7776 var wasOn = old && old != Init; 7777 if (!value != !wasOn) { 7778 var funcs = cm.display.dragFunctions; 7779 var toggle = value ? on : off; 7780 toggle(cm.display.scroller, "dragstart", funcs.start); 7781 toggle(cm.display.scroller, "dragenter", funcs.enter); 7782 toggle(cm.display.scroller, "dragover", funcs.over); 7783 toggle(cm.display.scroller, "dragleave", funcs.leave); 7784 toggle(cm.display.scroller, "drop", funcs.drop); 7785 } 7786 } 7787 7788 function wrappingChanged(cm) { 7789 if (cm.options.lineWrapping) { 7790 addClass(cm.display.wrapper, "CodeMirror-wrap"); 7791 cm.display.sizer.style.minWidth = ""; 7792 cm.display.sizerWidth = null; 7793 } else { 7794 rmClass(cm.display.wrapper, "CodeMirror-wrap"); 7795 findMaxLine(cm); 7796 } 7797 estimateLineHeights(cm); 7798 regChange(cm); 7799 clearCaches(cm); 7800 setTimeout(function () { return updateScrollbars(cm); }, 100); 7801 } 7802 7803 // A CodeMirror instance represents an editor. This is the object 7804 // that user code is usually dealing with. 7805 7806 function CodeMirror$1(place, options) { 7807 var this$1 = this; 7808 7809 if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) } 7810 7811 this.options = options = options ? copyObj(options) : {}; 7812 // Determine effective options based on given values and defaults. 7813 copyObj(defaults, options, false); 7814 setGuttersForLineNumbers(options); 7815 7816 var doc = options.value; 7817 if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } 7818 this.doc = doc; 7819 7820 var input = new CodeMirror$1.inputStyles[options.inputStyle](this); 7821 var display = this.display = new Display(place, doc, input); 7822 display.wrapper.CodeMirror = this; 7823 updateGutters(this); 7824 themeChanged(this); 7825 if (options.lineWrapping) 7826 { this.display.wrapper.className += " CodeMirror-wrap"; } 7827 initScrollbars(this); 7828 7829 this.state = { 7830 keyMaps: [], // stores maps added by addKeyMap 7831 overlays: [], // highlighting overlays, as added by addOverlay 7832 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info 7833 overwrite: false, 7834 delayingBlurEvent: false, 7835 focused: false, 7836 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode 7837 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll 7838 selectingText: false, 7839 draggingText: false, 7840 highlight: new Delayed(), // stores highlight worker timeout 7841 keySeq: null, // Unfinished key sequence 7842 specialChars: null 7843 }; 7844 7845 if (options.autofocus && !mobile) { display.input.focus(); } 7846 7847 // Override magic textarea content restore that IE sometimes does 7848 // on our hidden textarea on reload 7849 if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } 7850 7851 registerEventHandlers(this); 7852 ensureGlobalHandlers(); 7853 7854 startOperation(this); 7855 this.curOp.forceUpdate = true; 7856 attachDoc(this, doc); 7857 7858 if ((options.autofocus && !mobile) || this.hasFocus()) 7859 { setTimeout(bind(onFocus, this), 20); } 7860 else 7861 { onBlur(this); } 7862 7863 for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) 7864 { optionHandlers[opt](this$1, options[opt], Init); } } 7865 maybeUpdateLineNumberWidth(this); 7866 if (options.finishInit) { options.finishInit(this); } 7867 for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } 7868 endOperation(this); 7869 // Suppress optimizelegibility in Webkit, since it breaks text 7870 // measuring on line wrapping boundaries. 7871 if (webkit && options.lineWrapping && 7872 getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") 7873 { display.lineDiv.style.textRendering = "auto"; } 7874 } 7875 7876 // The default configuration options. 7877 CodeMirror$1.defaults = defaults; 7878 // Functions to run when options are changed. 7879 CodeMirror$1.optionHandlers = optionHandlers; 7880 7881 // Attach the necessary event handlers when initializing the editor 7882 function registerEventHandlers(cm) { 7883 var d = cm.display; 7884 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 7885 // Older IE's will not fire a second mousedown for a double click 7886 if (ie && ie_version < 11) 7887 { on(d.scroller, "dblclick", operation(cm, function (e) { 7888 if (signalDOMEvent(cm, e)) { return } 7889 var pos = posFromMouse(cm, e); 7890 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } 7891 e_preventDefault(e); 7892 var word = cm.findWordAt(pos); 7893 extendSelection(cm.doc, word.anchor, word.head); 7894 })); } 7895 else 7896 { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } 7897 // Some browsers fire contextmenu *after* opening the menu, at 7898 // which point we can't mess with it anymore. Context menu is 7899 // handled in onMouseDown for these browsers. 7900 if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); } 7901 7902 // Used to suppress mouse event handling when a touch happens 7903 var touchFinished, prevTouch = {end: 0}; 7904 function finishTouch() { 7905 if (d.activeTouch) { 7906 touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); 7907 prevTouch = d.activeTouch; 7908 prevTouch.end = +new Date; 7909 } 7910 } 7911 function isMouseLikeTouchEvent(e) { 7912 if (e.touches.length != 1) { return false } 7913 var touch = e.touches[0]; 7914 return touch.radiusX <= 1 && touch.radiusY <= 1 7915 } 7916 function farAway(touch, other) { 7917 if (other.left == null) { return true } 7918 var dx = other.left - touch.left, dy = other.top - touch.top; 7919 return dx * dx + dy * dy > 20 * 20 7920 } 7921 on(d.scroller, "touchstart", function (e) { 7922 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { 7923 d.input.ensurePolled(); 7924 clearTimeout(touchFinished); 7925 var now = +new Date; 7926 d.activeTouch = {start: now, moved: false, 7927 prev: now - prevTouch.end <= 300 ? prevTouch : null}; 7928 if (e.touches.length == 1) { 7929 d.activeTouch.left = e.touches[0].pageX; 7930 d.activeTouch.top = e.touches[0].pageY; 7931 } 7932 } 7933 }); 7934 on(d.scroller, "touchmove", function () { 7935 if (d.activeTouch) { d.activeTouch.moved = true; } 7936 }); 7937 on(d.scroller, "touchend", function (e) { 7938 var touch = d.activeTouch; 7939 if (touch && !eventInWidget(d, e) && touch.left != null && 7940 !touch.moved && new Date - touch.start < 300) { 7941 var pos = cm.coordsChar(d.activeTouch, "page"), range; 7942 if (!touch.prev || farAway(touch, touch.prev)) // Single tap 7943 { range = new Range(pos, pos); } 7944 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap 7945 { range = cm.findWordAt(pos); } 7946 else // Triple tap 7947 { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } 7948 cm.setSelection(range.anchor, range.head); 7949 cm.focus(); 7950 e_preventDefault(e); 7951 } 7952 finishTouch(); 7953 }); 7954 on(d.scroller, "touchcancel", finishTouch); 7955 7956 // Sync scrolling between fake scrollbars and real scrollable 7957 // area, ensure viewport is updated when scrolling. 7958 on(d.scroller, "scroll", function () { 7959 if (d.scroller.clientHeight) { 7960 updateScrollTop(cm, d.scroller.scrollTop); 7961 setScrollLeft(cm, d.scroller.scrollLeft, true); 7962 signal(cm, "scroll", cm); 7963 } 7964 }); 7965 7966 // Listen to wheel events in order to try and update the viewport on time. 7967 on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); 7968 on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); 7969 7970 // Prevent wrapper from ever scrolling 7971 on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 7972 7973 d.dragFunctions = { 7974 enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, 7975 over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, 7976 start: function (e) { return onDragStart(cm, e); }, 7977 drop: operation(cm, onDrop), 7978 leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} 7979 }; 7980 7981 var inp = d.input.getField(); 7982 on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); 7983 on(inp, "keydown", operation(cm, onKeyDown)); 7984 on(inp, "keypress", operation(cm, onKeyPress)); 7985 on(inp, "focus", function (e) { return onFocus(cm, e); }); 7986 on(inp, "blur", function (e) { return onBlur(cm, e); }); 7987 } 7988 7989 var initHooks = []; 7990 CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); }; 7991 7992 // Indent the given line. The how parameter can be "smart", 7993 // "add"/null, "subtract", or "prev". When aggressive is false 7994 // (typically set to true for forced single-line indents), empty 7995 // lines are not indented, and places where the mode returns Pass 7996 // are left alone. 7997 function indentLine(cm, n, how, aggressive) { 7998 var doc = cm.doc, state; 7999 if (how == null) { how = "add"; } 8000 if (how == "smart") { 8001 // Fall back to "prev" when the mode doesn't have an indentation 8002 // method. 8003 if (!doc.mode.indent) { how = "prev"; } 8004 else { state = getContextBefore(cm, n).state; } 8005 } 8006 8007 var tabSize = cm.options.tabSize; 8008 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 8009 if (line.stateAfter) { line.stateAfter = null; } 8010 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 8011 if (!aggressive && !/\S/.test(line.text)) { 8012 indentation = 0; 8013 how = "not"; 8014 } else if (how == "smart") { 8015 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 8016 if (indentation == Pass || indentation > 150) { 8017 if (!aggressive) { return } 8018 how = "prev"; 8019 } 8020 } 8021 if (how == "prev") { 8022 if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } 8023 else { indentation = 0; } 8024 } else if (how == "add") { 8025 indentation = curSpace + cm.options.indentUnit; 8026 } else if (how == "subtract") { 8027 indentation = curSpace - cm.options.indentUnit; 8028 } else if (typeof how == "number") { 8029 indentation = curSpace + how; 8030 } 8031 indentation = Math.max(0, indentation); 8032 8033 var indentString = "", pos = 0; 8034 if (cm.options.indentWithTabs) 8035 { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } 8036 if (pos < indentation) { indentString += spaceStr(indentation - pos); } 8037 8038 if (indentString != curSpaceString) { 8039 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 8040 line.stateAfter = null; 8041 return true 8042 } else { 8043 // Ensure that, if the cursor was in the whitespace at the start 8044 // of the line, it is moved to the end of that space. 8045 for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { 8046 var range = doc.sel.ranges[i$1]; 8047 if (range.head.line == n && range.head.ch < curSpaceString.length) { 8048 var pos$1 = Pos(n, curSpaceString.length); 8049 replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); 8050 break 8051 } 8052 } 8053 } 8054 } 8055 8056 // This will be set to a {lineWise: bool, text: [string]} object, so 8057 // that, when pasting, we know what kind of selections the copied 8058 // text was made out of. 8059 var lastCopied = null; 8060 8061 function setLastCopied(newLastCopied) { 8062 lastCopied = newLastCopied; 8063 } 8064 8065 function applyTextInput(cm, inserted, deleted, sel, origin) { 8066 var doc = cm.doc; 8067 cm.display.shift = false; 8068 if (!sel) { sel = doc.sel; } 8069 8070 var paste = cm.state.pasteIncoming || origin == "paste"; 8071 var textLines = splitLinesAuto(inserted), multiPaste = null; 8072 // When pasing N lines into N selections, insert one line per selection 8073 if (paste && sel.ranges.length > 1) { 8074 if (lastCopied && lastCopied.text.join("\n") == inserted) { 8075 if (sel.ranges.length % lastCopied.text.length == 0) { 8076 multiPaste = []; 8077 for (var i = 0; i < lastCopied.text.length; i++) 8078 { multiPaste.push(doc.splitLines(lastCopied.text[i])); } 8079 } 8080 } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { 8081 multiPaste = map(textLines, function (l) { return [l]; }); 8082 } 8083 } 8084 8085 var updateInput; 8086 // Normal behavior is to insert the new text into every selection 8087 for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { 8088 var range$$1 = sel.ranges[i$1]; 8089 var from = range$$1.from(), to = range$$1.to(); 8090 if (range$$1.empty()) { 8091 if (deleted && deleted > 0) // Handle deletion 8092 { from = Pos(from.line, from.ch - deleted); } 8093 else if (cm.state.overwrite && !paste) // Handle overwrite 8094 { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } 8095 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) 8096 { from = to = Pos(from.line, 0); } 8097 } 8098 updateInput = cm.curOp.updateInput; 8099 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, 8100 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; 8101 makeChange(cm.doc, changeEvent); 8102 signalLater(cm, "inputRead", cm, changeEvent); 8103 } 8104 if (inserted && !paste) 8105 { triggerElectric(cm, inserted); } 8106 8107 ensureCursorVisible(cm); 8108 cm.curOp.updateInput = updateInput; 8109 cm.curOp.typing = true; 8110 cm.state.pasteIncoming = cm.state.cutIncoming = false; 8111 } 8112 8113 function handlePaste(e, cm) { 8114 var pasted = e.clipboardData && e.clipboardData.getData("Text"); 8115 if (pasted) { 8116 e.preventDefault(); 8117 if (!cm.isReadOnly() && !cm.options.disableInput) 8118 { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } 8119 return true 8120 } 8121 } 8122 8123 function triggerElectric(cm, inserted) { 8124 // When an 'electric' character is inserted, immediately trigger a reindent 8125 if (!cm.options.electricChars || !cm.options.smartIndent) { return } 8126 var sel = cm.doc.sel; 8127 8128 for (var i = sel.ranges.length - 1; i >= 0; i--) { 8129 var range$$1 = sel.ranges[i]; 8130 if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } 8131 var mode = cm.getModeAt(range$$1.head); 8132 var indented = false; 8133 if (mode.electricChars) { 8134 for (var j = 0; j < mode.electricChars.length; j++) 8135 { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { 8136 indented = indentLine(cm, range$$1.head.line, "smart"); 8137 break 8138 } } 8139 } else if (mode.electricInput) { 8140 if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) 8141 { indented = indentLine(cm, range$$1.head.line, "smart"); } 8142 } 8143 if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } 8144 } 8145 } 8146 8147 function copyableRanges(cm) { 8148 var text = [], ranges = []; 8149 for (var i = 0; i < cm.doc.sel.ranges.length; i++) { 8150 var line = cm.doc.sel.ranges[i].head.line; 8151 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; 8152 ranges.push(lineRange); 8153 text.push(cm.getRange(lineRange.anchor, lineRange.head)); 8154 } 8155 return {text: text, ranges: ranges} 8156 } 8157 8158 function disableBrowserMagic(field, spellcheck) { 8159 field.setAttribute("autocorrect", "off"); 8160 field.setAttribute("autocapitalize", "off"); 8161 field.setAttribute("spellcheck", !!spellcheck); 8162 } 8163 8164 function hiddenTextarea() { 8165 var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); 8166 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 8167 // The textarea is kept positioned near the cursor to prevent the 8168 // fact that it'll be scrolled into view on input from scrolling 8169 // our fake cursor out of view. On webkit, when wrap=off, paste is 8170 // very slow. So make the area wide instead. 8171 if (webkit) { te.style.width = "1000px"; } 8172 else { te.setAttribute("wrap", "off"); } 8173 // If border: 0; -- iOS fails to open keyboard (issue #1287) 8174 if (ios) { te.style.border = "1px solid black"; } 8175 disableBrowserMagic(te); 8176 return div 8177 } 8178 8179 // The publicly visible API. Note that methodOp(f) means 8180 // 'wrap f in an operation, performed on its `this` parameter'. 8181 8182 // This is not the complete set of editor methods. Most of the 8183 // methods defined on the Doc type are also injected into 8184 // CodeMirror.prototype, for backwards compatibility and 8185 // convenience. 8186 8187 var addEditorMethods = function(CodeMirror) { 8188 var optionHandlers = CodeMirror.optionHandlers; 8189 8190 var helpers = CodeMirror.helpers = {}; 8191 8192 CodeMirror.prototype = { 8193 constructor: CodeMirror, 8194 focus: function(){window.focus(); this.display.input.focus();}, 8195 8196 setOption: function(option, value) { 8197 var options = this.options, old = options[option]; 8198 if (options[option] == value && option != "mode") { return } 8199 options[option] = value; 8200 if (optionHandlers.hasOwnProperty(option)) 8201 { operation(this, optionHandlers[option])(this, value, old); } 8202 signal(this, "optionChange", this, option); 8203 }, 8204 8205 getOption: function(option) {return this.options[option]}, 8206 getDoc: function() {return this.doc}, 8207 8208 addKeyMap: function(map$$1, bottom) { 8209 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); 8210 }, 8211 removeKeyMap: function(map$$1) { 8212 var maps = this.state.keyMaps; 8213 for (var i = 0; i < maps.length; ++i) 8214 { if (maps[i] == map$$1 || maps[i].name == map$$1) { 8215 maps.splice(i, 1); 8216 return true 8217 } } 8218 }, 8219 8220 addOverlay: methodOp(function(spec, options) { 8221 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 8222 if (mode.startState) { throw new Error("Overlays may not be stateful.") } 8223 insertSorted(this.state.overlays, 8224 {mode: mode, modeSpec: spec, opaque: options && options.opaque, 8225 priority: (options && options.priority) || 0}, 8226 function (overlay) { return overlay.priority; }); 8227 this.state.modeGen++; 8228 regChange(this); 8229 }), 8230 removeOverlay: methodOp(function(spec) { 8231 var this$1 = this; 8232 8233 var overlays = this.state.overlays; 8234 for (var i = 0; i < overlays.length; ++i) { 8235 var cur = overlays[i].modeSpec; 8236 if (cur == spec || typeof spec == "string" && cur.name == spec) { 8237 overlays.splice(i, 1); 8238 this$1.state.modeGen++; 8239 regChange(this$1); 8240 return 8241 } 8242 } 8243 }), 8244 8245 indentLine: methodOp(function(n, dir, aggressive) { 8246 if (typeof dir != "string" && typeof dir != "number") { 8247 if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } 8248 else { dir = dir ? "add" : "subtract"; } 8249 } 8250 if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } 8251 }), 8252 indentSelection: methodOp(function(how) { 8253 var this$1 = this; 8254 8255 var ranges = this.doc.sel.ranges, end = -1; 8256 for (var i = 0; i < ranges.length; i++) { 8257 var range$$1 = ranges[i]; 8258 if (!range$$1.empty()) { 8259 var from = range$$1.from(), to = range$$1.to(); 8260 var start = Math.max(end, from.line); 8261 end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; 8262 for (var j = start; j < end; ++j) 8263 { indentLine(this$1, j, how); } 8264 var newRanges = this$1.doc.sel.ranges; 8265 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) 8266 { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } 8267 } else if (range$$1.head.line > end) { 8268 indentLine(this$1, range$$1.head.line, how, true); 8269 end = range$$1.head.line; 8270 if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } 8271 } 8272 } 8273 }), 8274 8275 // Fetch the parser token for a given character. Useful for hacks 8276 // that want to inspect the mode state (say, for completion). 8277 getTokenAt: function(pos, precise) { 8278 return takeToken(this, pos, precise) 8279 }, 8280 8281 getLineTokens: function(line, precise) { 8282 return takeToken(this, Pos(line), precise, true) 8283 }, 8284 8285 getTokenTypeAt: function(pos) { 8286 pos = clipPos(this.doc, pos); 8287 var styles = getLineStyles(this, getLine(this.doc, pos.line)); 8288 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; 8289 var type; 8290 if (ch == 0) { type = styles[2]; } 8291 else { for (;;) { 8292 var mid = (before + after) >> 1; 8293 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } 8294 else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } 8295 else { type = styles[mid * 2 + 2]; break } 8296 } } 8297 var cut = type ? type.indexOf("overlay ") : -1; 8298 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) 8299 }, 8300 8301 getModeAt: function(pos) { 8302 var mode = this.doc.mode; 8303 if (!mode.innerMode) { return mode } 8304 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode 8305 }, 8306 8307 getHelper: function(pos, type) { 8308 return this.getHelpers(pos, type)[0] 8309 }, 8310 8311 getHelpers: function(pos, type) { 8312 var this$1 = this; 8313 8314 var found = []; 8315 if (!helpers.hasOwnProperty(type)) { return found } 8316 var help = helpers[type], mode = this.getModeAt(pos); 8317 if (typeof mode[type] == "string") { 8318 if (help[mode[type]]) { found.push(help[mode[type]]); } 8319 } else if (mode[type]) { 8320 for (var i = 0; i < mode[type].length; i++) { 8321 var val = help[mode[type][i]]; 8322 if (val) { found.push(val); } 8323 } 8324 } else if (mode.helperType && help[mode.helperType]) { 8325 found.push(help[mode.helperType]); 8326 } else if (help[mode.name]) { 8327 found.push(help[mode.name]); 8328 } 8329 for (var i$1 = 0; i$1 < help._global.length; i$1++) { 8330 var cur = help._global[i$1]; 8331 if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) 8332 { found.push(cur.val); } 8333 } 8334 return found 8335 }, 8336 8337 getStateAfter: function(line, precise) { 8338 var doc = this.doc; 8339 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 8340 return getContextBefore(this, line + 1, precise).state 8341 }, 8342 8343 cursorCoords: function(start, mode) { 8344 var pos, range$$1 = this.doc.sel.primary(); 8345 if (start == null) { pos = range$$1.head; } 8346 else if (typeof start == "object") { pos = clipPos(this.doc, start); } 8347 else { pos = start ? range$$1.from() : range$$1.to(); } 8348 return cursorCoords(this, pos, mode || "page") 8349 }, 8350 8351 charCoords: function(pos, mode) { 8352 return charCoords(this, clipPos(this.doc, pos), mode || "page") 8353 }, 8354 8355 coordsChar: function(coords, mode) { 8356 coords = fromCoordSystem(this, coords, mode || "page"); 8357 return coordsChar(this, coords.left, coords.top) 8358 }, 8359 8360 lineAtHeight: function(height, mode) { 8361 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; 8362 return lineAtHeight(this.doc, height + this.display.viewOffset) 8363 }, 8364 heightAtLine: function(line, mode, includeWidgets) { 8365 var end = false, lineObj; 8366 if (typeof line == "number") { 8367 var last = this.doc.first + this.doc.size - 1; 8368 if (line < this.doc.first) { line = this.doc.first; } 8369 else if (line > last) { line = last; end = true; } 8370 lineObj = getLine(this.doc, line); 8371 } else { 8372 lineObj = line; 8373 } 8374 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + 8375 (end ? this.doc.height - heightAtLine(lineObj) : 0) 8376 }, 8377 8378 defaultTextHeight: function() { return textHeight(this.display) }, 8379 defaultCharWidth: function() { return charWidth(this.display) }, 8380 8381 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, 8382 8383 addWidget: function(pos, node, scroll, vert, horiz) { 8384 var display = this.display; 8385 pos = cursorCoords(this, clipPos(this.doc, pos)); 8386 var top = pos.bottom, left = pos.left; 8387 node.style.position = "absolute"; 8388 node.setAttribute("cm-ignore-events", "true"); 8389 this.display.input.setUneditable(node); 8390 display.sizer.appendChild(node); 8391 if (vert == "over") { 8392 top = pos.top; 8393 } else if (vert == "above" || vert == "near") { 8394 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 8395 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 8396 // Default to positioning above (if specified and possible); otherwise default to positioning below 8397 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 8398 { top = pos.top - node.offsetHeight; } 8399 else if (pos.bottom + node.offsetHeight <= vspace) 8400 { top = pos.bottom; } 8401 if (left + node.offsetWidth > hspace) 8402 { left = hspace - node.offsetWidth; } 8403 } 8404 node.style.top = top + "px"; 8405 node.style.left = node.style.right = ""; 8406 if (horiz == "right") { 8407 left = display.sizer.clientWidth - node.offsetWidth; 8408 node.style.right = "0px"; 8409 } else { 8410 if (horiz == "left") { left = 0; } 8411 else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } 8412 node.style.left = left + "px"; 8413 } 8414 if (scroll) 8415 { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } 8416 }, 8417 8418 triggerOnKeyDown: methodOp(onKeyDown), 8419 triggerOnKeyPress: methodOp(onKeyPress), 8420 triggerOnKeyUp: onKeyUp, 8421 triggerOnMouseDown: methodOp(onMouseDown), 8422 8423 execCommand: function(cmd) { 8424 if (commands.hasOwnProperty(cmd)) 8425 { return commands[cmd].call(null, this) } 8426 }, 8427 8428 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), 8429 8430 findPosH: function(from, amount, unit, visually) { 8431 var this$1 = this; 8432 8433 var dir = 1; 8434 if (amount < 0) { dir = -1; amount = -amount; } 8435 var cur = clipPos(this.doc, from); 8436 for (var i = 0; i < amount; ++i) { 8437 cur = findPosH(this$1.doc, cur, dir, unit, visually); 8438 if (cur.hitSide) { break } 8439 } 8440 return cur 8441 }, 8442 8443 moveH: methodOp(function(dir, unit) { 8444 var this$1 = this; 8445 8446 this.extendSelectionsBy(function (range$$1) { 8447 if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) 8448 { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } 8449 else 8450 { return dir < 0 ? range$$1.from() : range$$1.to() } 8451 }, sel_move); 8452 }), 8453 8454 deleteH: methodOp(function(dir, unit) { 8455 var sel = this.doc.sel, doc = this.doc; 8456 if (sel.somethingSelected()) 8457 { doc.replaceSelection("", null, "+delete"); } 8458 else 8459 { deleteNearSelection(this, function (range$$1) { 8460 var other = findPosH(doc, range$$1.head, dir, unit, false); 8461 return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} 8462 }); } 8463 }), 8464 8465 findPosV: function(from, amount, unit, goalColumn) { 8466 var this$1 = this; 8467 8468 var dir = 1, x = goalColumn; 8469 if (amount < 0) { dir = -1; amount = -amount; } 8470 var cur = clipPos(this.doc, from); 8471 for (var i = 0; i < amount; ++i) { 8472 var coords = cursorCoords(this$1, cur, "div"); 8473 if (x == null) { x = coords.left; } 8474 else { coords.left = x; } 8475 cur = findPosV(this$1, coords, dir, unit); 8476 if (cur.hitSide) { break } 8477 } 8478 return cur 8479 }, 8480 8481 moveV: methodOp(function(dir, unit) { 8482 var this$1 = this; 8483 8484 var doc = this.doc, goals = []; 8485 var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); 8486 doc.extendSelectionsBy(function (range$$1) { 8487 if (collapse) 8488 { return dir < 0 ? range$$1.from() : range$$1.to() } 8489 var headPos = cursorCoords(this$1, range$$1.head, "div"); 8490 if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } 8491 goals.push(headPos.left); 8492 var pos = findPosV(this$1, headPos, dir, unit); 8493 if (unit == "page" && range$$1 == doc.sel.primary()) 8494 { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } 8495 return pos 8496 }, sel_move); 8497 if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) 8498 { doc.sel.ranges[i].goalColumn = goals[i]; } } 8499 }), 8500 8501 // Find the word at the given position (as returned by coordsChar). 8502 findWordAt: function(pos) { 8503 var doc = this.doc, line = getLine(doc, pos.line).text; 8504 var start = pos.ch, end = pos.ch; 8505 if (line) { 8506 var helper = this.getHelper(pos, "wordChars"); 8507 if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } 8508 var startChar = line.charAt(start); 8509 var check = isWordChar(startChar, helper) 8510 ? function (ch) { return isWordChar(ch, helper); } 8511 : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } 8512 : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; 8513 while (start > 0 && check(line.charAt(start - 1))) { --start; } 8514 while (end < line.length && check(line.charAt(end))) { ++end; } 8515 } 8516 return new Range(Pos(pos.line, start), Pos(pos.line, end)) 8517 }, 8518 8519 toggleOverwrite: function(value) { 8520 if (value != null && value == this.state.overwrite) { return } 8521 if (this.state.overwrite = !this.state.overwrite) 8522 { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8523 else 8524 { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8525 8526 signal(this, "overwriteToggle", this, this.state.overwrite); 8527 }, 8528 hasFocus: function() { return this.display.input.getField() == activeElt() }, 8529 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, 8530 8531 scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), 8532 getScrollInfo: function() { 8533 var scroller = this.display.scroller; 8534 return {left: scroller.scrollLeft, top: scroller.scrollTop, 8535 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, 8536 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, 8537 clientHeight: displayHeight(this), clientWidth: displayWidth(this)} 8538 }, 8539 8540 scrollIntoView: methodOp(function(range$$1, margin) { 8541 if (range$$1 == null) { 8542 range$$1 = {from: this.doc.sel.primary().head, to: null}; 8543 if (margin == null) { margin = this.options.cursorScrollMargin; } 8544 } else if (typeof range$$1 == "number") { 8545 range$$1 = {from: Pos(range$$1, 0), to: null}; 8546 } else if (range$$1.from == null) { 8547 range$$1 = {from: range$$1, to: null}; 8548 } 8549 if (!range$$1.to) { range$$1.to = range$$1.from; } 8550 range$$1.margin = margin || 0; 8551 8552 if (range$$1.from.line != null) { 8553 scrollToRange(this, range$$1); 8554 } else { 8555 scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); 8556 } 8557 }), 8558 8559 setSize: methodOp(function(width, height) { 8560 var this$1 = this; 8561 8562 var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; 8563 if (width != null) { this.display.wrapper.style.width = interpret(width); } 8564 if (height != null) { this.display.wrapper.style.height = interpret(height); } 8565 if (this.options.lineWrapping) { clearLineMeasurementCache(this); } 8566 var lineNo$$1 = this.display.viewFrom; 8567 this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { 8568 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) 8569 { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } 8570 ++lineNo$$1; 8571 }); 8572 this.curOp.forceUpdate = true; 8573 signal(this, "refresh", this); 8574 }), 8575 8576 operation: function(f){return runInOp(this, f)}, 8577 startOperation: function(){return startOperation(this)}, 8578 endOperation: function(){return endOperation(this)}, 8579 8580 refresh: methodOp(function() { 8581 var oldHeight = this.display.cachedTextHeight; 8582 regChange(this); 8583 this.curOp.forceUpdate = true; 8584 clearCaches(this); 8585 scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); 8586 updateGutterSpace(this); 8587 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) 8588 { estimateLineHeights(this); } 8589 signal(this, "refresh", this); 8590 }), 8591 8592 swapDoc: methodOp(function(doc) { 8593 var old = this.doc; 8594 old.cm = null; 8595 attachDoc(this, doc); 8596 clearCaches(this); 8597 this.display.input.reset(); 8598 scrollToCoords(this, doc.scrollLeft, doc.scrollTop); 8599 this.curOp.forceScroll = true; 8600 signalLater(this, "swapDoc", this, old); 8601 return old 8602 }), 8603 8604 getInputField: function(){return this.display.input.getField()}, 8605 getWrapperElement: function(){return this.display.wrapper}, 8606 getScrollerElement: function(){return this.display.scroller}, 8607 getGutterElement: function(){return this.display.gutters} 8608 }; 8609 eventMixin(CodeMirror); 8610 8611 CodeMirror.registerHelper = function(type, name, value) { 8612 if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } 8613 helpers[type][name] = value; 8614 }; 8615 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { 8616 CodeMirror.registerHelper(type, name, value); 8617 helpers[type]._global.push({pred: predicate, val: value}); 8618 }; 8619 }; 8620 8621 // Used for horizontal relative motion. Dir is -1 or 1 (left or 8622 // right), unit can be "char", "column" (like char, but doesn't 8623 // cross line boundaries), "word" (across next word), or "group" (to 8624 // the start of next group of word or non-word-non-whitespace 8625 // chars). The visually param controls whether, in right-to-left 8626 // text, direction 1 means to move towards the next index in the 8627 // string, or towards the character to the right of the current 8628 // position. The resulting position will have a hitSide=true 8629 // property if it reached the end of the document. 8630 function findPosH(doc, pos, dir, unit, visually) { 8631 var oldPos = pos; 8632 var origDir = dir; 8633 var lineObj = getLine(doc, pos.line); 8634 function findNextLine() { 8635 var l = pos.line + dir; 8636 if (l < doc.first || l >= doc.first + doc.size) { return false } 8637 pos = new Pos(l, pos.ch, pos.sticky); 8638 return lineObj = getLine(doc, l) 8639 } 8640 function moveOnce(boundToLine) { 8641 var next; 8642 if (visually) { 8643 next = moveVisually(doc.cm, lineObj, pos, dir); 8644 } else { 8645 next = moveLogically(lineObj, pos, dir); 8646 } 8647 if (next == null) { 8648 if (!boundToLine && findNextLine()) 8649 { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } 8650 else 8651 { return false } 8652 } else { 8653 pos = next; 8654 } 8655 return true 8656 } 8657 8658 if (unit == "char") { 8659 moveOnce(); 8660 } else if (unit == "column") { 8661 moveOnce(true); 8662 } else if (unit == "word" || unit == "group") { 8663 var sawType = null, group = unit == "group"; 8664 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); 8665 for (var first = true;; first = false) { 8666 if (dir < 0 && !moveOnce(!first)) { break } 8667 var cur = lineObj.text.charAt(pos.ch) || "\n"; 8668 var type = isWordChar(cur, helper) ? "w" 8669 : group && cur == "\n" ? "n" 8670 : !group || /\s/.test(cur) ? null 8671 : "p"; 8672 if (group && !first && !type) { type = "s"; } 8673 if (sawType && sawType != type) { 8674 if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} 8675 break 8676 } 8677 8678 if (type) { sawType = type; } 8679 if (dir > 0 && !moveOnce(!first)) { break } 8680 } 8681 } 8682 var result = skipAtomic(doc, pos, oldPos, origDir, true); 8683 if (equalCursorPos(oldPos, result)) { result.hitSide = true; } 8684 return result 8685 } 8686 8687 // For relative vertical movement. Dir may be -1 or 1. Unit can be 8688 // "page" or "line". The resulting position will have a hitSide=true 8689 // property if it reached the end of the document. 8690 function findPosV(cm, pos, dir, unit) { 8691 var doc = cm.doc, x = pos.left, y; 8692 if (unit == "page") { 8693 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 8694 var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); 8695 y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; 8696 8697 } else if (unit == "line") { 8698 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 8699 } 8700 var target; 8701 for (;;) { 8702 target = coordsChar(cm, x, y); 8703 if (!target.outside) { break } 8704 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } 8705 y += dir * 5; 8706 } 8707 return target 8708 } 8709 8710 // CONTENTEDITABLE INPUT STYLE 8711 8712 var ContentEditableInput = function(cm) { 8713 this.cm = cm; 8714 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; 8715 this.polling = new Delayed(); 8716 this.composing = null; 8717 this.gracePeriod = false; 8718 this.readDOMTimeout = null; 8719 }; 8720 8721 ContentEditableInput.prototype.init = function (display) { 8722 var this$1 = this; 8723 8724 var input = this, cm = input.cm; 8725 var div = input.div = display.lineDiv; 8726 disableBrowserMagic(div, cm.options.spellcheck); 8727 8728 on(div, "paste", function (e) { 8729 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 8730 // IE doesn't fire input events, so we schedule a read for the pasted content in this way 8731 if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } 8732 }); 8733 8734 on(div, "compositionstart", function (e) { 8735 this$1.composing = {data: e.data, done: false}; 8736 }); 8737 on(div, "compositionupdate", function (e) { 8738 if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } 8739 }); 8740 on(div, "compositionend", function (e) { 8741 if (this$1.composing) { 8742 if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } 8743 this$1.composing.done = true; 8744 } 8745 }); 8746 8747 on(div, "touchstart", function () { return input.forceCompositionEnd(); }); 8748 8749 on(div, "input", function () { 8750 if (!this$1.composing) { this$1.readFromDOMSoon(); } 8751 }); 8752 8753 function onCopyCut(e) { 8754 if (signalDOMEvent(cm, e)) { return } 8755 if (cm.somethingSelected()) { 8756 setLastCopied({lineWise: false, text: cm.getSelections()}); 8757 if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } 8758 } else if (!cm.options.lineWiseCopyCut) { 8759 return 8760 } else { 8761 var ranges = copyableRanges(cm); 8762 setLastCopied({lineWise: true, text: ranges.text}); 8763 if (e.type == "cut") { 8764 cm.operation(function () { 8765 cm.setSelections(ranges.ranges, 0, sel_dontScroll); 8766 cm.replaceSelection("", null, "cut"); 8767 }); 8768 } 8769 } 8770 if (e.clipboardData) { 8771 e.clipboardData.clearData(); 8772 var content = lastCopied.text.join("\n"); 8773 // iOS exposes the clipboard API, but seems to discard content inserted into it 8774 e.clipboardData.setData("Text", content); 8775 if (e.clipboardData.getData("Text") == content) { 8776 e.preventDefault(); 8777 return 8778 } 8779 } 8780 // Old-fashioned briefly-focus-a-textarea hack 8781 var kludge = hiddenTextarea(), te = kludge.firstChild; 8782 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); 8783 te.value = lastCopied.text.join("\n"); 8784 var hadFocus = document.activeElement; 8785 selectInput(te); 8786 setTimeout(function () { 8787 cm.display.lineSpace.removeChild(kludge); 8788 hadFocus.focus(); 8789 if (hadFocus == div) { input.showPrimarySelection(); } 8790 }, 50); 8791 } 8792 on(div, "copy", onCopyCut); 8793 on(div, "cut", onCopyCut); 8794 }; 8795 8796 ContentEditableInput.prototype.prepareSelection = function () { 8797 var result = prepareSelection(this.cm, false); 8798 result.focus = this.cm.state.focused; 8799 return result 8800 }; 8801 8802 ContentEditableInput.prototype.showSelection = function (info, takeFocus) { 8803 if (!info || !this.cm.display.view.length) { return } 8804 if (info.focus || takeFocus) { this.showPrimarySelection(); } 8805 this.showMultipleSelections(info); 8806 }; 8807 8808 ContentEditableInput.prototype.showPrimarySelection = function () { 8809 var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); 8810 var from = prim.from(), to = prim.to(); 8811 8812 if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { 8813 sel.removeAllRanges(); 8814 return 8815 } 8816 8817 var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8818 var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); 8819 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && 8820 cmp(minPos(curAnchor, curFocus), from) == 0 && 8821 cmp(maxPos(curAnchor, curFocus), to) == 0) 8822 { return } 8823 8824 var view = cm.display.view; 8825 var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || 8826 {node: view[0].measure.map[2], offset: 0}; 8827 var end = to.line < cm.display.viewTo && posToDOM(cm, to); 8828 if (!end) { 8829 var measure = view[view.length - 1].measure; 8830 var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; 8831 end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; 8832 } 8833 8834 if (!start || !end) { 8835 sel.removeAllRanges(); 8836 return 8837 } 8838 8839 var old = sel.rangeCount && sel.getRangeAt(0), rng; 8840 try { rng = range(start.node, start.offset, end.offset, end.node); } 8841 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible 8842 if (rng) { 8843 if (!gecko && cm.state.focused) { 8844 sel.collapse(start.node, start.offset); 8845 if (!rng.collapsed) { 8846 sel.removeAllRanges(); 8847 sel.addRange(rng); 8848 } 8849 } else { 8850 sel.removeAllRanges(); 8851 sel.addRange(rng); 8852 } 8853 if (old && sel.anchorNode == null) { sel.addRange(old); } 8854 else if (gecko) { this.startGracePeriod(); } 8855 } 8856 this.rememberSelection(); 8857 }; 8858 8859 ContentEditableInput.prototype.startGracePeriod = function () { 8860 var this$1 = this; 8861 8862 clearTimeout(this.gracePeriod); 8863 this.gracePeriod = setTimeout(function () { 8864 this$1.gracePeriod = false; 8865 if (this$1.selectionChanged()) 8866 { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } 8867 }, 20); 8868 }; 8869 8870 ContentEditableInput.prototype.showMultipleSelections = function (info) { 8871 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); 8872 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); 8873 }; 8874 8875 ContentEditableInput.prototype.rememberSelection = function () { 8876 var sel = window.getSelection(); 8877 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; 8878 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; 8879 }; 8880 8881 ContentEditableInput.prototype.selectionInEditor = function () { 8882 var sel = window.getSelection(); 8883 if (!sel.rangeCount) { return false } 8884 var node = sel.getRangeAt(0).commonAncestorContainer; 8885 return contains(this.div, node) 8886 }; 8887 8888 ContentEditableInput.prototype.focus = function () { 8889 if (this.cm.options.readOnly != "nocursor") { 8890 if (!this.selectionInEditor()) 8891 { this.showSelection(this.prepareSelection(), true); } 8892 this.div.focus(); 8893 } 8894 }; 8895 ContentEditableInput.prototype.blur = function () { this.div.blur(); }; 8896 ContentEditableInput.prototype.getField = function () { return this.div }; 8897 8898 ContentEditableInput.prototype.supportsTouch = function () { return true }; 8899 8900 ContentEditableInput.prototype.receivedFocus = function () { 8901 var input = this; 8902 if (this.selectionInEditor()) 8903 { this.pollSelection(); } 8904 else 8905 { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } 8906 8907 function poll() { 8908 if (input.cm.state.focused) { 8909 input.pollSelection(); 8910 input.polling.set(input.cm.options.pollInterval, poll); 8911 } 8912 } 8913 this.polling.set(this.cm.options.pollInterval, poll); 8914 }; 8915 8916 ContentEditableInput.prototype.selectionChanged = function () { 8917 var sel = window.getSelection(); 8918 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || 8919 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset 8920 }; 8921 8922 ContentEditableInput.prototype.pollSelection = function () { 8923 if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } 8924 var sel = window.getSelection(), cm = this.cm; 8925 // On Android Chrome (version 56, at least), backspacing into an 8926 // uneditable block element will put the cursor in that element, 8927 // and then, because it's not editable, hide the virtual keyboard. 8928 // Because Android doesn't allow us to actually detect backspace 8929 // presses in a sane way, this code checks for when that happens 8930 // and simulates a backspace press in this case. 8931 if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { 8932 this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); 8933 this.blur(); 8934 this.focus(); 8935 return 8936 } 8937 if (this.composing) { return } 8938 this.rememberSelection(); 8939 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8940 var head = domToPos(cm, sel.focusNode, sel.focusOffset); 8941 if (anchor && head) { runInOp(cm, function () { 8942 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); 8943 if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } 8944 }); } 8945 }; 8946 8947 ContentEditableInput.prototype.pollContent = function () { 8948 if (this.readDOMTimeout != null) { 8949 clearTimeout(this.readDOMTimeout); 8950 this.readDOMTimeout = null; 8951 } 8952 8953 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); 8954 var from = sel.from(), to = sel.to(); 8955 if (from.ch == 0 && from.line > cm.firstLine()) 8956 { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } 8957 if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) 8958 { to = Pos(to.line + 1, 0); } 8959 if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } 8960 8961 var fromIndex, fromLine, fromNode; 8962 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { 8963 fromLine = lineNo(display.view[0].line); 8964 fromNode = display.view[0].node; 8965 } else { 8966 fromLine = lineNo(display.view[fromIndex].line); 8967 fromNode = display.view[fromIndex - 1].node.nextSibling; 8968 } 8969 var toIndex = findViewIndex(cm, to.line); 8970 var toLine, toNode; 8971 if (toIndex == display.view.length - 1) { 8972 toLine = display.viewTo - 1; 8973 toNode = display.lineDiv.lastChild; 8974 } else { 8975 toLine = lineNo(display.view[toIndex + 1].line) - 1; 8976 toNode = display.view[toIndex + 1].node.previousSibling; 8977 } 8978 8979 if (!fromNode) { return false } 8980 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); 8981 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); 8982 while (newText.length > 1 && oldText.length > 1) { 8983 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } 8984 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } 8985 else { break } 8986 } 8987 8988 var cutFront = 0, cutEnd = 0; 8989 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); 8990 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) 8991 { ++cutFront; } 8992 var newBot = lst(newText), oldBot = lst(oldText); 8993 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), 8994 oldBot.length - (oldText.length == 1 ? cutFront : 0)); 8995 while (cutEnd < maxCutEnd && 8996 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) 8997 { ++cutEnd; } 8998 // Try to move start of change to start of selection if ambiguous 8999 if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { 9000 while (cutFront && cutFront > from.ch && 9001 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { 9002 cutFront--; 9003 cutEnd++; 9004 } 9005 } 9006 9007 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); 9008 newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); 9009 9010 var chFrom = Pos(fromLine, cutFront); 9011 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); 9012 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { 9013 replaceRange(cm.doc, newText, chFrom, chTo, "+input"); 9014 return true 9015 } 9016 }; 9017 9018 ContentEditableInput.prototype.ensurePolled = function () { 9019 this.forceCompositionEnd(); 9020 }; 9021 ContentEditableInput.prototype.reset = function () { 9022 this.forceCompositionEnd(); 9023 }; 9024 ContentEditableInput.prototype.forceCompositionEnd = function () { 9025 if (!this.composing) { return } 9026 clearTimeout(this.readDOMTimeout); 9027 this.composing = null; 9028 this.updateFromDOM(); 9029 this.div.blur(); 9030 this.div.focus(); 9031 }; 9032 ContentEditableInput.prototype.readFromDOMSoon = function () { 9033 var this$1 = this; 9034 9035 if (this.readDOMTimeout != null) { return } 9036 this.readDOMTimeout = setTimeout(function () { 9037 this$1.readDOMTimeout = null; 9038 if (this$1.composing) { 9039 if (this$1.composing.done) { this$1.composing = null; } 9040 else { return } 9041 } 9042 this$1.updateFromDOM(); 9043 }, 80); 9044 }; 9045 9046 ContentEditableInput.prototype.updateFromDOM = function () { 9047 var this$1 = this; 9048 9049 if (this.cm.isReadOnly() || !this.pollContent()) 9050 { runInOp(this.cm, function () { return regChange(this$1.cm); }); } 9051 }; 9052 9053 ContentEditableInput.prototype.setUneditable = function (node) { 9054 node.contentEditable = "false"; 9055 }; 9056 9057 ContentEditableInput.prototype.onKeyPress = function (e) { 9058 if (e.charCode == 0) { return } 9059 e.preventDefault(); 9060 if (!this.cm.isReadOnly()) 9061 { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } 9062 }; 9063 9064 ContentEditableInput.prototype.readOnlyChanged = function (val) { 9065 this.div.contentEditable = String(val != "nocursor"); 9066 }; 9067 9068 ContentEditableInput.prototype.onContextMenu = function () {}; 9069 ContentEditableInput.prototype.resetPosition = function () {}; 9070 9071 ContentEditableInput.prototype.needsContentAttribute = true; 9072 9073 function posToDOM(cm, pos) { 9074 var view = findViewForLine(cm, pos.line); 9075 if (!view || view.hidden) { return null } 9076 var line = getLine(cm.doc, pos.line); 9077 var info = mapFromLineView(view, line, pos.line); 9078 9079 var order = getOrder(line, cm.doc.direction), side = "left"; 9080 if (order) { 9081 var partPos = getBidiPartAt(order, pos.ch); 9082 side = partPos % 2 ? "right" : "left"; 9083 } 9084 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); 9085 result.offset = result.collapse == "right" ? result.end : result.start; 9086 return result 9087 } 9088 9089 function isInGutter(node) { 9090 for (var scan = node; scan; scan = scan.parentNode) 9091 { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } 9092 return false 9093 } 9094 9095 function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } 9096 9097 function domTextBetween(cm, from, to, fromLine, toLine) { 9098 var text = "", closing = false, lineSep = cm.doc.lineSeparator(); 9099 function recognizeMarker(id) { return function (marker) { return marker.id == id; } } 9100 function close() { 9101 if (closing) { 9102 text += lineSep; 9103 closing = false; 9104 } 9105 } 9106 function addText(str) { 9107 if (str) { 9108 close(); 9109 text += str; 9110 } 9111 } 9112 function walk(node) { 9113 if (node.nodeType == 1) { 9114 var cmText = node.getAttribute("cm-text"); 9115 if (cmText != null) { 9116 addText(cmText || node.textContent.replace(/\u200b/g, "")); 9117 return 9118 } 9119 var markerID = node.getAttribute("cm-marker"), range$$1; 9120 if (markerID) { 9121 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); 9122 if (found.length && (range$$1 = found[0].find(0))) 9123 { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } 9124 return 9125 } 9126 if (node.getAttribute("contenteditable") == "false") { return } 9127 var isBlock = /^(pre|div|p)$/i.test(node.nodeName); 9128 if (isBlock) { close(); } 9129 for (var i = 0; i < node.childNodes.length; i++) 9130 { walk(node.childNodes[i]); } 9131 if (isBlock) { closing = true; } 9132 } else if (node.nodeType == 3) { 9133 addText(node.nodeValue); 9134 } 9135 } 9136 for (;;) { 9137 walk(from); 9138 if (from == to) { break } 9139 from = from.nextSibling; 9140 } 9141 return text 9142 } 9143 9144 function domToPos(cm, node, offset) { 9145 var lineNode; 9146 if (node == cm.display.lineDiv) { 9147 lineNode = cm.display.lineDiv.childNodes[offset]; 9148 if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } 9149 node = null; offset = 0; 9150 } else { 9151 for (lineNode = node;; lineNode = lineNode.parentNode) { 9152 if (!lineNode || lineNode == cm.display.lineDiv) { return null } 9153 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } 9154 } 9155 } 9156 for (var i = 0; i < cm.display.view.length; i++) { 9157 var lineView = cm.display.view[i]; 9158 if (lineView.node == lineNode) 9159 { return locateNodeInLineView(lineView, node, offset) } 9160 } 9161 } 9162 9163 function locateNodeInLineView(lineView, node, offset) { 9164 var wrapper = lineView.text.firstChild, bad = false; 9165 if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } 9166 if (node == wrapper) { 9167 bad = true; 9168 node = wrapper.childNodes[offset]; 9169 offset = 0; 9170 if (!node) { 9171 var line = lineView.rest ? lst(lineView.rest) : lineView.line; 9172 return badPos(Pos(lineNo(line), line.text.length), bad) 9173 } 9174 } 9175 9176 var textNode = node.nodeType == 3 ? node : null, topNode = node; 9177 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { 9178 textNode = node.firstChild; 9179 if (offset) { offset = textNode.nodeValue.length; } 9180 } 9181 while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } 9182 var measure = lineView.measure, maps = measure.maps; 9183 9184 function find(textNode, topNode, offset) { 9185 for (var i = -1; i < (maps ? maps.length : 0); i++) { 9186 var map$$1 = i < 0 ? measure.map : maps[i]; 9187 for (var j = 0; j < map$$1.length; j += 3) { 9188 var curNode = map$$1[j + 2]; 9189 if (curNode == textNode || curNode == topNode) { 9190 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); 9191 var ch = map$$1[j] + offset; 9192 if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } 9193 return Pos(line, ch) 9194 } 9195 } 9196 } 9197 } 9198 var found = find(textNode, topNode, offset); 9199 if (found) { return badPos(found, bad) } 9200 9201 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems 9202 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { 9203 found = find(after, after.firstChild, 0); 9204 if (found) 9205 { return badPos(Pos(found.line, found.ch - dist), bad) } 9206 else 9207 { dist += after.textContent.length; } 9208 } 9209 for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { 9210 found = find(before, before.firstChild, -1); 9211 if (found) 9212 { return badPos(Pos(found.line, found.ch + dist$1), bad) } 9213 else 9214 { dist$1 += before.textContent.length; } 9215 } 9216 } 9217 9218 // TEXTAREA INPUT STYLE 9219 9220 var TextareaInput = function(cm) { 9221 this.cm = cm; 9222 // See input.poll and input.reset 9223 this.prevInput = ""; 9224 9225 // Flag that indicates whether we expect input to appear real soon 9226 // now (after some event like 'keypress' or 'input') and are 9227 // polling intensively. 9228 this.pollingFast = false; 9229 // Self-resetting timeout for the poller 9230 this.polling = new Delayed(); 9231 // Used to work around IE issue with selection being forgotten when focus moves away from textarea 9232 this.hasSelection = false; 9233 this.composing = null; 9234 }; 9235 9236 TextareaInput.prototype.init = function (display) { 9237 var this$1 = this; 9238 9239 var input = this, cm = this.cm; 9240 9241 // Wraps and hides input textarea 9242 var div = this.wrapper = hiddenTextarea(); 9243 // The semihidden textarea that is focused when the editor is 9244 // focused, and receives input. 9245 var te = this.textarea = div.firstChild; 9246 display.wrapper.insertBefore(div, display.wrapper.firstChild); 9247 9248 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) 9249 if (ios) { te.style.width = "0px"; } 9250 9251 on(te, "input", function () { 9252 if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } 9253 input.poll(); 9254 }); 9255 9256 on(te, "paste", function (e) { 9257 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 9258 9259 cm.state.pasteIncoming = true; 9260 input.fastPoll(); 9261 }); 9262 9263 function prepareCopyCut(e) { 9264 if (signalDOMEvent(cm, e)) { return } 9265 if (cm.somethingSelected()) { 9266 setLastCopied({lineWise: false, text: cm.getSelections()}); 9267 } else if (!cm.options.lineWiseCopyCut) { 9268 return 9269 } else { 9270 var ranges = copyableRanges(cm); 9271 setLastCopied({lineWise: true, text: ranges.text}); 9272 if (e.type == "cut") { 9273 cm.setSelections(ranges.ranges, null, sel_dontScroll); 9274 } else { 9275 input.prevInput = ""; 9276 te.value = ranges.text.join("\n"); 9277 selectInput(te); 9278 } 9279 } 9280 if (e.type == "cut") { cm.state.cutIncoming = true; } 9281 } 9282 on(te, "cut", prepareCopyCut); 9283 on(te, "copy", prepareCopyCut); 9284 9285 on(display.scroller, "paste", function (e) { 9286 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } 9287 cm.state.pasteIncoming = true; 9288 input.focus(); 9289 }); 9290 9291 // Prevent normal selection in the editor (we handle our own) 9292 on(display.lineSpace, "selectstart", function (e) { 9293 if (!eventInWidget(display, e)) { e_preventDefault(e); } 9294 }); 9295 9296 on(te, "compositionstart", function () { 9297 var start = cm.getCursor("from"); 9298 if (input.composing) { input.composing.range.clear(); } 9299 input.composing = { 9300 start: start, 9301 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) 9302 }; 9303 }); 9304 on(te, "compositionend", function () { 9305 if (input.composing) { 9306 input.poll(); 9307 input.composing.range.clear(); 9308 input.composing = null; 9309 } 9310 }); 9311 }; 9312 9313 TextareaInput.prototype.prepareSelection = function () { 9314 // Redraw the selection and/or cursor 9315 var cm = this.cm, display = cm.display, doc = cm.doc; 9316 var result = prepareSelection(cm); 9317 9318 // Move the hidden textarea near the cursor to prevent scrolling artifacts 9319 if (cm.options.moveInputWithCursor) { 9320 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); 9321 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); 9322 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 9323 headPos.top + lineOff.top - wrapOff.top)); 9324 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 9325 headPos.left + lineOff.left - wrapOff.left)); 9326 } 9327 9328 return result 9329 }; 9330 9331 TextareaInput.prototype.showSelection = function (drawn) { 9332 var cm = this.cm, display = cm.display; 9333 removeChildrenAndAdd(display.cursorDiv, drawn.cursors); 9334 removeChildrenAndAdd(display.selectionDiv, drawn.selection); 9335 if (drawn.teTop != null) { 9336 this.wrapper.style.top = drawn.teTop + "px"; 9337 this.wrapper.style.left = drawn.teLeft + "px"; 9338 } 9339 }; 9340 9341 // Reset the input to correspond to the selection (or to be empty, 9342 // when not typing and nothing is selected) 9343 TextareaInput.prototype.reset = function (typing) { 9344 if (this.contextMenuPending || this.composing) { return } 9345 var cm = this.cm; 9346 if (cm.somethingSelected()) { 9347 this.prevInput = ""; 9348 var content = cm.getSelection(); 9349 this.textarea.value = content; 9350 if (cm.state.focused) { selectInput(this.textarea); } 9351 if (ie && ie_version >= 9) { this.hasSelection = content; } 9352 } else if (!typing) { 9353 this.prevInput = this.textarea.value = ""; 9354 if (ie && ie_version >= 9) { this.hasSelection = null; } 9355 } 9356 }; 9357 9358 TextareaInput.prototype.getField = function () { return this.textarea }; 9359 9360 TextareaInput.prototype.supportsTouch = function () { return false }; 9361 9362 TextareaInput.prototype.focus = function () { 9363 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { 9364 try { this.textarea.focus(); } 9365 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM 9366 } 9367 }; 9368 9369 TextareaInput.prototype.blur = function () { this.textarea.blur(); }; 9370 9371 TextareaInput.prototype.resetPosition = function () { 9372 this.wrapper.style.top = this.wrapper.style.left = 0; 9373 }; 9374 9375 TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; 9376 9377 // Poll for input changes, using the normal rate of polling. This 9378 // runs as long as the editor is focused. 9379 TextareaInput.prototype.slowPoll = function () { 9380 var this$1 = this; 9381 9382 if (this.pollingFast) { return } 9383 this.polling.set(this.cm.options.pollInterval, function () { 9384 this$1.poll(); 9385 if (this$1.cm.state.focused) { this$1.slowPoll(); } 9386 }); 9387 }; 9388 9389 // When an event has just come in that is likely to add or change 9390 // something in the input textarea, we poll faster, to ensure that 9391 // the change appears on the screen quickly. 9392 TextareaInput.prototype.fastPoll = function () { 9393 var missed = false, input = this; 9394 input.pollingFast = true; 9395 function p() { 9396 var changed = input.poll(); 9397 if (!changed && !missed) {missed = true; input.polling.set(60, p);} 9398 else {input.pollingFast = false; input.slowPoll();} 9399 } 9400 input.polling.set(20, p); 9401 }; 9402 9403 // Read input from the textarea, and update the document to match. 9404 // When something is selected, it is present in the textarea, and 9405 // selected (unless it is huge, in which case a placeholder is 9406 // used). When nothing is selected, the cursor sits after previously 9407 // seen text (can be empty), which is stored in prevInput (we must 9408 // not reset the textarea when typing, because that breaks IME). 9409 TextareaInput.prototype.poll = function () { 9410 var this$1 = this; 9411 9412 var cm = this.cm, input = this.textarea, prevInput = this.prevInput; 9413 // Since this is called a *lot*, try to bail out as cheaply as 9414 // possible when it is clear that nothing happened. hasSelection 9415 // will be the case when there is a lot of text in the textarea, 9416 // in which case reading its value would be expensive. 9417 if (this.contextMenuPending || !cm.state.focused || 9418 (hasSelection(input) && !prevInput && !this.composing) || 9419 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) 9420 { return false } 9421 9422 var text = input.value; 9423 // If nothing changed, bail. 9424 if (text == prevInput && !cm.somethingSelected()) { return false } 9425 // Work around nonsensical selection resetting in IE9/10, and 9426 // inexplicable appearance of private area unicode characters on 9427 // some key combos in Mac (#2689). 9428 if (ie && ie_version >= 9 && this.hasSelection === text || 9429 mac && /[\uf700-\uf7ff]/.test(text)) { 9430 cm.display.input.reset(); 9431 return false 9432 } 9433 9434 if (cm.doc.sel == cm.display.selForContextMenu) { 9435 var first = text.charCodeAt(0); 9436 if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } 9437 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } 9438 } 9439 // Find the part of the input that is actually new 9440 var same = 0, l = Math.min(prevInput.length, text.length); 9441 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } 9442 9443 runInOp(cm, function () { 9444 applyTextInput(cm, text.slice(same), prevInput.length - same, 9445 null, this$1.composing ? "*compose" : null); 9446 9447 // Don't leave long text in the textarea, since it makes further polling slow 9448 if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } 9449 else { this$1.prevInput = text; } 9450 9451 if (this$1.composing) { 9452 this$1.composing.range.clear(); 9453 this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), 9454 {className: "CodeMirror-composing"}); 9455 } 9456 }); 9457 return true 9458 }; 9459 9460 TextareaInput.prototype.ensurePolled = function () { 9461 if (this.pollingFast && this.poll()) { this.pollingFast = false; } 9462 }; 9463 9464 TextareaInput.prototype.onKeyPress = function () { 9465 if (ie && ie_version >= 9) { this.hasSelection = null; } 9466 this.fastPoll(); 9467 }; 9468 9469 TextareaInput.prototype.onContextMenu = function (e) { 9470 var input = this, cm = input.cm, display = cm.display, te = input.textarea; 9471 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 9472 if (!pos || presto) { return } // Opera is difficult. 9473 9474 // Reset the current text selection only if the click is done outside of the selection 9475 // and 'resetSelectionOnContextMenu' option is true. 9476 var reset = cm.options.resetSelectionOnContextMenu; 9477 if (reset && cm.doc.sel.contains(pos) == -1) 9478 { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } 9479 9480 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; 9481 input.wrapper.style.cssText = "position: absolute"; 9482 var wrapperBox = input.wrapper.getBoundingClientRect(); 9483 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);"; 9484 var oldScrollY; 9485 if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) 9486 display.input.focus(); 9487 if (webkit) { window.scrollTo(null, oldScrollY); } 9488 display.input.reset(); 9489 // Adds "Select all" to context menu in FF 9490 if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } 9491 input.contextMenuPending = true; 9492 display.selForContextMenu = cm.doc.sel; 9493 clearTimeout(display.detectingSelectAll); 9494 9495 // Select-all will be greyed out if there's nothing to select, so 9496 // this adds a zero-width space so that we can later check whether 9497 // it got selected. 9498 function prepareSelectAllHack() { 9499 if (te.selectionStart != null) { 9500 var selected = cm.somethingSelected(); 9501 var extval = "\u200b" + (selected ? te.value : ""); 9502 te.value = "\u21da"; // Used to catch context-menu undo 9503 te.value = extval; 9504 input.prevInput = selected ? "" : "\u200b"; 9505 te.selectionStart = 1; te.selectionEnd = extval.length; 9506 // Re-set this, in case some other handler touched the 9507 // selection in the meantime. 9508 display.selForContextMenu = cm.doc.sel; 9509 } 9510 } 9511 function rehide() { 9512 input.contextMenuPending = false; 9513 input.wrapper.style.cssText = oldWrapperCSS; 9514 te.style.cssText = oldCSS; 9515 if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } 9516 9517 // Try to detect the user choosing select-all 9518 if (te.selectionStart != null) { 9519 if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } 9520 var i = 0, poll = function () { 9521 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && 9522 te.selectionEnd > 0 && input.prevInput == "\u200b") { 9523 operation(cm, selectAll)(cm); 9524 } else if (i++ < 10) { 9525 display.detectingSelectAll = setTimeout(poll, 500); 9526 } else { 9527 display.selForContextMenu = null; 9528 display.input.reset(); 9529 } 9530 }; 9531 display.detectingSelectAll = setTimeout(poll, 200); 9532 } 9533 } 9534 9535 if (ie && ie_version >= 9) { prepareSelectAllHack(); } 9536 if (captureRightClick) { 9537 e_stop(e); 9538 var mouseup = function () { 9539 off(window, "mouseup", mouseup); 9540 setTimeout(rehide, 20); 9541 }; 9542 on(window, "mouseup", mouseup); 9543 } else { 9544 setTimeout(rehide, 50); 9545 } 9546 }; 9547 9548 TextareaInput.prototype.readOnlyChanged = function (val) { 9549 if (!val) { this.reset(); } 9550 this.textarea.disabled = val == "nocursor"; 9551 }; 9552 9553 TextareaInput.prototype.setUneditable = function () {}; 9554 9555 TextareaInput.prototype.needsContentAttribute = false; 9556 9557 function fromTextArea(textarea, options) { 9558 options = options ? copyObj(options) : {}; 9559 options.value = textarea.value; 9560 if (!options.tabindex && textarea.tabIndex) 9561 { options.tabindex = textarea.tabIndex; } 9562 if (!options.placeholder && textarea.placeholder) 9563 { options.placeholder = textarea.placeholder; } 9564 // Set autofocus to true if this textarea is focused, or if it has 9565 // autofocus and no other element is focused. 9566 if (options.autofocus == null) { 9567 var hasFocus = activeElt(); 9568 options.autofocus = hasFocus == textarea || 9569 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 9570 } 9571 9572 function save() {textarea.value = cm.getValue();} 9573 9574 var realSubmit; 9575 if (textarea.form) { 9576 on(textarea.form, "submit", save); 9577 // Deplorable hack to make the submit method do the right thing. 9578 if (!options.leaveSubmitMethodAlone) { 9579 var form = textarea.form; 9580 realSubmit = form.submit; 9581 try { 9582 var wrappedSubmit = form.submit = function () { 9583 save(); 9584 form.submit = realSubmit; 9585 form.submit(); 9586 form.submit = wrappedSubmit; 9587 }; 9588 } catch(e) {} 9589 } 9590 } 9591 9592 options.finishInit = function (cm) { 9593 cm.save = save; 9594 cm.getTextArea = function () { return textarea; }; 9595 cm.toTextArea = function () { 9596 cm.toTextArea = isNaN; // Prevent this from being ran twice 9597 save(); 9598 textarea.parentNode.removeChild(cm.getWrapperElement()); 9599 textarea.style.display = ""; 9600 if (textarea.form) { 9601 off(textarea.form, "submit", save); 9602 if (typeof textarea.form.submit == "function") 9603 { textarea.form.submit = realSubmit; } 9604 } 9605 }; 9606 }; 9607 9608 textarea.style.display = "none"; 9609 var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, 9610 options); 9611 return cm 9612 } 9613 9614 function addLegacyProps(CodeMirror) { 9615 CodeMirror.off = off; 9616 CodeMirror.on = on; 9617 CodeMirror.wheelEventPixels = wheelEventPixels; 9618 CodeMirror.Doc = Doc; 9619 CodeMirror.splitLines = splitLinesAuto; 9620 CodeMirror.countColumn = countColumn; 9621 CodeMirror.findColumn = findColumn; 9622 CodeMirror.isWordChar = isWordCharBasic; 9623 CodeMirror.Pass = Pass; 9624 CodeMirror.signal = signal; 9625 CodeMirror.Line = Line; 9626 CodeMirror.changeEnd = changeEnd; 9627 CodeMirror.scrollbarModel = scrollbarModel; 9628 CodeMirror.Pos = Pos; 9629 CodeMirror.cmpPos = cmp; 9630 CodeMirror.modes = modes; 9631 CodeMirror.mimeModes = mimeModes; 9632 CodeMirror.resolveMode = resolveMode; 9633 CodeMirror.getMode = getMode; 9634 CodeMirror.modeExtensions = modeExtensions; 9635 CodeMirror.extendMode = extendMode; 9636 CodeMirror.copyState = copyState; 9637 CodeMirror.startState = startState; 9638 CodeMirror.innerMode = innerMode; 9639 CodeMirror.commands = commands; 9640 CodeMirror.keyMap = keyMap; 9641 CodeMirror.keyName = keyName; 9642 CodeMirror.isModifierKey = isModifierKey; 9643 CodeMirror.lookupKey = lookupKey; 9644 CodeMirror.normalizeKeyMap = normalizeKeyMap; 9645 CodeMirror.StringStream = StringStream; 9646 CodeMirror.SharedTextMarker = SharedTextMarker; 9647 CodeMirror.TextMarker = TextMarker; 9648 CodeMirror.LineWidget = LineWidget; 9649 CodeMirror.e_preventDefault = e_preventDefault; 9650 CodeMirror.e_stopPropagation = e_stopPropagation; 9651 CodeMirror.e_stop = e_stop; 9652 CodeMirror.addClass = addClass; 9653 CodeMirror.contains = contains; 9654 CodeMirror.rmClass = rmClass; 9655 CodeMirror.keyNames = keyNames; 9656 } 9657 9658 // EDITOR CONSTRUCTOR 9659 9660 defineOptions(CodeMirror$1); 9661 9662 addEditorMethods(CodeMirror$1); 9663 9664 // Set up methods on CodeMirror's prototype to redirect to the editor's document. 9665 var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); 9666 for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 9667 { CodeMirror$1.prototype[prop] = (function(method) { 9668 return function() {return method.apply(this.doc, arguments)} 9669 })(Doc.prototype[prop]); } } 9670 9671 eventMixin(Doc); 9672 9673 // INPUT HANDLING 9674 9675 CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; 9676 9677 // MODE DEFINITION AND QUERYING 9678 9679 // Extra arguments are stored as the mode's dependencies, which is 9680 // used by (legacy) mechanisms like loadmode.js to automatically 9681 // load a mode. (Preferred mechanism is the require/define calls.) 9682 CodeMirror$1.defineMode = function(name/*, mode, âŠ*/) { 9683 if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; } 9684 defineMode.apply(this, arguments); 9685 }; 9686 9687 CodeMirror$1.defineMIME = defineMIME; 9688 9689 // Minimal default mode. 9690 CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); 9691 CodeMirror$1.defineMIME("text/plain", "null"); 9692 9693 // EXTENSIONS 9694 9695 CodeMirror$1.defineExtension = function (name, func) { 9696 CodeMirror$1.prototype[name] = func; 9697 }; 9698 CodeMirror$1.defineDocExtension = function (name, func) { 9699 Doc.prototype[name] = func; 9700 }; 9701 9702 CodeMirror$1.fromTextArea = fromTextArea; 9703 9704 addLegacyProps(CodeMirror$1); 9705 9706 CodeMirror$1.version = "5.31.0"; 9707 9708 return CodeMirror$1; 9709 9710 }))); 9711 9712 },{}],3:[function(require,module,exports){ 9713 // CodeMirror, copyright (c) by Marijn Haverbeke and others 9714 // Distributed under an MIT license: http://codemirror.net/LICENSE 9715 9716 // mode(s) for the sequence chart dsl's mscgen, xù and msgenny 9717 // For more information on mscgen, see the site of the original author: 9718 // http://www.mcternan.me.uk/mscgen 9719 // 9720 // This mode for mscgen and the two derivative languages were 9721 // originally made for use in the mscgen_js interpreter 9722 // (https://sverweij.github.io/mscgen_js) 9723 9724 (function(mod) { 9725 if ( typeof exports == "object" && typeof module == "object")// CommonJS 9726 mod(require("../../lib/codemirror")); 9727 else if ( typeof define == "function" && define.amd)// AMD 9728 define(["../../lib/codemirror"], mod); 9729 else// Plain browser env 9730 mod(CodeMirror); 9731 })(function(CodeMirror) { 9732 "use strict"; 9733 9734 var languages = { 9735 "fcs-ql": { 9736 "keywords" : ["msc"], 9737 "options" : ["hscale", "width", "arcgradient", "wordwraparcs"], 9738 "constants" : ["true", "false", "on", "off"], 9739 "attributes" : ["text", "lemma", "word", "pos", ""], 9740 "brackets" : ["\\{", "\\}"], // [ and ] are brackets too, but these get handled in with lists 9741 "arcsWords" : ["note", "abox", "rbox", "box"], 9742 "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], 9743 "singlecomment" : ["//", "#"], 9744 "operators" : ["=", "!=", "contains"] 9745 } 9746 } 9747 9748 CodeMirror.defineMode("fcs-ql", function(_, modeConfig) { 9749 var language = languages[modeConfig && modeConfig.language || "fcs-ql"] 9750 return { 9751 startState: startStateFn, 9752 copyState: copyStateFn, 9753 token: produceTokenFunction(language), 9754 lineComment : "#", 9755 blockCommentStart : "/*", 9756 blockCommentEnd : "*/" 9757 }; 9758 }); 9759 9760 CodeMirror.defineMIME("text/x-fcs-ql", "fcs-ql"); 9761 9762 function wordRegexpBoundary(pWords) { 9763 return new RegExp("\\b(" + pWords.join("|") + ")\\b", "i"); 9764 } 9765 9766 function wordRegexp(pWords) { 9767 return new RegExp("(" + pWords.join("|") + ")", "i"); 9768 } 9769 9770 function startStateFn() { 9771 return { 9772 inComment : false, 9773 inString : false, 9774 inAttributeList : false, 9775 inScript : false 9776 }; 9777 } 9778 9779 function copyStateFn(pState) { 9780 return { 9781 inComment : pState.inComment, 9782 inString : pState.inString, 9783 inAttributeList : pState.inAttributeList, 9784 inScript : pState.inScript 9785 }; 9786 } 9787 9788 function produceTokenFunction(pConfig) { 9789 9790 return function(pStream, pState) { 9791 if (pStream.match(wordRegexp(pConfig.brackets), true, true)) { 9792 return "bracket"; 9793 } 9794 /* comments */ 9795 if (!pState.inComment) { 9796 if (pStream.match(/\/\*[^\*\/]*/, true, true)) { 9797 pState.inComment = true; 9798 return "comment"; 9799 } 9800 if (pStream.match(wordRegexp(pConfig.singlecomment), true, true)) { 9801 pStream.skipToEnd(); 9802 return "comment"; 9803 } 9804 } 9805 if (pState.inComment) { 9806 if (pStream.match(/[^\*\/]*\*\//, true, true)) 9807 pState.inComment = false; 9808 else 9809 pStream.skipToEnd(); 9810 return "comment"; 9811 } 9812 /* strings */ 9813 if (!pState.inString && pStream.match(/\"(\\\"|[^\"])*/, true, true)) { 9814 pState.inString = true; 9815 return "string"; 9816 } 9817 if (pState.inString) { 9818 if (pStream.match(/[^\"]*\"/, true, true)) 9819 pState.inString = false; 9820 else 9821 pStream.skipToEnd(); 9822 return "string"; 9823 } 9824 /* keywords & operators */ 9825 if (!!pConfig.keywords && pStream.match(wordRegexpBoundary(pConfig.keywords), true, true)) 9826 return "keyword"; 9827 9828 if (pStream.match(wordRegexpBoundary(pConfig.options), true, true)) 9829 return "keyword"; 9830 9831 if (pStream.match(wordRegexpBoundary(pConfig.arcsWords), true, true)) 9832 return "keyword"; 9833 9834 if (pStream.match(wordRegexp(pConfig.arcsOthers), true, true)) 9835 return "keyword"; 9836 9837 if (!!pConfig.operators && pStream.match(wordRegexp(pConfig.operators), true, true)) 9838 return "operator"; 9839 9840 if (!!pConfig.constants && pStream.match(wordRegexp(pConfig.constants), true, true)) 9841 return "variable"; 9842 9843 /* attribute lists */ 9844 if (!pConfig.inAttributeList && !!pConfig.attributes && pStream.match(/\[/, true, true)) { 9845 pConfig.inAttributeList = true; 9846 return "bracket"; 9847 } 9848 if (pConfig.inAttributeList) { 9849 if (pConfig.attributes !== null && pStream.match(wordRegexpBoundary(pConfig.attributes), true, true)) { 9850 return "attribute"; 9851 } 9852 if (pStream.match(/]/, true, true)) { 9853 pConfig.inAttributeList = false; 9854 return "bracket"; 9855 } 9856 } 9857 9858 pStream.next(); 9859 return "base"; 9860 }; 9861 } 9862 9863 }); 9864 9865 },{"../../lib/codemirror":2}],4:[function(require,module,exports){ 9866 // CodeMirror, copyright (c) by Marijn Haverbeke and others 9867 // Distributed under an MIT license: http://codemirror.net/LICENSE 9868 9869 (function(mod) { 9870 if (typeof exports == "object" && typeof module == "object") // CommonJS 9871 mod(require("../../lib/codemirror")); 9872 else if (typeof define == "function" && define.amd) // AMD 9873 define(["../../lib/codemirror"], mod); 9874 else // Plain browser env 9875 mod(CodeMirror); 9876 })(function(CodeMirror) { 9877 "use strict"; 9878 9879 CodeMirror.defineMode("javascript", function(config, parserConfig) { 9880 var indentUnit = config.indentUnit; 9881 var statementIndent = parserConfig.statementIndent; 9882 var jsonldMode = parserConfig.jsonld; 9883 var jsonMode = parserConfig.json || jsonldMode; 9884 var isTS = parserConfig.typescript; 9885 var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; 9886 9887 // Tokenizer 9888 9889 var keywords = function(){ 9890 function kw(type) {return {type: type, style: "keyword"};} 9891 var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); 9892 var operator = kw("operator"), atom = {type: "atom", style: "atom"}; 9893 9894 var jsKeywords = { 9895 "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, 9896 "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, 9897 "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), 9898 "function": kw("function"), "catch": kw("catch"), 9899 "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), 9900 "in": operator, "typeof": operator, "instanceof": operator, 9901 "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, 9902 "this": kw("this"), "class": kw("class"), "super": kw("atom"), 9903 "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, 9904 "await": C 9905 }; 9906 9907 // Extend the 'normal' keywords with the TypeScript language extensions 9908 if (isTS) { 9909 var type = {type: "variable", style: "type"}; 9910 var tsKeywords = { 9911 // object-like things 9912 "interface": kw("class"), 9913 "implements": C, 9914 "namespace": C, 9915 "module": kw("module"), 9916 "enum": kw("module"), 9917 9918 // scope modifiers 9919 "public": kw("modifier"), 9920 "private": kw("modifier"), 9921 "protected": kw("modifier"), 9922 "abstract": kw("modifier"), 9923 "readonly": kw("modifier"), 9924 9925 // types 9926 "string": type, "number": type, "boolean": type, "any": type 9927 }; 9928 9929 for (var attr in tsKeywords) { 9930 jsKeywords[attr] = tsKeywords[attr]; 9931 } 9932 } 9933 9934 return jsKeywords; 9935 }(); 9936 9937 var isOperatorChar = /[+\-*&%=<>!?|~^@]/; 9938 var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; 9939 9940 function readRegexp(stream) { 9941 var escaped = false, next, inSet = false; 9942 while ((next = stream.next()) != null) { 9943 if (!escaped) { 9944 if (next == "/" && !inSet) return; 9945 if (next == "[") inSet = true; 9946 else if (inSet && next == "]") inSet = false; 9947 } 9948 escaped = !escaped && next == "\\"; 9949 } 9950 } 9951 9952 // Used as scratch variables to communicate multiple values without 9953 // consing up tons of objects. 9954 var type, content; 9955 function ret(tp, style, cont) { 9956 type = tp; content = cont; 9957 return style; 9958 } 9959 function tokenBase(stream, state) { 9960 var ch = stream.next(); 9961 if (ch == '"' || ch == "'") { 9962 state.tokenize = tokenString(ch); 9963 return state.tokenize(stream, state); 9964 } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { 9965 return ret("number", "number"); 9966 } else if (ch == "." && stream.match("..")) { 9967 return ret("spread", "meta"); 9968 } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { 9969 return ret(ch); 9970 } else if (ch == "=" && stream.eat(">")) { 9971 return ret("=>", "operator"); 9972 } else if (ch == "0" && stream.eat(/x/i)) { 9973 stream.eatWhile(/[\da-f]/i); 9974 return ret("number", "number"); 9975 } else if (ch == "0" && stream.eat(/o/i)) { 9976 stream.eatWhile(/[0-7]/i); 9977 return ret("number", "number"); 9978 } else if (ch == "0" && stream.eat(/b/i)) { 9979 stream.eatWhile(/[01]/i); 9980 return ret("number", "number"); 9981 } else if (/\d/.test(ch)) { 9982 stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); 9983 return ret("number", "number"); 9984 } else if (ch == "/") { 9985 if (stream.eat("*")) { 9986 state.tokenize = tokenComment; 9987 return tokenComment(stream, state); 9988 } else if (stream.eat("/")) { 9989 stream.skipToEnd(); 9990 return ret("comment", "comment"); 9991 } else if (expressionAllowed(stream, state, 1)) { 9992 readRegexp(stream); 9993 stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); 9994 return ret("regexp", "string-2"); 9995 } else { 9996 stream.eat("="); 9997 return ret("operator", "operator", stream.current()); 9998 } 9999 } else if (ch == "`") { 10000 state.tokenize = tokenQuasi; 10001 return tokenQuasi(stream, state); 10002 } else if (ch == "#") { 10003 stream.skipToEnd(); 10004 return ret("error", "error"); 10005 } else if (isOperatorChar.test(ch)) { 10006 if (ch != ">" || !state.lexical || state.lexical.type != ">") { 10007 if (stream.eat("=")) { 10008 if (ch == "!" || ch == "=") stream.eat("=") 10009 } else if (/[<>*+\-]/.test(ch)) { 10010 stream.eat(ch) 10011 if (ch == ">") stream.eat(ch) 10012 } 10013 } 10014 return ret("operator", "operator", stream.current()); 10015 } else if (wordRE.test(ch)) { 10016 stream.eatWhile(wordRE); 10017 var word = stream.current() 10018 if (state.lastType != ".") { 10019 if (keywords.propertyIsEnumerable(word)) { 10020 var kw = keywords[word] 10021 return ret(kw.type, kw.style, word) 10022 } 10023 if (word == "async" && stream.match(/^\s*[\(\w]/, false)) 10024 return ret("async", "keyword", word) 10025 } 10026 return ret("variable", "variable", word) 10027 } 10028 } 10029 10030 function tokenString(quote) { 10031 return function(stream, state) { 10032 var escaped = false, next; 10033 if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ 10034 state.tokenize = tokenBase; 10035 return ret("jsonld-keyword", "meta"); 10036 } 10037 while ((next = stream.next()) != null) { 10038 if (next == quote && !escaped) break; 10039 escaped = !escaped && next == "\\"; 10040 } 10041 if (!escaped) state.tokenize = tokenBase; 10042 return ret("string", "string"); 10043 }; 10044 } 10045 10046 function tokenComment(stream, state) { 10047 var maybeEnd = false, ch; 10048 while (ch = stream.next()) { 10049 if (ch == "/" && maybeEnd) { 10050 state.tokenize = tokenBase; 10051 break; 10052 } 10053 maybeEnd = (ch == "*"); 10054 } 10055 return ret("comment", "comment"); 10056 } 10057 10058 function tokenQuasi(stream, state) { 10059 var escaped = false, next; 10060 while ((next = stream.next()) != null) { 10061 if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { 10062 state.tokenize = tokenBase; 10063 break; 10064 } 10065 escaped = !escaped && next == "\\"; 10066 } 10067 return ret("quasi", "string-2", stream.current()); 10068 } 10069 10070 var brackets = "([{}])"; 10071 // This is a crude lookahead trick to try and notice that we're 10072 // parsing the argument patterns for a fat-arrow function before we 10073 // actually hit the arrow token. It only works if the arrow is on 10074 // the same line as the arguments and there's no strange noise 10075 // (comments) in between. Fallback is to only notice when we hit the 10076 // arrow, and not declare the arguments as locals for the arrow 10077 // body. 10078 function findFatArrow(stream, state) { 10079 if (state.fatArrowAt) state.fatArrowAt = null; 10080 var arrow = stream.string.indexOf("=>", stream.start); 10081 if (arrow < 0) return; 10082 10083 if (isTS) { // Try to skip TypeScript return type declarations after the arguments 10084 var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) 10085 if (m) arrow = m.index 10086 } 10087 10088 var depth = 0, sawSomething = false; 10089 for (var pos = arrow - 1; pos >= 0; --pos) { 10090 var ch = stream.string.charAt(pos); 10091 var bracket = brackets.indexOf(ch); 10092 if (bracket >= 0 && bracket < 3) { 10093 if (!depth) { ++pos; break; } 10094 if (--depth == 0) { if (ch == "(") sawSomething = true; break; } 10095 } else if (bracket >= 3 && bracket < 6) { 10096 ++depth; 10097 } else if (wordRE.test(ch)) { 10098 sawSomething = true; 10099 } else if (/["'\/]/.test(ch)) { 10100 return; 10101 } else if (sawSomething && !depth) { 10102 ++pos; 10103 break; 10104 } 10105 } 10106 if (sawSomething && !depth) state.fatArrowAt = pos; 10107 } 10108 10109 // Parser 10110 10111 var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; 10112 10113 function JSLexical(indented, column, type, align, prev, info) { 10114 this.indented = indented; 10115 this.column = column; 10116 this.type = type; 10117 this.prev = prev; 10118 this.info = info; 10119 if (align != null) this.align = align; 10120 } 10121 10122 function inScope(state, varname) { 10123 for (var v = state.localVars; v; v = v.next) 10124 if (v.name == varname) return true; 10125 for (var cx = state.context; cx; cx = cx.prev) { 10126 for (var v = cx.vars; v; v = v.next) 10127 if (v.name == varname) return true; 10128 } 10129 } 10130 10131 function parseJS(state, style, type, content, stream) { 10132 var cc = state.cc; 10133 // Communicate our context to the combinators. 10134 // (Less wasteful than consing up a hundred closures on every call.) 10135 cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; 10136 10137 if (!state.lexical.hasOwnProperty("align")) 10138 state.lexical.align = true; 10139 10140 while(true) { 10141 var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; 10142 if (combinator(type, content)) { 10143 while(cc.length && cc[cc.length - 1].lex) 10144 cc.pop()(); 10145 if (cx.marked) return cx.marked; 10146 if (type == "variable" && inScope(state, content)) return "variable-2"; 10147 return style; 10148 } 10149 } 10150 } 10151 10152 // Combinator utils 10153 10154 var cx = {state: null, column: null, marked: null, cc: null}; 10155 function pass() { 10156 for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); 10157 } 10158 function cont() { 10159 pass.apply(null, arguments); 10160 return true; 10161 } 10162 function register(varname) { 10163 function inList(list) { 10164 for (var v = list; v; v = v.next) 10165 if (v.name == varname) return true; 10166 return false; 10167 } 10168 var state = cx.state; 10169 cx.marked = "def"; 10170 if (state.context) { 10171 if (inList(state.localVars)) return; 10172 state.localVars = {name: varname, next: state.localVars}; 10173 } else { 10174 if (inList(state.globalVars)) return; 10175 if (parserConfig.globalVars) 10176 state.globalVars = {name: varname, next: state.globalVars}; 10177 } 10178 } 10179 10180 // Combinators 10181 10182 var defaultVars = {name: "this", next: {name: "arguments"}}; 10183 function pushcontext() { 10184 cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; 10185 cx.state.localVars = defaultVars; 10186 } 10187 function popcontext() { 10188 cx.state.localVars = cx.state.context.vars; 10189 cx.state.context = cx.state.context.prev; 10190 } 10191 function pushlex(type, info) { 10192 var result = function() { 10193 var state = cx.state, indent = state.indented; 10194 if (state.lexical.type == "stat") indent = state.lexical.indented; 10195 else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) 10196 indent = outer.indented; 10197 state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); 10198 }; 10199 result.lex = true; 10200 return result; 10201 } 10202 function poplex() { 10203 var state = cx.state; 10204 if (state.lexical.prev) { 10205 if (state.lexical.type == ")") 10206 state.indented = state.lexical.indented; 10207 state.lexical = state.lexical.prev; 10208 } 10209 } 10210 poplex.lex = true; 10211 10212 function expect(wanted) { 10213 function exp(type) { 10214 if (type == wanted) return cont(); 10215 else if (wanted == ";") return pass(); 10216 else return cont(exp); 10217 }; 10218 return exp; 10219 } 10220 10221 function statement(type, value) { 10222 if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); 10223 if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); 10224 if (type == "keyword b") return cont(pushlex("form"), statement, poplex); 10225 if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); 10226 if (type == "debugger") return cont(expect(";")); 10227 if (type == "{") return cont(pushlex("}"), block, poplex); 10228 if (type == ";") return cont(); 10229 if (type == "if") { 10230 if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) 10231 cx.state.cc.pop()(); 10232 return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); 10233 } 10234 if (type == "function") return cont(functiondef); 10235 if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); 10236 if (type == "variable") { 10237 if (isTS && value == "type") { 10238 cx.marked = "keyword" 10239 return cont(typeexpr, expect("operator"), typeexpr, expect(";")); 10240 } if (isTS && value == "declare") { 10241 cx.marked = "keyword" 10242 return cont(statement) 10243 } else { 10244 return cont(pushlex("stat"), maybelabel); 10245 } 10246 } 10247 if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), 10248 block, poplex, poplex); 10249 if (type == "case") return cont(expression, expect(":")); 10250 if (type == "default") return cont(expect(":")); 10251 if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), 10252 statement, poplex, popcontext); 10253 if (type == "class") return cont(pushlex("form"), className, poplex); 10254 if (type == "export") return cont(pushlex("stat"), afterExport, poplex); 10255 if (type == "import") return cont(pushlex("stat"), afterImport, poplex); 10256 if (type == "module") return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) 10257 if (type == "async") return cont(statement) 10258 if (value == "@") return cont(expression, statement) 10259 return pass(pushlex("stat"), expression, expect(";"), poplex); 10260 } 10261 function expression(type) { 10262 return expressionInner(type, false); 10263 } 10264 function expressionNoComma(type) { 10265 return expressionInner(type, true); 10266 } 10267 function parenExpr(type) { 10268 if (type != "(") return pass() 10269 return cont(pushlex(")"), expression, expect(")"), poplex) 10270 } 10271 function expressionInner(type, noComma) { 10272 if (cx.state.fatArrowAt == cx.stream.start) { 10273 var body = noComma ? arrowBodyNoComma : arrowBody; 10274 if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); 10275 else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); 10276 } 10277 10278 var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; 10279 if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); 10280 if (type == "function") return cont(functiondef, maybeop); 10281 if (type == "class") return cont(pushlex("form"), classExpression, poplex); 10282 if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); 10283 if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); 10284 if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); 10285 if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); 10286 if (type == "{") return contCommasep(objprop, "}", null, maybeop); 10287 if (type == "quasi") return pass(quasi, maybeop); 10288 if (type == "new") return cont(maybeTarget(noComma)); 10289 return cont(); 10290 } 10291 function maybeexpression(type) { 10292 if (type.match(/[;\}\)\],]/)) return pass(); 10293 return pass(expression); 10294 } 10295 10296 function maybeoperatorComma(type, value) { 10297 if (type == ",") return cont(expression); 10298 return maybeoperatorNoComma(type, value, false); 10299 } 10300 function maybeoperatorNoComma(type, value, noComma) { 10301 var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; 10302 var expr = noComma == false ? expression : expressionNoComma; 10303 if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); 10304 if (type == "operator") { 10305 if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); 10306 if (value == "?") return cont(expression, expect(":"), expr); 10307 return cont(expr); 10308 } 10309 if (type == "quasi") { return pass(quasi, me); } 10310 if (type == ";") return; 10311 if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); 10312 if (type == ".") return cont(property, me); 10313 if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); 10314 if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } 10315 if (type == "regexp") { 10316 cx.state.lastType = cx.marked = "operator" 10317 cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) 10318 return cont(expr) 10319 } 10320 } 10321 function quasi(type, value) { 10322 if (type != "quasi") return pass(); 10323 if (value.slice(value.length - 2) != "${") return cont(quasi); 10324 return cont(expression, continueQuasi); 10325 } 10326 function continueQuasi(type) { 10327 if (type == "}") { 10328 cx.marked = "string-2"; 10329 cx.state.tokenize = tokenQuasi; 10330 return cont(quasi); 10331 } 10332 } 10333 function arrowBody(type) { 10334 findFatArrow(cx.stream, cx.state); 10335 return pass(type == "{" ? statement : expression); 10336 } 10337 function arrowBodyNoComma(type) { 10338 findFatArrow(cx.stream, cx.state); 10339 return pass(type == "{" ? statement : expressionNoComma); 10340 } 10341 function maybeTarget(noComma) { 10342 return function(type) { 10343 if (type == ".") return cont(noComma ? targetNoComma : target); 10344 else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) 10345 else return pass(noComma ? expressionNoComma : expression); 10346 }; 10347 } 10348 function target(_, value) { 10349 if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } 10350 } 10351 function targetNoComma(_, value) { 10352 if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } 10353 } 10354 function maybelabel(type) { 10355 if (type == ":") return cont(poplex, statement); 10356 return pass(maybeoperatorComma, expect(";"), poplex); 10357 } 10358 function property(type) { 10359 if (type == "variable") {cx.marked = "property"; return cont();} 10360 } 10361 function objprop(type, value) { 10362 if (type == "async") { 10363 cx.marked = "property"; 10364 return cont(objprop); 10365 } else if (type == "variable" || cx.style == "keyword") { 10366 cx.marked = "property"; 10367 if (value == "get" || value == "set") return cont(getterSetter); 10368 var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params 10369 if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) 10370 cx.state.fatArrowAt = cx.stream.pos + m[0].length 10371 return cont(afterprop); 10372 } else if (type == "number" || type == "string") { 10373 cx.marked = jsonldMode ? "property" : (cx.style + " property"); 10374 return cont(afterprop); 10375 } else if (type == "jsonld-keyword") { 10376 return cont(afterprop); 10377 } else if (type == "modifier") { 10378 return cont(objprop) 10379 } else if (type == "[") { 10380 return cont(expression, expect("]"), afterprop); 10381 } else if (type == "spread") { 10382 return cont(expressionNoComma, afterprop); 10383 } else if (value == "*") { 10384 cx.marked = "keyword"; 10385 return cont(objprop); 10386 } else if (type == ":") { 10387 return pass(afterprop) 10388 } 10389 } 10390 function getterSetter(type) { 10391 if (type != "variable") return pass(afterprop); 10392 cx.marked = "property"; 10393 return cont(functiondef); 10394 } 10395 function afterprop(type) { 10396 if (type == ":") return cont(expressionNoComma); 10397 if (type == "(") return pass(functiondef); 10398 } 10399 function commasep(what, end, sep) { 10400 function proceed(type, value) { 10401 if (sep ? sep.indexOf(type) > -1 : type == ",") { 10402 var lex = cx.state.lexical; 10403 if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; 10404 return cont(function(type, value) { 10405 if (type == end || value == end) return pass() 10406 return pass(what) 10407 }, proceed); 10408 } 10409 if (type == end || value == end) return cont(); 10410 return cont(expect(end)); 10411 } 10412 return function(type, value) { 10413 if (type == end || value == end) return cont(); 10414 return pass(what, proceed); 10415 }; 10416 } 10417 function contCommasep(what, end, info) { 10418 for (var i = 3; i < arguments.length; i++) 10419 cx.cc.push(arguments[i]); 10420 return cont(pushlex(end, info), commasep(what, end), poplex); 10421 } 10422 function block(type) { 10423 if (type == "}") return cont(); 10424 return pass(statement, block); 10425 } 10426 function maybetype(type, value) { 10427 if (isTS) { 10428 if (type == ":") return cont(typeexpr); 10429 if (value == "?") return cont(maybetype); 10430 } 10431 } 10432 function typeexpr(type, value) { 10433 if (type == "variable" || value == "void") { 10434 if (value == "keyof") { 10435 cx.marked = "keyword" 10436 return cont(typeexpr) 10437 } else { 10438 cx.marked = "type" 10439 return cont(afterType) 10440 } 10441 } 10442 if (type == "string" || type == "number" || type == "atom") return cont(afterType); 10443 if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) 10444 if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) 10445 if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType) 10446 } 10447 function maybeReturnType(type) { 10448 if (type == "=>") return cont(typeexpr) 10449 } 10450 function typeprop(type, value) { 10451 if (type == "variable" || cx.style == "keyword") { 10452 cx.marked = "property" 10453 return cont(typeprop) 10454 } else if (value == "?") { 10455 return cont(typeprop) 10456 } else if (type == ":") { 10457 return cont(typeexpr) 10458 } else if (type == "[") { 10459 return cont(expression, maybetype, expect("]"), typeprop) 10460 } 10461 } 10462 function typearg(type) { 10463 if (type == "variable") return cont(typearg) 10464 else if (type == ":") return cont(typeexpr) 10465 } 10466 function afterType(type, value) { 10467 if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) 10468 if (value == "|" || type == ".") return cont(typeexpr) 10469 if (type == "[") return cont(expect("]"), afterType) 10470 if (value == "extends") return cont(typeexpr) 10471 } 10472 function maybeTypeArgs(_, value) { 10473 if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) 10474 } 10475 function vardef() { 10476 return pass(pattern, maybetype, maybeAssign, vardefCont); 10477 } 10478 function pattern(type, value) { 10479 if (type == "modifier") return cont(pattern) 10480 if (type == "variable") { register(value); return cont(); } 10481 if (type == "spread") return cont(pattern); 10482 if (type == "[") return contCommasep(pattern, "]"); 10483 if (type == "{") return contCommasep(proppattern, "}"); 10484 } 10485 function proppattern(type, value) { 10486 if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { 10487 register(value); 10488 return cont(maybeAssign); 10489 } 10490 if (type == "variable") cx.marked = "property"; 10491 if (type == "spread") return cont(pattern); 10492 if (type == "}") return pass(); 10493 return cont(expect(":"), pattern, maybeAssign); 10494 } 10495 function maybeAssign(_type, value) { 10496 if (value == "=") return cont(expressionNoComma); 10497 } 10498 function vardefCont(type) { 10499 if (type == ",") return cont(vardef); 10500 } 10501 function maybeelse(type, value) { 10502 if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); 10503 } 10504 function forspec(type) { 10505 if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); 10506 } 10507 function forspec1(type) { 10508 if (type == "var") return cont(vardef, expect(";"), forspec2); 10509 if (type == ";") return cont(forspec2); 10510 if (type == "variable") return cont(formaybeinof); 10511 return pass(expression, expect(";"), forspec2); 10512 } 10513 function formaybeinof(_type, value) { 10514 if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } 10515 return cont(maybeoperatorComma, forspec2); 10516 } 10517 function forspec2(type, value) { 10518 if (type == ";") return cont(forspec3); 10519 if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } 10520 return pass(expression, expect(";"), forspec3); 10521 } 10522 function forspec3(type) { 10523 if (type != ")") cont(expression); 10524 } 10525 function functiondef(type, value) { 10526 if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} 10527 if (type == "variable") {register(value); return cont(functiondef);} 10528 if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext); 10529 if (isTS && value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, functiondef) 10530 } 10531 function funarg(type, value) { 10532 if (value == "@") cont(expression, funarg) 10533 if (type == "spread" || type == "modifier") return cont(funarg); 10534 return pass(pattern, maybetype, maybeAssign); 10535 } 10536 function classExpression(type, value) { 10537 // Class expressions may have an optional name. 10538 if (type == "variable") return className(type, value); 10539 return classNameAfter(type, value); 10540 } 10541 function className(type, value) { 10542 if (type == "variable") {register(value); return cont(classNameAfter);} 10543 } 10544 function classNameAfter(type, value) { 10545 if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, classNameAfter) 10546 if (value == "extends" || value == "implements" || (isTS && type == ",")) 10547 return cont(isTS ? typeexpr : expression, classNameAfter); 10548 if (type == "{") return cont(pushlex("}"), classBody, poplex); 10549 } 10550 function classBody(type, value) { 10551 if (type == "modifier" || type == "async" || 10552 (type == "variable" && 10553 (value == "static" || value == "get" || value == "set") && 10554 cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { 10555 cx.marked = "keyword"; 10556 return cont(classBody); 10557 } 10558 if (type == "variable" || cx.style == "keyword") { 10559 cx.marked = "property"; 10560 return cont(isTS ? classfield : functiondef, classBody); 10561 } 10562 if (type == "[") 10563 return cont(expression, expect("]"), isTS ? classfield : functiondef, classBody) 10564 if (value == "*") { 10565 cx.marked = "keyword"; 10566 return cont(classBody); 10567 } 10568 if (type == ";") return cont(classBody); 10569 if (type == "}") return cont(); 10570 if (value == "@") return cont(expression, classBody) 10571 } 10572 function classfield(type, value) { 10573 if (value == "?") return cont(classfield) 10574 if (type == ":") return cont(typeexpr, maybeAssign) 10575 if (value == "=") return cont(expressionNoComma) 10576 return pass(functiondef) 10577 } 10578 function afterExport(type, value) { 10579 if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } 10580 if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } 10581 if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); 10582 return pass(statement); 10583 } 10584 function exportField(type, value) { 10585 if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } 10586 if (type == "variable") return pass(expressionNoComma, exportField); 10587 } 10588 function afterImport(type) { 10589 if (type == "string") return cont(); 10590 return pass(importSpec, maybeMoreImports, maybeFrom); 10591 } 10592 function importSpec(type, value) { 10593 if (type == "{") return contCommasep(importSpec, "}"); 10594 if (type == "variable") register(value); 10595 if (value == "*") cx.marked = "keyword"; 10596 return cont(maybeAs); 10597 } 10598 function maybeMoreImports(type) { 10599 if (type == ",") return cont(importSpec, maybeMoreImports) 10600 } 10601 function maybeAs(_type, value) { 10602 if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } 10603 } 10604 function maybeFrom(_type, value) { 10605 if (value == "from") { cx.marked = "keyword"; return cont(expression); } 10606 } 10607 function arrayLiteral(type) { 10608 if (type == "]") return cont(); 10609 return pass(commasep(expressionNoComma, "]")); 10610 } 10611 10612 function isContinuedStatement(state, textAfter) { 10613 return state.lastType == "operator" || state.lastType == "," || 10614 isOperatorChar.test(textAfter.charAt(0)) || 10615 /[,.]/.test(textAfter.charAt(0)); 10616 } 10617 10618 function expressionAllowed(stream, state, backUp) { 10619 return state.tokenize == tokenBase && 10620 /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || 10621 (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) 10622 } 10623 10624 // Interface 10625 10626 return { 10627 startState: function(basecolumn) { 10628 var state = { 10629 tokenize: tokenBase, 10630 lastType: "sof", 10631 cc: [], 10632 lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), 10633 localVars: parserConfig.localVars, 10634 context: parserConfig.localVars && {vars: parserConfig.localVars}, 10635 indented: basecolumn || 0 10636 }; 10637 if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") 10638 state.globalVars = parserConfig.globalVars; 10639 return state; 10640 }, 10641 10642 token: function(stream, state) { 10643 if (stream.sol()) { 10644 if (!state.lexical.hasOwnProperty("align")) 10645 state.lexical.align = false; 10646 state.indented = stream.indentation(); 10647 findFatArrow(stream, state); 10648 } 10649 if (state.tokenize != tokenComment && stream.eatSpace()) return null; 10650 var style = state.tokenize(stream, state); 10651 if (type == "comment") return style; 10652 state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; 10653 return parseJS(state, style, type, content, stream); 10654 }, 10655 10656 indent: function(state, textAfter) { 10657 if (state.tokenize == tokenComment) return CodeMirror.Pass; 10658 if (state.tokenize != tokenBase) return 0; 10659 var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top 10660 // Kludge to prevent 'maybelse' from blocking lexical scope pops 10661 if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { 10662 var c = state.cc[i]; 10663 if (c == poplex) lexical = lexical.prev; 10664 else if (c != maybeelse) break; 10665 } 10666 while ((lexical.type == "stat" || lexical.type == "form") && 10667 (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && 10668 (top == maybeoperatorComma || top == maybeoperatorNoComma) && 10669 !/^[,\.=+\-*:?[\(]/.test(textAfter)))) 10670 lexical = lexical.prev; 10671 if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") 10672 lexical = lexical.prev; 10673 var type = lexical.type, closing = firstChar == type; 10674 10675 if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); 10676 else if (type == "form" && firstChar == "{") return lexical.indented; 10677 else if (type == "form") return lexical.indented + indentUnit; 10678 else if (type == "stat") 10679 return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); 10680 else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) 10681 return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); 10682 else if (lexical.align) return lexical.column + (closing ? 0 : 1); 10683 else return lexical.indented + (closing ? 0 : indentUnit); 10684 }, 10685 10686 electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, 10687 blockCommentStart: jsonMode ? null : "/*", 10688 blockCommentEnd: jsonMode ? null : "*/", 10689 blockCommentContinue: jsonMode ? null : " * ", 10690 lineComment: jsonMode ? null : "//", 10691 fold: "brace", 10692 closeBrackets: "()[]{}''\"\"``", 10693 10694 helperType: jsonMode ? "json" : "javascript", 10695 jsonldMode: jsonldMode, 10696 jsonMode: jsonMode, 10697 10698 expressionAllowed: expressionAllowed, 10699 10700 skipExpression: function(state) { 10701 var top = state.cc[state.cc.length - 1] 10702 if (top == expression || top == expressionNoComma) state.cc.pop() 10703 } 10704 }; 10705 }); 10706 10707 CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); 10708 10709 CodeMirror.defineMIME("text/javascript", "javascript"); 10710 CodeMirror.defineMIME("text/ecmascript", "javascript"); 10711 CodeMirror.defineMIME("application/javascript", "javascript"); 10712 CodeMirror.defineMIME("application/x-javascript", "javascript"); 10713 CodeMirror.defineMIME("application/ecmascript", "javascript"); 10714 CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); 10715 CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); 10716 CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); 10717 CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); 10718 CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); 10719 10720 }); 10721 10722 },{"../../lib/codemirror":2}],5:[function(require,module,exports){ 52 10723 (function (process){ 53 10724 /** … … 923 11594 924 11595 }).call(this,require('_process')) 925 },{"_process":2 6,"fbjs/lib/emptyObject":13,"fbjs/lib/invariant":18,"fbjs/lib/warning":24,"object-assign":25}],3:[function(require,module,exports){11596 },{"_process":29,"fbjs/lib/emptyObject":16,"fbjs/lib/invariant":21,"fbjs/lib/warning":27,"object-assign":28}],6:[function(require,module,exports){ 926 11597 /** 927 11598 * Copyright (c) 2013-present, Facebook, Inc. … … 953 11624 ); 954 11625 955 },{"./factory": 2,"react":44}],4:[function(require,module,exports){11626 },{"./factory":5,"react":49}],7:[function(require,module,exports){ 956 11627 'use strict'; 957 11628 … … 971 11642 } 972 11643 module.exports = exports['default']; 973 },{"./hasClass": 5}],5:[function(require,module,exports){11644 },{"./hasClass":8}],8:[function(require,module,exports){ 974 11645 "use strict"; 975 11646 … … 982 11653 } 983 11654 module.exports = exports["default"]; 984 },{}], 6:[function(require,module,exports){11655 },{}],9:[function(require,module,exports){ 985 11656 'use strict'; 986 11657 … … 988 11659 if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); 989 11660 }; 990 },{}], 7:[function(require,module,exports){11661 },{}],10:[function(require,module,exports){ 991 11662 (function (process){ 992 11663 'use strict'; … … 1065 11736 module.exports = EventListener; 1066 11737 }).call(this,require('_process')) 1067 },{"./emptyFunction":1 2,"_process":26}],8:[function(require,module,exports){11738 },{"./emptyFunction":15,"_process":29}],11:[function(require,module,exports){ 1068 11739 /** 1069 11740 * Copyright (c) 2013-present, Facebook, Inc. … … 1099 11770 1100 11771 module.exports = ExecutionEnvironment; 1101 },{}], 9:[function(require,module,exports){11772 },{}],12:[function(require,module,exports){ 1102 11773 "use strict"; 1103 11774 … … 1129 11800 1130 11801 module.exports = camelize; 1131 },{}],1 0:[function(require,module,exports){11802 },{}],13:[function(require,module,exports){ 1132 11803 /** 1133 11804 * Copyright (c) 2013-present, Facebook, Inc. … … 1167 11838 1168 11839 module.exports = camelizeStyleName; 1169 },{"./camelize": 9}],11:[function(require,module,exports){11840 },{"./camelize":12}],14:[function(require,module,exports){ 1170 11841 'use strict'; 1171 11842 … … 1205 11876 1206 11877 module.exports = containsNode; 1207 },{"./isTextNode":2 0}],12:[function(require,module,exports){11878 },{"./isTextNode":23}],15:[function(require,module,exports){ 1208 11879 "use strict"; 1209 11880 … … 1242 11913 1243 11914 module.exports = emptyFunction; 1244 },{}],1 3:[function(require,module,exports){11915 },{}],16:[function(require,module,exports){ 1245 11916 (function (process){ 1246 11917 /** … … 1262 11933 module.exports = emptyObject; 1263 11934 }).call(this,require('_process')) 1264 },{"_process":2 6}],14:[function(require,module,exports){11935 },{"_process":29}],17:[function(require,module,exports){ 1265 11936 /** 1266 11937 * Copyright (c) 2013-present, Facebook, Inc. … … 1287 11958 1288 11959 module.exports = focusNode; 1289 },{}],1 5:[function(require,module,exports){11960 },{}],18:[function(require,module,exports){ 1290 11961 'use strict'; 1291 11962 … … 1324 11995 1325 11996 module.exports = getActiveElement; 1326 },{}],1 6:[function(require,module,exports){11997 },{}],19:[function(require,module,exports){ 1327 11998 'use strict'; 1328 11999 … … 1355 12026 1356 12027 module.exports = hyphenate; 1357 },{}], 17:[function(require,module,exports){12028 },{}],20:[function(require,module,exports){ 1358 12029 /** 1359 12030 * Copyright (c) 2013-present, Facebook, Inc. … … 1392 12063 1393 12064 module.exports = hyphenateStyleName; 1394 },{"./hyphenate":1 6}],18:[function(require,module,exports){12065 },{"./hyphenate":19}],21:[function(require,module,exports){ 1395 12066 (function (process){ 1396 12067 /** … … 1448 12119 module.exports = invariant; 1449 12120 }).call(this,require('_process')) 1450 },{"_process":2 6}],19:[function(require,module,exports){12121 },{"_process":29}],22:[function(require,module,exports){ 1451 12122 'use strict'; 1452 12123 … … 1471 12142 1472 12143 module.exports = isNode; 1473 },{}],2 0:[function(require,module,exports){12144 },{}],23:[function(require,module,exports){ 1474 12145 'use strict'; 1475 12146 … … 1494 12165 1495 12166 module.exports = isTextNode; 1496 },{"./isNode": 19}],21:[function(require,module,exports){12167 },{"./isNode":22}],24:[function(require,module,exports){ 1497 12168 /** 1498 12169 * Copyright (c) 2013-present, Facebook, Inc. … … 1515 12186 1516 12187 module.exports = performance || {}; 1517 },{"./ExecutionEnvironment": 8}],22:[function(require,module,exports){12188 },{"./ExecutionEnvironment":11}],25:[function(require,module,exports){ 1518 12189 'use strict'; 1519 12190 … … 1547 12218 1548 12219 module.exports = performanceNow; 1549 },{"./performance":2 1}],23:[function(require,module,exports){12220 },{"./performance":24}],26:[function(require,module,exports){ 1550 12221 /** 1551 12222 * Copyright (c) 2013-present, Facebook, Inc. … … 1613 12284 1614 12285 module.exports = shallowEqual; 1615 },{}],2 4:[function(require,module,exports){12286 },{}],27:[function(require,module,exports){ 1616 12287 (function (process){ 1617 12288 /** … … 1678 12349 module.exports = warning; 1679 12350 }).call(this,require('_process')) 1680 },{"./emptyFunction":1 2,"_process":26}],25:[function(require,module,exports){12351 },{"./emptyFunction":15,"_process":29}],28:[function(require,module,exports){ 1681 12352 /* 1682 12353 object-assign … … 1770 12441 }; 1771 12442 1772 },{}],2 6:[function(require,module,exports){12443 },{}],29:[function(require,module,exports){ 1773 12444 // shim for using process in browser 1774 12445 var process = module.exports = {}; … … 1956 12627 process.umask = function() { return 0; }; 1957 12628 1958 },{}], 27:[function(require,module,exports){12629 },{}],30:[function(require,module,exports){ 1959 12630 (function (process){ 1960 12631 /** … … 2019 12690 2020 12691 }).call(this,require('_process')) 2021 },{"./lib/ReactPropTypesSecret":3 1,"_process":26,"fbjs/lib/invariant":18,"fbjs/lib/warning":24}],28:[function(require,module,exports){12692 },{"./lib/ReactPropTypesSecret":34,"_process":29,"fbjs/lib/invariant":21,"fbjs/lib/warning":27}],31:[function(require,module,exports){ 2022 12693 /** 2023 12694 * Copyright (c) 2013-present, Facebook, Inc. … … 2079 12750 }; 2080 12751 2081 },{"./lib/ReactPropTypesSecret":3 1,"fbjs/lib/emptyFunction":12,"fbjs/lib/invariant":18}],29:[function(require,module,exports){12752 },{"./lib/ReactPropTypesSecret":34,"fbjs/lib/emptyFunction":15,"fbjs/lib/invariant":21}],32:[function(require,module,exports){ 2082 12753 (function (process){ 2083 12754 /** … … 2625 13296 2626 13297 }).call(this,require('_process')) 2627 },{"./checkPropTypes": 27,"./lib/ReactPropTypesSecret":31,"_process":26,"fbjs/lib/emptyFunction":12,"fbjs/lib/invariant":18,"fbjs/lib/warning":24,"object-assign":25}],30:[function(require,module,exports){13298 },{"./checkPropTypes":30,"./lib/ReactPropTypesSecret":34,"_process":29,"fbjs/lib/emptyFunction":15,"fbjs/lib/invariant":21,"fbjs/lib/warning":27,"object-assign":28}],33:[function(require,module,exports){ 2628 13299 (function (process){ 2629 13300 /** … … 2657 13328 2658 13329 }).call(this,require('_process')) 2659 },{"./factoryWithThrowingShims": 28,"./factoryWithTypeCheckers":29,"_process":26}],31:[function(require,module,exports){13330 },{"./factoryWithThrowingShims":31,"./factoryWithTypeCheckers":32,"_process":29}],34:[function(require,module,exports){ 2660 13331 /** 2661 13332 * Copyright (c) 2013-present, Facebook, Inc. … … 2671 13342 module.exports = ReactPropTypesSecret; 2672 13343 2673 },{}],3 2:[function(require,module,exports){13344 },{}],35:[function(require,module,exports){ 2674 13345 /** 2675 13346 * Copyright (c) 2013-present, Facebook, Inc. … … 2829 13500 module.exports = LinkedStateMixin; 2830 13501 2831 },{}],33:[function(require,module,exports){ 13502 },{}],36:[function(require,module,exports){ 13503 /** 13504 * Copyright (c) 2015-present, Facebook, Inc. 13505 * 13506 * This source code is licensed under the MIT license found in the 13507 * LICENSE file in the root directory of this source tree. 13508 * 13509 */ 13510 13511 'use strict'; 13512 13513 var shallowEqual = require('fbjs/lib/shallowEqual'); 13514 13515 module.exports = { 13516 shouldComponentUpdate: function(nextProps, nextState) { 13517 return ( 13518 !shallowEqual(this.props, nextProps) || 13519 !shallowEqual(this.state, nextState) 13520 ); 13521 } 13522 }; 13523 13524 },{"fbjs/lib/shallowEqual":26}],37:[function(require,module,exports){ 13525 (function (global){ 13526 'use strict'; 13527 var __extends = (this && this.__extends) || (function () { 13528 var extendStatics = Object.setPrototypeOf || 13529 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 13530 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 13531 return function (d, b) { 13532 extendStatics(d, b); 13533 function __() { this.constructor = d; } 13534 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 13535 }; 13536 })(); 13537 Object.defineProperty(exports, '__esModule', { value: true }); 13538 var React = require('react'); 13539 var SERVER_RENDERED = (typeof navigator === 'undefined' || global['PREVENT_CODEMIRROR_RENDER'] === true); 13540 var cm; 13541 if (!SERVER_RENDERED) { 13542 cm = require('codemirror'); 13543 } 13544 var Helper = (function () { 13545 function Helper() { 13546 } 13547 Helper.equals = function (x, y) { 13548 var _this = this; 13549 var ok = Object.keys, tx = typeof x, ty = typeof y; 13550 return x && y && tx === 'object' && tx === ty ? (ok(x).length === ok(y).length && 13551 ok(x).every(function (key) { return _this.equals(x[key], y[key]); })) : (x === y); 13552 }; 13553 return Helper; 13554 }()); 13555 var Shared = (function () { 13556 function Shared(editor, props) { 13557 this.editor = editor; 13558 this.props = props; 13559 } 13560 Shared.prototype.delegateCursor = function (position, scroll, focus) { 13561 var doc = this.editor.getDoc(); 13562 if (focus) { 13563 this.editor.focus(); 13564 } 13565 scroll ? doc.setCursor(position) : doc.setCursor(position, null, { scroll: false }); 13566 }; 13567 Shared.prototype.delegateScroll = function (coordinates) { 13568 this.editor.scrollTo(coordinates.x, coordinates.y); 13569 }; 13570 Shared.prototype.delegateSelection = function (ranges, focus) { 13571 this.editor.setSelections(ranges); 13572 if (focus) { 13573 this.editor.focus(); 13574 } 13575 }; 13576 Shared.prototype.apply = function (props, next, preserved) { 13577 if (next) { 13578 if (next.selection) { 13579 if (next.selection.ranges) { 13580 if (props.selection) { 13581 if (!Helper.equals(props.selection.ranges, next.selection.ranges)) { 13582 this.delegateSelection(next.selection.ranges, next.selection.focus || false); 13583 } 13584 } 13585 else { 13586 this.delegateSelection(next.selection.ranges, next.selection.focus || false); 13587 } 13588 } 13589 } 13590 if (next.cursor) { 13591 if (props.cursor) { 13592 if (!Helper.equals(props.cursor, next.cursor)) { 13593 this.delegateCursor(preserved.cursor || next.cursor, (next.autoScroll || false), (next.autoCursor || false)); 13594 } 13595 } 13596 else { 13597 this.delegateCursor(preserved.cursor || next.cursor, (next.autoScroll || false), (next.autoCursor || false)); 13598 } 13599 } 13600 if (next.scroll) { 13601 this.delegateScroll(next.scroll); 13602 } 13603 } 13604 else { 13605 if (props.selection) { 13606 if (props.selection.ranges) { 13607 this.delegateSelection(props.selection.ranges, props.selection.focus || false); 13608 } 13609 } 13610 if (props.cursor) { 13611 this.delegateCursor(props.cursor, (props.autoScroll || false), (props.autoFocus || false)); 13612 } 13613 if (props.scroll) { 13614 this.delegateScroll(props.scroll); 13615 } 13616 } 13617 }; 13618 Shared.prototype.wire = function (name) { 13619 var _this = this; 13620 switch (name) { 13621 case 'onBlur': 13622 { 13623 this.editor.on('blur', function (cm, event) { 13624 _this.props.onBlur(_this.editor, event); 13625 }); 13626 } 13627 break; 13628 case 'onCursor': 13629 { 13630 this.editor.on('cursorActivity', function (cm) { 13631 _this.props.onCursor(_this.editor, _this.editor.getCursor()); 13632 }); 13633 } 13634 break; 13635 case 'onCursorActivity': 13636 { 13637 this.editor.on('cursorActivity', function (cm) { 13638 _this.props.onCursorActivity(_this.editor); 13639 }); 13640 } 13641 break; 13642 case 'onDragEnter': 13643 { 13644 this.editor.on('dragenter', function (cm, event) { 13645 _this.props.onDragEnter(_this.editor, event); 13646 }); 13647 } 13648 break; 13649 case 'onDragOver': 13650 { 13651 this.editor.on('dragover', function (cm, event) { 13652 _this.props.onDragOver(_this.editor, event); 13653 }); 13654 } 13655 break; 13656 case 'onDrop': 13657 { 13658 this.editor.on('drop', function (cm, event) { 13659 _this.props.onDrop(_this.editor, event); 13660 }); 13661 } 13662 break; 13663 case 'onFocus': 13664 { 13665 this.editor.on('focus', function (cm, event) { 13666 _this.props.onFocus(_this.editor, event); 13667 }); 13668 } 13669 break; 13670 case 'onGutterClick': 13671 { 13672 this.editor.on('gutterClick', function (cm, lineNumber, gutter, event) { 13673 _this.props.onGutterClick(_this.editor, lineNumber, gutter, event); 13674 }); 13675 } 13676 break; 13677 case 'onKeyDown': 13678 { 13679 this.editor.on('keydown', function (cm, event) { 13680 _this.props.onKeyDown(_this.editor, event); 13681 }); 13682 } 13683 break; 13684 case 'onKeyPress': 13685 { 13686 this.editor.on('keypress', function (cm, event) { 13687 _this.props.onKeyPress(_this.editor, event); 13688 }); 13689 } 13690 break; 13691 case 'onKeyUp': 13692 { 13693 this.editor.on('keyup', function (cm, event) { 13694 _this.props.onKeyUp(_this.editor, event); 13695 }); 13696 } 13697 break; 13698 case 'onScroll': 13699 { 13700 this.editor.on('scroll', function (cm) { 13701 _this.props.onScroll(_this.editor, _this.editor.getScrollInfo()); 13702 }); 13703 } 13704 break; 13705 case 'onSelection': 13706 { 13707 this.editor.on('beforeSelectionChange', function (cm, data) { 13708 _this.props.onSelection(_this.editor, data); 13709 }); 13710 } 13711 break; 13712 case 'onUpdate': 13713 { 13714 this.editor.on('update', function (cm) { 13715 _this.props.onUpdate(_this.editor); 13716 }); 13717 } 13718 break; 13719 case 'onViewportChange': 13720 { 13721 this.editor.on('viewportChange', function (cm, from, to) { 13722 _this.props.onViewportChange(_this.editor, from, to); 13723 }); 13724 } 13725 break; 13726 } 13727 }; 13728 return Shared; 13729 }()); 13730 var Controlled = (function (_super) { 13731 __extends(Controlled, _super); 13732 function Controlled(props) { 13733 var _this = _super.call(this, props) || this; 13734 if (SERVER_RENDERED) 13735 return _this; 13736 _this.deferred = null; 13737 _this.emulating = false; 13738 _this.hydrated = false; 13739 _this.initCb = function () { 13740 if (_this.props.editorDidConfigure) { 13741 _this.props.editorDidConfigure(_this.editor); 13742 } 13743 }; 13744 _this.mounted = false; 13745 return _this; 13746 } 13747 Controlled.prototype.hydrate = function (props) { 13748 var _this = this; 13749 var userDefinedOptions = Object.assign({}, cm.defaults, this.editor.options, props.options || {}); 13750 var optionDelta = Object.keys(userDefinedOptions).some(function (key) { return _this.editor.getOption(key) !== userDefinedOptions[key]; }); 13751 if (optionDelta) { 13752 Object.keys(userDefinedOptions).forEach(function (key) { 13753 if (props.options.hasOwnProperty(key)) { 13754 if (_this.editor.getOption(key) !== userDefinedOptions[key]) { 13755 _this.editor.setOption(key, userDefinedOptions[key]); 13756 _this.mirror.setOption(key, userDefinedOptions[key]); 13757 } 13758 } 13759 }); 13760 } 13761 if (!this.hydrated) { 13762 if (!this.mounted) { 13763 this.initChange(props.value || ''); 13764 } 13765 else { 13766 if (this.deferred) { 13767 this.resolveChange(); 13768 } 13769 else { 13770 this.initChange(props.value || ''); 13771 } 13772 } 13773 } 13774 this.hydrated = true; 13775 }; 13776 Controlled.prototype.initChange = function (value) { 13777 this.emulating = true; 13778 var lastLine = this.editor.lastLine(); 13779 var lastChar = this.editor.getLine(this.editor.lastLine()).length; 13780 this.editor.replaceRange(value || '', { line: 0, ch: 0 }, { line: lastLine, ch: lastChar }); 13781 this.mirror.setValue(value); 13782 this.editor.clearHistory(); 13783 this.mirror.clearHistory(); 13784 this.emulating = false; 13785 }; 13786 Controlled.prototype.resolveChange = function () { 13787 this.emulating = true; 13788 if (this.deferred.origin === 'undo') { 13789 this.editor.undo(); 13790 } 13791 else if (this.deferred.origin === 'redo') { 13792 this.editor.redo(); 13793 } 13794 else { 13795 this.editor.replaceRange(this.deferred.text, this.deferred.from, this.deferred.to, this.deferred.origin); 13796 } 13797 this.emulating = false; 13798 this.deferred = null; 13799 }; 13800 Controlled.prototype.mirrorChange = function (deferred) { 13801 if (deferred.origin === 'undo') { 13802 this.editor.setHistory(this.mirror.getHistory()); 13803 this.mirror.undo(); 13804 } 13805 else if (deferred.origin === 'redo') { 13806 this.editor.setHistory(this.mirror.getHistory()); 13807 this.mirror.redo(); 13808 } 13809 else { 13810 this.mirror.replaceRange(deferred.text, deferred.from, deferred.to, deferred.origin); 13811 } 13812 return this.mirror.getValue(); 13813 }; 13814 Controlled.prototype.componentWillMount = function () { 13815 if (SERVER_RENDERED) 13816 return; 13817 if (this.props.editorWillMount) { 13818 this.props.editorWillMount(); 13819 } 13820 }; 13821 Controlled.prototype.componentDidMount = function () { 13822 var _this = this; 13823 if (SERVER_RENDERED) 13824 return; 13825 if (this.props.defineMode) { 13826 if (this.props.defineMode.name && this.props.defineMode.fn) { 13827 cm.defineMode(this.props.defineMode.name, this.props.defineMode.fn); 13828 } 13829 } 13830 this.editor = cm(this.ref); 13831 this.shared = new Shared(this.editor, this.props); 13832 this.mirror = cm(function () { 13833 }); 13834 this.editor.on('electricInput', function () { 13835 _this.mirror.setHistory(_this.editor.getHistory()); 13836 }); 13837 this.editor.on('cursorActivity', function () { 13838 _this.mirror.setCursor(_this.editor.getCursor()); 13839 }); 13840 this.editor.on('beforeChange', function (cm, data) { 13841 if (_this.emulating) { 13842 return; 13843 } 13844 data.cancel(); 13845 _this.deferred = data; 13846 var phantomChange = _this.mirrorChange(_this.deferred); 13847 if (_this.props.onBeforeChange) 13848 _this.props.onBeforeChange(_this.editor, _this.deferred, phantomChange); 13849 }); 13850 this.editor.on('change', function (cm, data) { 13851 if (!_this.mounted) { 13852 return; 13853 } 13854 if (_this.props.onChange) { 13855 _this.props.onChange(_this.editor, data, _this.editor.getValue()); 13856 } 13857 }); 13858 this.hydrate(this.props); 13859 this.shared.apply(this.props); 13860 this.mounted = true; 13861 if (this.props.onBlur) 13862 this.shared.wire('onBlur'); 13863 if (this.props.onCursor) 13864 this.shared.wire('onCursor'); 13865 if (this.props.onCursorActivity) 13866 this.shared.wire('onCursorActivity'); 13867 if (this.props.onDragEnter) 13868 this.shared.wire('onDragEnter'); 13869 if (this.props.onDragOver) 13870 this.shared.wire('onDragOver'); 13871 if (this.props.onDrop) 13872 this.shared.wire('onDrop'); 13873 if (this.props.onFocus) 13874 this.shared.wire('onFocus'); 13875 if (this.props.onGutterClick) 13876 this.shared.wire('onGutterClick'); 13877 if (this.props.onKeyDown) 13878 this.shared.wire('onKeyDown'); 13879 if (this.props.onKeyPress) 13880 this.shared.wire('onKeyPress'); 13881 if (this.props.onKeyUp) 13882 this.shared.wire('onKeyUp'); 13883 if (this.props.onScroll) 13884 this.shared.wire('onScroll'); 13885 if (this.props.onSelection) 13886 this.shared.wire('onSelection'); 13887 if (this.props.onUpdate) 13888 this.shared.wire('onUpdate'); 13889 if (this.props.onViewportChange) 13890 this.shared.wire('onViewportChange'); 13891 if (this.props.editorDidMount) { 13892 this.props.editorDidMount(this.editor, this.editor.getValue(), this.initCb); 13893 } 13894 }; 13895 Controlled.prototype.componentWillReceiveProps = function (nextProps) { 13896 if (SERVER_RENDERED) 13897 return; 13898 var preserved = { cursor: null }; 13899 if (nextProps.value !== this.props.value) { 13900 this.hydrated = false; 13901 } 13902 if (!this.props.autoCursor && this.props.autoCursor !== undefined) { 13903 preserved.cursor = this.editor.getCursor(); 13904 } 13905 this.hydrate(nextProps); 13906 this.shared.apply(this.props, nextProps, preserved); 13907 }; 13908 Controlled.prototype.componentWillUnmount = function () { 13909 if (SERVER_RENDERED) 13910 return; 13911 if (this.props.editorWillUnmount) { 13912 this.props.editorWillUnmount(cm); 13913 } 13914 }; 13915 Controlled.prototype.shouldComponentUpdate = function (nextProps, nextState) { 13916 return !SERVER_RENDERED; 13917 }; 13918 Controlled.prototype.render = function () { 13919 var _this = this; 13920 if (SERVER_RENDERED) 13921 return null; 13922 var className = this.props.className ? 'react-codemirror2 ' + this.props.className : 'react-codemirror2'; 13923 return (React.createElement('div', { className: className, ref: function (self) { return _this.ref = self; } })); 13924 }; 13925 return Controlled; 13926 }(React.Component)); 13927 exports.Controlled = Controlled; 13928 var UnControlled = (function (_super) { 13929 __extends(UnControlled, _super); 13930 function UnControlled(props) { 13931 var _this = _super.call(this, props) || this; 13932 if (SERVER_RENDERED) 13933 return _this; 13934 _this.continueChange = false; 13935 _this.hydrated = false; 13936 _this.initCb = function () { 13937 if (_this.props.editorDidConfigure) { 13938 _this.props.editorDidConfigure(_this.editor); 13939 } 13940 }; 13941 _this.mounted = false; 13942 _this.onBeforeChangeCb = function () { 13943 _this.continueChange = true; 13944 }; 13945 return _this; 13946 } 13947 UnControlled.prototype.hydrate = function (props) { 13948 var _this = this; 13949 var userDefinedOptions = Object.assign({}, cm.defaults, this.editor.options, props.options || {}); 13950 var optionDelta = Object.keys(userDefinedOptions).some(function (key) { return _this.editor.getOption(key) !== userDefinedOptions[key]; }); 13951 if (optionDelta) { 13952 Object.keys(userDefinedOptions).forEach(function (key) { 13953 if (props.options.hasOwnProperty(key)) { 13954 if (_this.editor.getOption(key) !== userDefinedOptions[key]) { 13955 _this.editor.setOption(key, userDefinedOptions[key]); 13956 } 13957 } 13958 }); 13959 } 13960 if (!this.hydrated) { 13961 var lastLine = this.editor.lastLine(); 13962 var lastChar = this.editor.getLine(this.editor.lastLine()).length; 13963 this.editor.replaceRange(props.value || '', { line: 0, ch: 0 }, { line: lastLine, ch: lastChar }); 13964 } 13965 this.hydrated = true; 13966 }; 13967 UnControlled.prototype.componentWillMount = function () { 13968 if (SERVER_RENDERED) 13969 return; 13970 if (this.props.editorWillMount) { 13971 this.props.editorWillMount(); 13972 } 13973 }; 13974 UnControlled.prototype.componentDidMount = function () { 13975 var _this = this; 13976 if (SERVER_RENDERED) 13977 return; 13978 if (this.props.defineMode) { 13979 if (this.props.defineMode.name && this.props.defineMode.fn) { 13980 cm.defineMode(this.props.defineMode.name, this.props.defineMode.fn); 13981 } 13982 } 13983 this.editor = cm(this.ref); 13984 this.shared = new Shared(this.editor, this.props); 13985 this.editor.on('beforeChange', function (cm, data) { 13986 if (_this.props.onBeforeChange) { 13987 _this.props.onBeforeChange(_this.editor, data, null, _this.onBeforeChangeCb); 13988 } 13989 }); 13990 this.editor.on('change', function (cm, data) { 13991 if (!_this.mounted) { 13992 return; 13993 } 13994 if (_this.props.onBeforeChange) { 13995 if (_this.continueChange) { 13996 _this.props.onChange(_this.editor, data, _this.editor.getValue()); 13997 } 13998 } 13999 else { 14000 _this.props.onChange(_this.editor, data, _this.editor.getValue()); 14001 } 14002 }); 14003 this.hydrate(this.props); 14004 this.shared.apply(this.props); 14005 this.mounted = true; 14006 if (this.props.onBlur) 14007 this.shared.wire('onBlur'); 14008 if (this.props.onCursor) 14009 this.shared.wire('onCursor'); 14010 if (this.props.onCursorActivity) 14011 this.shared.wire('onCursorActivity'); 14012 if (this.props.onDragEnter) 14013 this.shared.wire('onDragEnter'); 14014 if (this.props.onDragOver) 14015 this.shared.wire('onDragOver'); 14016 if (this.props.onDrop) 14017 this.shared.wire('onDrop'); 14018 if (this.props.onFocus) 14019 this.shared.wire('onFocus'); 14020 if (this.props.onGutterClick) 14021 this.shared.wire('onGutterClick'); 14022 if (this.props.onKeyDown) 14023 this.shared.wire('onKeyDown'); 14024 if (this.props.onKeyPress) 14025 this.shared.wire('onKeyPress'); 14026 if (this.props.onKeyUp) 14027 this.shared.wire('onKeyUp'); 14028 if (this.props.onScroll) 14029 this.shared.wire('onScroll'); 14030 if (this.props.onSelection) 14031 this.shared.wire('onSelection'); 14032 if (this.props.onUpdate) 14033 this.shared.wire('onUpdate'); 14034 if (this.props.onViewportChange) 14035 this.shared.wire('onViewportChange'); 14036 this.editor.clearHistory(); 14037 if (this.props.editorDidMount) { 14038 this.props.editorDidMount(this.editor, this.editor.getValue(), this.initCb); 14039 } 14040 }; 14041 UnControlled.prototype.componentWillReceiveProps = function (nextProps) { 14042 if (SERVER_RENDERED) 14043 return; 14044 var preserved = { cursor: null }; 14045 if (nextProps.value !== this.props.value) { 14046 this.hydrated = false; 14047 } 14048 if (!this.props.autoCursor && this.props.autoCursor !== undefined) { 14049 preserved.cursor = this.editor.getCursor(); 14050 } 14051 this.hydrate(nextProps); 14052 this.shared.apply(this.props, nextProps, preserved); 14053 }; 14054 UnControlled.prototype.componentWillUnmount = function () { 14055 if (SERVER_RENDERED) 14056 return; 14057 if (this.props.editorWillUnmount) { 14058 this.props.editorWillUnmount(cm); 14059 } 14060 }; 14061 UnControlled.prototype.shouldComponentUpdate = function (nextProps, nextState) { 14062 return !SERVER_RENDERED; 14063 }; 14064 UnControlled.prototype.render = function () { 14065 var _this = this; 14066 if (SERVER_RENDERED) 14067 return null; 14068 var className = this.props.className ? 'react-codemirror2 ' + this.props.className : 'react-codemirror2'; 14069 return (React.createElement('div', { className: className, ref: function (self) { return _this.ref = self; } })); 14070 }; 14071 return UnControlled; 14072 }(React.Component)); 14073 exports.UnControlled = UnControlled; 14074 14075 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 14076 },{"codemirror":2,"react":49}],38:[function(require,module,exports){ 2832 14077 (function (process){ 2833 14078 /** @license React v16.0.0 … … 20054 31299 20055 31300 }).call(this,require('_process')) 20056 },{"_process":2 6,"fbjs/lib/EventListener":7,"fbjs/lib/ExecutionEnvironment":8,"fbjs/lib/camelizeStyleName":10,"fbjs/lib/containsNode":11,"fbjs/lib/emptyFunction":12,"fbjs/lib/emptyObject":13,"fbjs/lib/focusNode":14,"fbjs/lib/getActiveElement":15,"fbjs/lib/hyphenateStyleName":17,"fbjs/lib/invariant":18,"fbjs/lib/performanceNow":22,"fbjs/lib/shallowEqual":23,"fbjs/lib/warning":24,"object-assign":25,"prop-types":30,"prop-types/checkPropTypes":27,"react":44}],34:[function(require,module,exports){31301 },{"_process":29,"fbjs/lib/EventListener":10,"fbjs/lib/ExecutionEnvironment":11,"fbjs/lib/camelizeStyleName":13,"fbjs/lib/containsNode":14,"fbjs/lib/emptyFunction":15,"fbjs/lib/emptyObject":16,"fbjs/lib/focusNode":17,"fbjs/lib/getActiveElement":18,"fbjs/lib/hyphenateStyleName":20,"fbjs/lib/invariant":21,"fbjs/lib/performanceNow":25,"fbjs/lib/shallowEqual":26,"fbjs/lib/warning":27,"object-assign":28,"prop-types":33,"prop-types/checkPropTypes":30,"react":49}],39:[function(require,module,exports){ 20057 31302 /* 20058 31303 React v16.0.0 … … 20312 31557 unstable_deferredUpdates:Xj.deferredUpdates,flushSync:Xj.flushSync,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{EventPluginHub:Jb,EventPluginRegistry:sa,EventPropagators:Th,ReactControlledComponent:nb,ReactDOMComponentTree:G,ReactDOMEventListener:L}};Cj({findFiberByHostInstance:G.getClosestInstanceFromNode,findHostInstanceByFiber:Xj.findHostInstance,bundleType:0,version:"16.0.0",rendererPackageName:"react-dom"});module.exports=ek; 20313 31558 20314 },{"fbjs/lib/EventListener": 7,"fbjs/lib/ExecutionEnvironment":8,"fbjs/lib/containsNode":11,"fbjs/lib/emptyFunction":12,"fbjs/lib/emptyObject":13,"fbjs/lib/focusNode":14,"fbjs/lib/getActiveElement":15,"fbjs/lib/invariant":18,"fbjs/lib/shallowEqual":23,"object-assign":25,"react":44}],35:[function(require,module,exports){31559 },{"fbjs/lib/EventListener":10,"fbjs/lib/ExecutionEnvironment":11,"fbjs/lib/containsNode":14,"fbjs/lib/emptyFunction":15,"fbjs/lib/emptyObject":16,"fbjs/lib/focusNode":17,"fbjs/lib/getActiveElement":18,"fbjs/lib/invariant":21,"fbjs/lib/shallowEqual":26,"object-assign":28,"react":49}],40:[function(require,module,exports){ 20315 31560 (function (process){ 20316 31561 'use strict'; … … 20354 31599 20355 31600 }).call(this,require('_process')) 20356 },{"./cjs/react-dom.development.js":3 3,"./cjs/react-dom.production.min.js":34,"_process":26}],36:[function(require,module,exports){31601 },{"./cjs/react-dom.development.js":38,"./cjs/react-dom.production.min.js":39,"_process":29}],41:[function(require,module,exports){ 20357 31602 (function (process){ 20358 31603 'use strict'; … … 20668 31913 module.exports = exports['default']; 20669 31914 }).call(this,require('_process')) 20670 },{"./Transition": 37,"./utils/PropTypes":41,"_process":26,"dom-helpers/class/addClass":4,"dom-helpers/class/removeClass":6,"prop-types":30,"react":44}],37:[function(require,module,exports){31915 },{"./Transition":42,"./utils/PropTypes":46,"_process":29,"dom-helpers/class/addClass":7,"dom-helpers/class/removeClass":9,"prop-types":33,"react":49}],42:[function(require,module,exports){ 20671 31916 (function (process){ 20672 31917 'use strict'; … … 21228 32473 exports.default = Transition; 21229 32474 }).call(this,require('_process')) 21230 },{"./utils/PropTypes":4 1,"_process":26,"prop-types":30,"react":44,"react-dom":35}],38:[function(require,module,exports){32475 },{"./utils/PropTypes":46,"_process":29,"prop-types":33,"react":49,"react-dom":40}],43:[function(require,module,exports){ 21231 32476 (function (process){ 21232 32477 'use strict'; … … 21521 32766 module.exports = exports['default']; 21522 32767 }).call(this,require('_process')) 21523 },{"./utils/ChildMapping":4 0,"_process":26,"prop-types":30,"react":44}],39:[function(require,module,exports){32768 },{"./utils/ChildMapping":45,"_process":29,"prop-types":33,"react":49}],44:[function(require,module,exports){ 21524 32769 'use strict'; 21525 32770 … … 21543 32788 CSSTransition: _CSSTransition2.default 21544 32789 }; 21545 },{"./CSSTransition": 36,"./Transition":37,"./TransitionGroup":38}],40:[function(require,module,exports){32790 },{"./CSSTransition":41,"./Transition":42,"./TransitionGroup":43}],45:[function(require,module,exports){ 21546 32791 'use strict'; 21547 32792 … … 21633 32878 return childMapping; 21634 32879 } 21635 },{"react":4 4}],41:[function(require,module,exports){32880 },{"react":49}],46:[function(require,module,exports){ 21636 32881 'use strict'; 21637 32882 … … 21682 32927 exitActive: _propTypes2.default.string 21683 32928 })]); 21684 },{"prop-types":3 0}],42:[function(require,module,exports){32929 },{"prop-types":33}],47:[function(require,module,exports){ 21685 32930 (function (process){ 21686 32931 /** @license React v16.0.0 … … 23384 34629 23385 34630 }).call(this,require('_process')) 23386 },{"_process":2 6,"fbjs/lib/emptyFunction":12,"fbjs/lib/emptyObject":13,"fbjs/lib/invariant":18,"fbjs/lib/warning":24,"object-assign":25,"prop-types/checkPropTypes":27}],43:[function(require,module,exports){34631 },{"_process":29,"fbjs/lib/emptyFunction":15,"fbjs/lib/emptyObject":16,"fbjs/lib/invariant":21,"fbjs/lib/warning":27,"object-assign":28,"prop-types/checkPropTypes":30}],48:[function(require,module,exports){ 23387 34632 /* 23388 34633 React v16.0.0 … … 23409 34654 module.exports={Children:{map:S.map,forEach:S.forEach,count:S.count,toArray:S.toArray,only:function(a){G.isValidElement(a)?void 0:t("143");return a}},Component:B.Component,PureComponent:B.PureComponent,unstable_AsyncComponent:B.AsyncComponent,createElement:G.createElement,cloneElement:G.cloneElement,isValidElement:G.isValidElement,createFactory:G.createFactory,version:"16.0.0",__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentOwner:C,assign:f}}; 23410 34655 23411 },{"fbjs/lib/emptyFunction":1 2,"fbjs/lib/emptyObject":13,"fbjs/lib/invariant":18,"object-assign":25}],44:[function(require,module,exports){34656 },{"fbjs/lib/emptyFunction":15,"fbjs/lib/emptyObject":16,"fbjs/lib/invariant":21,"object-assign":28}],49:[function(require,module,exports){ 23412 34657 (function (process){ 23413 34658 'use strict'; … … 23420 34665 23421 34666 }).call(this,require('_process')) 23422 },{"./cjs/react.development.js":4 2,"./cjs/react.production.min.js":43,"_process":26}],45:[function(require,module,exports){34667 },{"./cjs/react.development.js":47,"./cjs/react.production.min.js":48,"_process":29}],50:[function(require,module,exports){ 23423 34668 "use strict"; 23424 34669 … … 23451 34696 languageMap: PT.object.isRequired 23452 34697 }, 34698 34699 getInitialState: function getInitialState() { 34700 return { 34701 viewSelected: false }; 34702 }, 34703 23453 34704 23454 34705 toggleSelection: function toggleSelection(corpus, e) { … … 23461 34712 }, 23462 34713 34714 toggleViewSelected: function toggleViewSelected(evt) { 34715 this.setState(function (st) { 34716 return { viewSelected: !st.viewSelected }; 34717 }); 34718 }, 34719 toggleShowDisabled: function toggleShowDisabled(evt) { 34720 this.setState(function (st) { 34721 return { showDisabled: !st.showDisabled }; 34722 }); 34723 }, 34724 34725 34726 toggleDescExpansion: function toggleDescExpansion(corpus) { 34727 corpus.descExpanded = !corpus.descExpanded; 34728 this.props.corpora.update(); 34729 }, 34730 23463 34731 toggleExpansion: function toggleExpansion(corpus) { 23464 34732 corpus.expanded = !corpus.expanded; … … 23467 34735 23468 34736 selectAll: function selectAll(value) { 34737 // select all _visible_ 23469 34738 this.props.corpora.recurse(function (c) { 23470 c. selected = value;34739 c.visible ? c.selected = value : false; 23471 34740 }); 23472 34741 this.props.corpora.update(); … … 23579 34848 return React.createElement( 23580 34849 "div", 23581 { className: "expansion-handle", style: {}},34850 { className: "expansion-handle", onClick: this.toggleExpansion.bind(this, corpus) }, 23582 34851 React.createElement( 23583 34852 "a", … … 23598 34867 }, 23599 34868 34869 shouldShowItem: function shouldShowItem(level, corpus) { 34870 if (this.state.viewSelected && !corpus.selected) { 34871 return false; 34872 } 34873 if (!this.state.showDisabled && !corpus.visible) { 34874 return false; 34875 } 34876 // normal search filter. 34877 if (level === 0 && corpus.priority <= 0) { 34878 return false; 34879 } 34880 34881 return true; 34882 }, 23600 34883 renderFilteredMessage: function renderFilteredMessage() { 34884 var _this = this; 34885 23601 34886 var total = 0; 23602 34887 var visible = 0; 23603 34888 this.props.corpora.recurse(function (corpus) { 23604 if (corpus.visible ) {34889 if (corpus.visible || _this.state.showDisabled) { 23605 34890 total++; 23606 if ( corpus.priority > 0) {34891 if (_this.shouldShowItem(0, corpus)) { 23607 34892 visible++; 23608 34893 } … … 23611 34896 if (visible === total) { 23612 34897 return false; 34898 } 34899 if (visible === 0) { 34900 return false; // we do have an "empty" message anyway 23613 34901 } 23614 34902 return React.createElement( … … 23623 34911 }, 23624 34912 34913 23625 34914 renderCorpus: function renderCorpus(level, minmaxp, corpus) { 23626 if (! corpus.visible || corpus.priority <= 0) {23627 return false;34915 if (!this.shouldShowItem(level, corpus)) { 34916 return; 23628 34917 } 23629 34918 … … 23634 34923 var color = minmaxp[0] === minmaxp[1] ? 'transparent' : 'hsl(' + hue + ', 50%, 50%)'; 23635 34924 var priorityStyle = { paddingBottom: 4, paddingLeft: 2, borderBottom: '3px solid ' + color }; 23636 var expansive = corpus. expanded ? { overflow: 'hidden' } : { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };34925 var expansive = corpus.descExpanded ? { overflow: 'hidden' } : { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }; 23637 34926 return React.createElement( 23638 34927 "div", … … 23640 34929 React.createElement( 23641 34930 "div", 23642 { className: "row corpus", onClick: this.toggle Expansion.bind(this, corpus) },34931 { className: "row corpus", onClick: this.toggleDescExpansion.bind(this, corpus) }, 23643 34932 React.createElement( 23644 34933 "div", … … 23702 34991 }, 23703 34992 34993 renderCorpList: function renderCorpList() { 34994 var _this2 = this; 34995 34996 var minmaxp = this.getMinMaxPriority(); 34997 34998 var corpListRender = []; 34999 35000 // this is so we get a non-undefined items .length in corpListRender. 35001 this.props.corpora.corpora.forEach(function (c) { 35002 var rend = _this2.renderCorpus(0, minmaxp, c); 35003 if (rend) corpListRender.push(rend); 35004 }); 35005 35006 return React.createElement( 35007 "div", 35008 { className: "corpusview-corpora" }, 35009 corpListRender.length > 0 ? corpListRender : React.createElement( 35010 "h3", 35011 { className: "aligncenter" }, 35012 this.state.viewSelected ? "No collections selected yet!" : "No collections found." 35013 ) 35014 ); 35015 }, 23704 35016 render: function render() { 23705 var minmaxp = this.getMinMaxPriority(); 35017 var selectedCount = 0; 35018 //var disabledCount = 0; 35019 this.props.corpora.recurse(function (c) { 35020 if (c.selected && c.visible) selectedCount++; 35021 //if (c.selected) selectedCount++; 35022 //if (!c.visible) disabledCount++; 35023 }); 35024 23706 35025 return React.createElement( 23707 35026 "div", … … 23712 35031 React.createElement( 23713 35032 "div", 23714 { className: "float-left inline " },35033 { className: "float-left inline corpusview-filter-buttons" }, 23715 35034 React.createElement( 23716 "h3", 23717 { style: { marginTop: 10 } }, 23718 this.props.corpora.getSelectedMessage() 35035 "div", 35036 { className: "btn-group btn-group-toggle" }, 35037 React.createElement( 35038 "label", 35039 { className: "btn btn-light btn " + (this.state.viewSelected ? 'active' : 'inactive'), onClick: this.toggleViewSelected, title: "View selected collections" }, 35040 React.createElement("span", { className: this.state.viewSelected ? "glyphicon glyphicon-check" : "glyphicon glyphicon-unchecked" }), 35041 " View selected (", 35042 selectedCount, 35043 ")" 35044 ) 23719 35045 ) 23720 35046 ), … … 23744 35070 ) 23745 35071 ), 23746 this. props.corpora.corpora.map(this.renderCorpus.bind(this, 0, minmaxp))35072 this.renderCorpList() 23747 35073 ); 23748 35074 } … … 23751 35077 module.exports = CorpusView; 23752 35078 23753 },{"./searchcorpusbox.jsx": 56,"classnames":1,"create-react-class":3,"prop-types":30}],46:[function(require,module,exports){35079 },{"./searchcorpusbox.jsx":61,"classnames":1,"create-react-class":6,"prop-types":33}],51:[function(require,module,exports){ 23754 35080 "use strict"; 23755 35081 … … 23810 35136 module.exports = EmbeddedFooter; 23811 35137 23812 },{"classnames":1,"create-react-class": 3,"prop-types":30}],47:[function(require,module,exports){35138 },{"classnames":1,"create-react-class":6,"prop-types":33}],52:[function(require,module,exports){ 23813 35139 "use strict"; 23814 35140 … … 23874 35200 module.exports = ErrorPane; 23875 35201 23876 },{"./jqueryfade.jsx": 49,"classnames":1,"create-react-class":3,"prop-types":30,"react-transition-group":39}],48:[function(require,module,exports){35202 },{"./jqueryfade.jsx":54,"classnames":1,"create-react-class":6,"prop-types":33,"react-transition-group":44}],53:[function(require,module,exports){ 23877 35203 "use strict"; 23878 35204 … … 23962 35288 module.exports = Footer; 23963 35289 23964 },{"classnames":1,"create-react-class": 3,"prop-types":30}],49:[function(require,module,exports){35290 },{"classnames":1,"create-react-class":6,"prop-types":33}],54:[function(require,module,exports){ 23965 35291 "use strict"; 23966 35292 … … 24000 35326 module.exports = JQueryFade; 24001 35327 24002 },{"classnames":1,"create-react-class": 3,"prop-types":30}],50:[function(require,module,exports){35328 },{"classnames":1,"create-react-class":6,"prop-types":33}],55:[function(require,module,exports){ 24003 35329 "use strict"; 24004 35330 … … 24149 35475 module.exports = LanguageSelector; 24150 35476 24151 },{"classnames":1,"create-react-class": 3,"prop-types":30,"react-addons-linked-state-mixin":32}],51:[function(require,module,exports){35477 },{"classnames":1,"create-react-class":6,"prop-types":33,"react-addons-linked-state-mixin":35}],56:[function(require,module,exports){ 24152 35478 "use strict"; 24153 35479 … … 24239 35565 module.exports = Modal; 24240 35566 24241 },{"classnames":1,"create-react-class": 3,"prop-types":30}],52:[function(require,module,exports){35567 },{"classnames":1,"create-react-class":6,"prop-types":33}],57:[function(require,module,exports){ 24242 35568 "use strict"; 24243 35569 … … 24313 35639 module.exports = Panel; 24314 35640 24315 },{"classnames":1,"create-react-class": 3,"prop-types":30}],53:[function(require,module,exports){35641 },{"classnames":1,"create-react-class":6,"prop-types":33}],58:[function(require,module,exports){ 24316 35642 "use strict"; 24317 35643 … … 24328 35654 var _createReactClass2 = _interopRequireDefault(_createReactClass); 24329 35655 35656 var _reactAddonsPureRenderMixin = require("react-addons-pure-render-mixin"); 35657 35658 var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); 35659 24330 35660 var _reactTransitionGroup = require("react-transition-group"); 24331 35661 35662 var _reactCodemirror = require("react-codemirror2"); 35663 24332 35664 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 24333 35665 35666 require('codemirror/mode/fcs-ql/fcs-ql'); 35667 require('codemirror/mode/javascript/javascript'); 35668 24334 35669 var PT = _propTypes2.default; 24335 35670 35671 function nextId() { 35672 return nextId.id++; 35673 } 35674 nextId.id = 0; 35675 24336 35676 var QueryInput = (0, _createReactClass2.default)({ 24337 displayName: "QueryInput", 24338 24339 //fixme! - class QueryInput extends React.Component { 24340 propTypes: { 24341 searchedLanguage: PT.array, 24342 queryTypeId: PT.string.isRequired, 24343 query: PT.string, 24344 embedded: PT.bool.isRequired, 24345 placeholder: PT.string, 24346 onChange: PT.func.isRequired, 24347 onQuery: PT.func.isRequired, 24348 onKeyDown: PT.func.isRequired 24349 }, 24350 24351 render: function render() { 24352 //if (this.props.queryTypeId == "cql") { 24353 return React.createElement("input", { className: "form-control input-lg search", 24354 id: "query-cql", name: "query-cql", type: "text", 24355 value: this.props.query, placeholder: this.props.placeholder, 24356 tabIndex: "1", onChange: this.props.onChange 24357 //onQuery={this.props.onQuery} 24358 , onKeyDown: this.props.onKeyDown, 24359 ref: "cqlOrEmbeddedQuery" }); 24360 // } else if (this.props.embedded && this.props.queryTypeId == "fcs") { 24361 // return ( 24362 // <textarea className="form-control input-lg search" 24363 // id="query-fcs" name="query-fcs" 24364 // type="text" rows="1" 24365 // value={this.props.query} placeholder={this.props.placeholder} 24366 // tabIndex="1" onChange={this.props.onChange} 24367 // //onQuery={this.props.onQuery} 24368 // onKeyDown={this.props.onKeyDown} 24369 // ref="fcsOrEmbeddedQuery" /> 24370 // ); 24371 // } 24372 // return (<div id="adv_query_input_group" className="input-group-addon"> 24373 // <ADVTokens 24374 // query={this.props.query} 24375 // ref="fcsGQB" 24376 // /> 24377 // </div>); 24378 } 35677 displayName: "QueryInput", 35678 35679 //fixme! - class QueryInput extends React.Component { 35680 propTypes: { 35681 searchedLanguage: PT.array, 35682 queryTypeId: PT.string.isRequired, 35683 query: PT.string, 35684 embedded: PT.bool.isRequired, 35685 placeholder: PT.string, 35686 onQueryChange: PT.func.isRequired, 35687 onKeyDown: PT.func.isRequired 35688 }, 35689 35690 render: function render() { 35691 var _this = this; 35692 35693 if (this.props.queryTypeId == "cql") { 35694 return React.createElement("input", { className: "form-control input-lg search", 35695 id: "query-cql", name: "query-cql", type: "text", 35696 value: this.props.query, placeholder: this.props.placeholder, 35697 tabIndex: "1", onChange: function onChange(evt) { 35698 return _this.props.onQueryChange(evt.target.value); 35699 } 35700 //onQuery={this.props.onQuery} 35701 , onKeyDown: this.props.onKeyDown, 35702 ref: "cqlOrEmbeddedQuery" }) 35703 /* 35704 // <CodeMirror 35705 // value={this.props.placeholder || this.props.query} 35706 // options={{ 35707 // mode: 'fcs-ql', 35708 // theme: 'default', 35709 // lineNumbers: false, 35710 // matchBrackets: true, 35711 // viewportMargin: 1 35712 // }} 35713 // className="form-control input-lg search" 35714 // onBeforeChange={(editor, data, value) => { 35715 // this.setState({value}); 35716 // }} 35717 // onChange={(editor, data, value) => { 35718 // this.props.onChange(value); 35719 // }} 35720 // onQuery={this.props.onQuery} 35721 // onKeyDown={(editor, event) => { 35722 // this.props.onKeyDown(editor, event) 35723 // }} 35724 // ref="cqlOrEmbeddedQuery" 35725 // > 35726 // </CodeMirror> 35727 */ 35728 ; 35729 } else if (this.props.embedded && this.props.queryTypeId == "fcs") { 35730 return React.createElement("textarea", { className: "form-control input-lg search", 35731 id: "query-fcs", name: "query-fcs", 35732 type: "text", rows: "1", 35733 value: this.props.query, placeholder: this.props.placeholder, 35734 tabIndex: "1", onChange: function onChange(evt) { 35735 return _this.props.onQueryChange(evt.target.value); 35736 } 35737 //onQuery={this.props.onQuery} 35738 , onKeyDown: this.props.onKeyDown, 35739 ref: "fcsOrEmbeddedQuery" }); 35740 } 35741 return React.createElement( 35742 "div", 35743 { id: "adv_query_input_group" }, 35744 React.createElement(ADVTokens, { 35745 query: this.props.query, 35746 ref: "fcsGQB", 35747 onQueryChange: this.props.onQueryChange 35748 }) 35749 ); 35750 } 24379 35751 }); 24380 35752 24381 35753 var ADVTokens = (0, _createReactClass2.default)({ 24382 displayName: "ADVTokens", 24383 24384 24385 propTypes: { 24386 query: PT.string 24387 }, 24388 24389 getInitialState: function getInitialState() { 24390 return { 24391 tokenCounter: 1, 24392 tokens: ["token1"] 24393 }; 24394 }, 24395 24396 addADVToken: function addADVToken() { 24397 var i = this.state.tokenCounter + 1; 24398 this.state.tokens.push('token' + i); 24399 this.setState({ tokenCounter: i, tokens: this.state.tokens }); 24400 }, 24401 24402 removeADVToken: function removeADVToken(id) { 24403 var tokens = this.state.tokens; 24404 var i = tokens.indexOf(id); 24405 if (tokens.length > 1) { 24406 var one = tokens; 24407 var two = one.slice(0, i - 1).concat(one.slice(i));; 24408 this.setState({ tokens: two }); 24409 } 24410 }, 24411 24412 render: function render() { 24413 var i = 0; 24414 var tokens = this.state.tokens.map(function (token, i) { 24415 return React.createElement( 24416 _reactTransitionGroup.CSSTransition, 24417 { key: i, classNames: "token", timeout: { enter: 250, exit: 250 } }, 24418 React.createElement(ADVToken, { 24419 key: token, 24420 parentToken: token, 24421 handleRemoveADVToken: this.removeADVToken }) 24422 ); 24423 }.bind(this)); 24424 24425 return React.createElement( 24426 "div", 24427 null, 24428 React.createElement( 24429 _reactTransitionGroup.TransitionGroup, 24430 null, 24431 tokens 24432 ), 24433 React.createElement( 24434 "button", 24435 { className: "btn btn-xs btn-default image_button insert_token", type: "button", onClick: this.addADVToken, ref: "addToken" }, 24436 React.createElement("i", { className: "glyphicon glyphicon-plus" }) 24437 ) 24438 ); 24439 } 35754 displayName: "ADVTokens", 35755 35756 35757 propTypes: { 35758 query: PT.string, // initial state query. If you want to set a new one, change the 'key' prop on ADVTokens. 35759 onQueryChange: PT.func.isRequired 35760 }, 35761 35762 getDefaultProps: function getDefaultProps() { 35763 return { 35764 query: '[ word = "Elefant" ]' 35765 }; 35766 }, 35767 35768 35769 getInitialState: function getInitialState() { 35770 var _this2 = this; 35771 35772 this.queryStrCache = {}; 35773 35774 console.log('ADVTokens:', this.props.query); 35775 35776 var match = queryToTokens(this.props.query); 35777 console.log('ADVTokens 2:', match); 35778 if (match === null) { 35779 return { tokens: ['token-' + nextId()] }; 35780 } 35781 35782 var tokens = []; 35783 match.forEach(function (m) { 35784 var id = 'token-' + nextId(); 35785 tokens.push(id); 35786 _this2.queryStrCache[id] = m; 35787 }); 35788 35789 return { tokens: tokens }; 35790 }, 35791 35792 addADVToken: function addADVToken() { 35793 this.setState(function (oldSt) { 35794 oldSt.tokens.push('token-' + nextId()); 35795 return { tokens: oldSt.tokens }; 35796 }); 35797 }, 35798 35799 removeADVToken: function removeADVToken(id) { 35800 var _this3 = this; 35801 35802 this.setState(function (oldSt) { 35803 delete _this3.queryStrCache[id]; 35804 oldSt.tokens.splice(oldSt.tokens.indexOf(id), 1); 35805 return { tokens: oldSt.tokens }; 35806 }, this.fireQueryChange); 35807 }, 35808 35809 fireQueryChange: function fireQueryChange() { 35810 var _this4 = this; 35811 35812 var tokenParts = this.state.tokens.map(function (id) { 35813 return _this4.queryStrCache[id]; 35814 }); 35815 var queryString = tokenParts.join(' '); 35816 this.props.onQueryChange(queryString); 35817 }, 35818 onQueryChange: function onQueryChange(tokenId, queryStr) { 35819 this.queryStrCache[tokenId] = queryStr; 35820 this.fireQueryChange(); 35821 }, 35822 35823 35824 render: function render() { 35825 var _this5 = this; 35826 35827 var i = 0; 35828 var tokens = this.state.tokens.map(function (tokenId, i) { 35829 return React.createElement( 35830 _reactTransitionGroup.CSSTransition, 35831 { key: tokenId, classNames: "token", timeout: { enter: 250, exit: 250 } }, 35832 React.createElement(ADVToken, { 35833 query: _this5.queryStrCache[tokenId], 35834 onQueryChange: function onQueryChange(qs) { 35835 return _this5.onQueryChange(tokenId, qs); 35836 }, 35837 handleRemoveADVToken: function handleRemoveADVToken() { 35838 return _this5.removeADVToken(tokenId); 35839 } }) 35840 ); 35841 }); 35842 35843 return React.createElement( 35844 "div", 35845 { id: "adv-tokens" }, 35846 React.createElement( 35847 _reactTransitionGroup.TransitionGroup, 35848 null, 35849 tokens 35850 ), 35851 React.createElement( 35852 "button", 35853 { className: "btn btn-xs btn-default image_button insert_token", type: "button", onClick: this.addADVToken }, 35854 React.createElement("i", { className: "glyphicon glyphicon-plus" }) 35855 ) 35856 ); 35857 } 24440 35858 }); 24441 35859 24442 35860 var ADVToken = (0, _createReactClass2.default)({ 24443 displayName: "ADVToken", 24444 24445 propTypes: { 24446 parentToken: PT.string.isRequired, 24447 handleRemoveADVToken: PT.func.isRequired 24448 }, 24449 render: function render() { 24450 return React.createElement( 24451 "div", 24452 { className: "token query_token inline btn-group", style: { display: "inline-block" } }, 24453 React.createElement( 24454 "div", 24455 { className: "token_header" }, 24456 React.createElement( 24457 "button", 24458 { className: "btn btn-xs btn-default image_button close_btn", type: "button", onClick: this.props.handleRemoveADVToken(this.props.parentToken), ref: "removeToken" }, 24459 React.createElement("i", { className: "glyphicon glyphicon-remove-circle" }) 24460 ), 24461 React.createElement("div", { style: { clear: "both" } }) 24462 ), 24463 React.createElement( 24464 "div", 24465 { className: "args" }, 24466 React.createElement(ANDQueryArgs, null), 24467 React.createElement("div", { className: "lower_footer" }) 24468 ) 24469 ); 24470 } 35861 displayName: "ADVToken", 35862 35863 propTypes: { 35864 query: PT.string, 35865 onQueryChange: PT.func.isRequired, 35866 handleRemoveADVToken: PT.func.isRequired 35867 }, 35868 35869 render: function render() { 35870 return React.createElement( 35871 "div", 35872 { className: "token query_token inline btn-group", style: { display: "inline-block" } }, 35873 React.createElement( 35874 "div", 35875 { className: "token_header" }, 35876 React.createElement( 35877 "span", 35878 { className: "image_button close_btn", type: "button", onClick: this.props.handleRemoveADVToken, ref: "removeToken" }, 35879 React.createElement("i", { className: "glyphicon glyphicon-remove-circle" }) 35880 ), 35881 React.createElement("div", { style: { clear: "both" } }) 35882 ), 35883 React.createElement( 35884 "div", 35885 { className: "args" }, 35886 React.createElement(ANDQueryArgs, { onQueryChange: this.props.onQueryChange, query: this.props.query }), 35887 React.createElement("div", { className: "lower_footer" }) 35888 ) 35889 ); 35890 } 24471 35891 }); 24472 35892 24473 35893 var ADVTokenMenu = (0, _createReactClass2.default)({ 24474 displayName: "ADVTokenMenu", 24475 24476 getInitialState: function getInitialState() { 24477 return { "hideRepeatMenu": true }; 24478 }, 24479 24480 toggleRepeatMenu: function toggleRepeatMenu(e) { 24481 this.setState({ "hideRepeatMenu": !this.state.hideRepeatMenu }); 24482 e.preventDefault(); 24483 }, 24484 24485 render: function render() { 24486 return React.createElement( 24487 "div", 24488 null, 24489 React.createElement( 24490 "button", 24491 { className: "btn btn-xs btn-default image_button repeat_menu", onClick: this.toggleRepeatMenu, ref: "repeatMenu" }, 24492 React.createElement("i", { className: "fa fa-cog" }) 24493 ), 24494 React.createElement( 24495 "div", 24496 { id: "repeatMenu", className: "repeat hide-" + this.state.hideRepeatMenu }, 24497 React.createElement( 24498 "span", 24499 null, 24500 "repeat" 24501 ), 24502 React.createElement("input", { type: "number", id: "repeat1", value: this.state.repeat1, ref: "repeat1" }), 24503 React.createElement( 24504 "span", 24505 null, 24506 "to" 24507 ), 24508 React.createElement("input", { type: "number", id: "repeat2", value: this.state.repeat2, ref: "repeat2" }), 24509 React.createElement( 24510 "span", 24511 null, 24512 "times" 24513 ) 24514 ) 24515 ); 24516 } 35894 displayName: "ADVTokenMenu", 35895 35896 mixins: [_reactAddonsPureRenderMixin2.default], 35897 35898 propTypes: { 35899 onChange: PT.func.isRequired, 35900 repeat1: PT.string, 35901 repeat2: PT.string 35902 }, 35903 35904 getInitialState: function getInitialState() { 35905 var repeat1 = this.props.repeat1 || ''; 35906 var repeat2 = this.props.repeat2 || ''; 35907 return { 35908 repeat1: repeat1, 35909 repeat2: repeat2, 35910 hideMenu: repeat1 || repeat2 ? false : true, 35911 isStart: false, 35912 isEnd: false 35913 }; 35914 }, 35915 35916 getMenuState: function getMenuState() { 35917 if (this.state.hideMenu) { 35918 return {}; 35919 } else { 35920 return $.extend({}, this.state); // copy of state 35921 } 35922 }, 35923 35924 35925 toggleRepeatMenu: function toggleRepeatMenu(e) { 35926 this.setState(function (st) { 35927 return { hideMenu: !st.hideMenu }; 35928 }); 35929 }, 35930 toggleStart: function toggleStart(e) { 35931 this.setState(function (st) { 35932 return { isStart: !st.isStart }; 35933 }); 35934 }, 35935 toggleEnd: function toggleEnd(e) { 35936 this.setState(function (st) { 35937 return { isEnd: !st.isEnd }; 35938 }); 35939 }, 35940 componentDidMount: function componentDidMount() { 35941 // make this compoent controlled to so that this awkward ref.getMenuState() stuff can be removed 35942 this.props.onChange(this.getMenuState()); 35943 }, 35944 componentDidUpdate: function componentDidUpdate() { 35945 // safe because of pure render mixin: will only update on state change. 35946 this.props.onChange(this.getMenuState()); 35947 }, 35948 35949 35950 render: function render() { 35951 var _this6 = this; 35952 35953 return React.createElement( 35954 "div", 35955 { id: "ADVtokenMenu" }, 35956 React.createElement( 35957 "button", 35958 { className: "btn btn-xs btn-default image_button repeat_menu", onClick: this.toggleRepeatMenu, ref: "repeatMenu" }, 35959 React.createElement("i", { className: "fa fa-cog" }) 35960 ), 35961 React.createElement( 35962 "div", 35963 { id: "ADVtokenMenu-items", className: "hide-" + this.state.hideMenu }, 35964 React.createElement( 35965 "div", 35966 { id: "repeatMenu", className: "repeat" }, 35967 React.createElement( 35968 "span", 35969 null, 35970 "Repeat" 35971 ), 35972 React.createElement("input", { type: "text", id: "repeat1", value: this.state.repeat1, onChange: function onChange(evt) { 35973 return _this6.setState({ repeat1: evt.target.value }); 35974 }, ref: "repeat1" }), 35975 React.createElement( 35976 "span", 35977 null, 35978 "to" 35979 ), 35980 React.createElement("input", { type: "text", id: "repeat2", value: this.state.repeat2, onChange: function onChange(evt) { 35981 return _this6.setState({ repeat2: evt.target.value }); 35982 }, ref: "repeat2" }), 35983 React.createElement( 35984 "span", 35985 null, 35986 "times" 35987 ) 35988 ), 35989 React.createElement( 35990 "div", 35991 { id: "start-end-menu" }, 35992 React.createElement( 35993 "div", 35994 null, 35995 React.createElement( 35996 "label", 35997 null, 35998 React.createElement("input", { type: "checkbox", checked: this.state.isStart, onChange: this.toggleStart }), 35999 " Sentence start" 36000 ) 36001 ), 36002 React.createElement( 36003 "div", 36004 null, 36005 React.createElement( 36006 "label", 36007 null, 36008 React.createElement("input", { type: "checkbox", checked: this.state.isEnd, onChange: this.toggleEnd }), 36009 " Sentence end" 36010 ) 36011 ) 36012 ) 36013 ) 36014 ); 36015 } 24517 36016 }); 24518 36017 24519 36018 var ANDQueryArgs = (0, _createReactClass2.default)({ 24520 displayName: "ANDQueryArgs", 24521 24522 24523 getInitialState: function getInitialState() { 24524 return { 24525 andCounter: 1, 24526 ands: ["and1"] 24527 }; 24528 }, 24529 24530 setADVTokenLayer: function setADVTokenLayer(layer) { 24531 //fixme! - check agains valid layers 24532 return; 24533 }, 24534 24535 addADVAnd: function addADVAnd() { 24536 var i = this.state.andCounter + 1; 24537 this.state.ands.push('and' + i); 24538 this.setState({ andCounter: i, ands: this.state.ands }); 24539 }, 24540 24541 removeADVAnd: function removeADVAnd(id) { 24542 var ands = this.state.ands; 24543 var i = ands.indexOf(id); 24544 if (ands.length > 1) { 24545 var one = ands; 24546 var two = one.slice(0, i - 1).concat(one.slice(i));; 24547 this.setState({ ands: two }); 24548 } 24549 }, 24550 24551 renderANDTokenFooter: function renderANDTokenFooter() { 24552 return React.createElement( 24553 "div", 24554 { className: "token_footer" }, 24555 React.createElement( 24556 "button", 24557 { className: "btn btn-xs btn-default image_button insert_arg", onClick: this.addADVAnd, ref: "addAndButton" }, 24558 React.createElement("i", { className: "glyphicon glyphicon-plus" }) 24559 ), 24560 React.createElement(ADVTokenMenu, null), 24561 React.createElement("div", { style: { clear: "both" } }) 24562 ); 24563 }, 24564 24565 renderANDQueryArg: function renderANDQueryArg(and) { 24566 return React.createElement( 24567 "div", 24568 { className: "and query_arg" }, 24569 React.createElement( 24570 "span", 24571 { className: "hidden" }, 24572 "and" 24573 ), 24574 React.createElement(ANDQueryORArgs, { 24575 numAnds: this.state.ands.length, 24576 parentAnd: and, 24577 handleRemoveADVAnd: this.removeADVAnd }) 24578 ); 24579 }, 24580 24581 render: function render() { 24582 var andQueryArgs = this.state.ands.map(function (and, i) { 24583 return React.createElement( 24584 _reactTransitionGroup.CSSTransition, 24585 { key: i, classNames: "fade", timeout: { enter: 200, exit: 200 } }, 24586 React.createElement( 24587 "div", 24588 { key: and }, 24589 this.renderANDQueryArg(and) 24590 ) 24591 ); 24592 }.bind(this)); 24593 return React.createElement( 24594 "div", 24595 null, 24596 React.createElement( 24597 _reactTransitionGroup.TransitionGroup, 24598 null, 24599 andQueryArgs 24600 ), 24601 this.renderANDTokenFooter() 24602 ); 24603 } 36019 displayName: "ANDQueryArgs", 36020 36021 propTypes: { 36022 query: PT.string, 36023 onQueryChange: PT.func.isRequired 36024 }, 36025 36026 getInitialState: function getInitialState() { 36027 var _this7 = this; 36028 36029 this.queryStrCache = {}; 36030 36031 console.log('ANDQueryArgs:', this.props.query); 36032 36033 var repeat1, repeat2; 36034 var qlean = this.props.query; 36035 if (qlean) { 36036 var repeatMatch = qlean.match(/{ *(\d)* *(?:, *(\d)*)? *} *$/); 36037 36038 if (repeatMatch !== null) { 36039 repeat1 = repeatMatch[1]; 36040 repeat2 = repeatMatch[2] || repeat1; 36041 qlean = qlean.substring(0, qlean.length - repeatMatch[0].length); 36042 } 36043 36044 // replace token's [ and ] 36045 qlean = qlean.replace(/^\s*\[\s*/, '').replace(/\s*\]\s*$/, ''); 36046 } 36047 36048 var match = queryToANDArgs(qlean); 36049 console.log('ANDQueryArgs 2:', match); 36050 if (match === null) { 36051 return { 36052 ands: ["and-" + nextId()] 36053 }; 36054 } 36055 36056 var ands = []; 36057 match.forEach(function (m) { 36058 var id = 'and-' + nextId(); 36059 ands.push(id); 36060 _this7.queryStrCache[id] = m; 36061 }); 36062 36063 return { 36064 ands: ands, 36065 repeat1: repeat1, 36066 repeat2: repeat2 36067 }; 36068 }, 36069 36070 addADVAnd: function addADVAnd() { 36071 var _this8 = this; 36072 36073 this.setState(function (oldSt) { 36074 oldSt.ands.push('and-' + nextId()); 36075 return { ands: _this8.state.ands }; 36076 }); 36077 }, 36078 36079 removeADVAnd: function removeADVAnd(id) { 36080 var _this9 = this; 36081 36082 this.setState(function (oldSt) { 36083 delete _this9.queryStrCache[id]; 36084 oldSt.ands.splice(oldSt.ands.indexOf(id), 1); 36085 return { ands: oldSt.ands }; 36086 }, this.fireQueryChange); 36087 }, 36088 36089 onMenuChange: function onMenuChange(menust) { 36090 var _this10 = this; 36091 36092 this.setState({ 36093 menuState_isStart: menust.isStart, 36094 menuState_isEnd: menust.isEnd, 36095 menuState_repeat1: menust.repeat1, 36096 menuState_repeat2: menust.repeat2 36097 }, function () { 36098 return _this10.fireQueryChange(); 36099 }); 36100 }, 36101 fireQueryChange: function fireQueryChange() { 36102 var _this11 = this; 36103 36104 var andParts = this.state.ands.map(function (id) { 36105 return _this11.queryStrCache[id]; 36106 }); 36107 36108 if (this.state.menuState_isStart) { 36109 andParts.push('lbound(sentence)'); 36110 } 36111 if (this.state.menuState_isEnd) { 36112 andParts.push('rbound(sentence)'); 36113 } 36114 36115 var queryString = andParts.length >= 2 ? andParts.join(' & ') : andParts[0]; 36116 queryString = "[ " + queryString + " ]"; 36117 36118 if (this.state.menuState_repeat1 || this.state.menuState_repeat2) { 36119 queryString = queryString + '{' + (this.state.menuState_repeat1 || this.state.menuState_repeat2) + ',' + (this.state.menuState_repeat2 || this.state.menuState_repeat1) + '}'; 36120 } 36121 36122 this.props.onQueryChange(queryString); 36123 }, 36124 onQueryChange: function onQueryChange(andId, queryStr) { 36125 this.queryStrCache[andId] = queryStr; 36126 this.fireQueryChange(); 36127 }, 36128 36129 36130 renderANDTokenFooter: function renderANDTokenFooter() { 36131 var _this12 = this; 36132 36133 return React.createElement( 36134 "div", 36135 { className: "token_footer" }, 36136 React.createElement( 36137 "button", 36138 { className: "btn btn-xs btn-default image_button insert_arg", onClick: this.addADVAnd, ref: "addAndButton" }, 36139 React.createElement("i", { className: "glyphicon glyphicon-plus" }) 36140 ), 36141 React.createElement(ADVTokenMenu, { ref: function ref(_ref) { 36142 return _this12.menuRef = _ref; 36143 }, onChange: this.onMenuChange, repeat1: this.state.repeat1, repeat2: this.state.repeat2 }), 36144 React.createElement("div", { style: { clear: "both" } }) 36145 ); 36146 }, 36147 36148 render: function render() { 36149 var _this13 = this; 36150 36151 var andQueryArgs = this.state.ands.map(function (andId) { 36152 return React.createElement( 36153 _reactTransitionGroup.CSSTransition, 36154 { key: andId, classNames: "fade", timeout: { enter: 200, exit: 200 } }, 36155 React.createElement( 36156 "div", 36157 { className: "and query_arg" }, 36158 React.createElement( 36159 "span", 36160 { className: "hidden" }, 36161 "and" 36162 ), 36163 React.createElement(ANDQueryORArgs, { 36164 query: _this13.queryStrCache[andId], 36165 onQueryChange: function onQueryChange(qs) { 36166 return _this13.onQueryChange(andId, qs); 36167 }, 36168 handleRemoveADVAnd: function handleRemoveADVAnd() { 36169 return _this13.removeADVAnd(andId); 36170 } 36171 }) 36172 ) 36173 ); 36174 }); 36175 return React.createElement( 36176 "div", 36177 null, 36178 React.createElement( 36179 _reactTransitionGroup.TransitionGroup, 36180 null, 36181 andQueryArgs 36182 ), 36183 this.renderANDTokenFooter() 36184 ); 36185 } 24604 36186 }); 24605 36187 24606 36188 var ANDQueryORArgs = (0, _createReactClass2.default)({ 24607 displayName: "ANDQueryORArgs", 24608 24609 propTypes: { 24610 numAnds: PT.number.isRequired, 24611 parentAnd: PT.string.isRequired, 24612 handleRemoveADVAnd: PT.func.isRequired 24613 }, 24614 getInitialState: function getInitialState() { 24615 return { 24616 orCounter: 1, 24617 ors: [{ id: "or1", layerType: "string:lemma", placeholder: "Bagdad" }] 24618 }; 24619 }, 24620 24621 //shouldComponentUpdate: function (nextProps, nextState) { 24622 // return nextState.ors.length > 1; //!== this.state.ors.length; 24623 //}, 24624 24625 setADVTokenOp: function setADVTokenOp(op) { 24626 //fixme! - check agains valid layers 24627 return; 24628 }, 24629 24630 setADVInputDefault: function setADVInputDefault(or) { 24631 //fixme! - disable SearchButton if not atleast 1 token is in the query filter 24632 return; 24633 }, 24634 24635 validateADV: function validateADV(value) { 24636 //fixme! - disable SearchButton if not atleast 1 token is in the query filter 24637 return; 24638 }, 24639 24640 addADVOr: function addADVOr(e) { 24641 var i = this.state.orCounter + 1; 24642 this.state.ors.push({ id: 'or' + i, layerType: "string:pos", placeholder: "PROPN" }); 24643 this.setState({ orCounter: i, ors: this.state.ors }); 24644 }, 24645 24646 removeADVOr: function removeADVOr(id, e) { 24647 var ors = this.state.ors; 24648 var i = ors.indexOf(id); 24649 if (ors.length > 1) { 24650 var one = ors; 24651 var two = one.slice(0, i - 1).concat(one.slice(i));; 24652 this.setState({ ors: two }); 24653 } else if (ors.length === 1 && this.props.numAnds > 1) { 24654 this.props.handleRemoveADVAnd(this.props.parentAnd); 24655 } 24656 }, 24657 24658 render: function render() { 24659 var orArgs = this.state.ors.map(function (or, i) { 24660 return React.createElement( 24661 _reactTransitionGroup.CSSTransition, 24662 { key: i, classNames: "fade", timeout: { enter: 200, exit: 200 } }, 24663 React.createElement(ORArg, { key: or.id, 24664 data: or, 24665 handleRemoveADVOr: this.removeADVOr, 24666 handleSetADVInputDefault: this.setADVInputDefault, 24667 handleSetADVTokenOp: this.setADVTokenOp, 24668 handleValidateADV: this.validateADV 24669 }) 24670 ); 24671 }.bind(this)); 24672 return React.createElement( 24673 "div", 24674 null, 24675 React.createElement( 24676 "div", 24677 { className: "or_container" }, 24678 React.createElement( 24679 _reactTransitionGroup.TransitionGroup, 24680 null, 24681 orArgs 24682 ) 24683 ), 24684 React.createElement( 24685 "div", 24686 { className: "arg_footer" }, 24687 React.createElement( 24688 "span", 24689 { className: "link", onClick: this.addADVOr, ref: 'addOR' + this.props.numAnds }, 24690 "or" 24691 ), 24692 React.createElement("div", { style: { clear: "both" } }) 24693 ) 24694 ); 24695 } 36189 displayName: "ANDQueryORArgs", 36190 36191 propTypes: { 36192 query: PT.string, 36193 onQueryChange: PT.func.isRequired, 36194 handleRemoveADVAnd: PT.func.isRequired 36195 }, 36196 36197 getInitialState: function getInitialState() { 36198 var _this14 = this; 36199 36200 this.queryStrCache = {}; 36201 36202 console.log('ANDQueryORArgs:', this.props.query); 36203 var match = queryToORArgs(this.props.query); 36204 console.log('ANDQueryORArgs 2:', match); 36205 36206 if (match === null) { 36207 return { 36208 ors: ["or-" + nextId()] 36209 }; 36210 } 36211 36212 var ors = []; 36213 match.forEach(function (m) { 36214 var id = 'or-' + nextId(); 36215 ors.push(id); 36216 _this14.queryStrCache[id] = m; 36217 }); 36218 36219 return { 36220 ors: ors 36221 }; 36222 }, 36223 36224 validateADV: function validateADV(value) { 36225 //fixme! - disable SearchButton if not atleast 1 token is in the query filter 36226 return; 36227 }, 36228 36229 fireQueryChange: function fireQueryChange() { 36230 var _this15 = this; 36231 36232 var orParts = this.state.ors.map(function (id) { 36233 return _this15.queryStrCache[id]; 36234 }); 36235 var queryString = orParts.length >= 2 ? '( ' + orParts.join(' | ') + ' )' : orParts[0]; 36236 this.props.onQueryChange(queryString); 36237 }, 36238 36239 36240 addADVOr: function addADVOr(e) { 36241 var _this16 = this; 36242 36243 this.setState(function (oldSt) { 36244 oldSt.ors.push('or-' + nextId()); 36245 return { ors: _this16.state.ors }; 36246 }); 36247 }, 36248 36249 removeADVOr: function removeADVOr(id) { 36250 var _this17 = this; 36251 36252 this.setState(function (oldSt) { 36253 delete _this17.queryStrCache[id]; 36254 oldSt.ors.splice(oldSt.ors.indexOf(id), 1); 36255 return { ors: oldSt.ors }; 36256 }, function () { 36257 if (_this17.state.ors.length === 0) { 36258 _this17.props.handleRemoveADVAnd(); 36259 } else { 36260 _this17.fireQueryChange(); 36261 } 36262 }); 36263 }, 36264 36265 onQueryChange: function onQueryChange(orId, queryStr) { 36266 this.queryStrCache[orId] = queryStr; 36267 this.fireQueryChange(); 36268 }, 36269 render: function render() { 36270 var _this18 = this; 36271 36272 var orArgs = this.state.ors.map(function (orId) { 36273 return React.createElement( 36274 _reactTransitionGroup.CSSTransition, 36275 { key: orId, classNames: "fade", timeout: { enter: 200, exit: 200 } }, 36276 React.createElement(ORArg, { 36277 query: _this18.queryStrCache[orId], 36278 handleRemoveADVOr: function handleRemoveADVOr() { 36279 return _this18.removeADVOr(orId); 36280 }, 36281 handleValidateADV: function handleValidateADV() { 36282 return true; 36283 }, 36284 onQueryChange: function onQueryChange(qs) { 36285 return _this18.onQueryChange(orId, qs); 36286 } 36287 }) 36288 ); 36289 }); 36290 return React.createElement( 36291 "div", 36292 null, 36293 React.createElement( 36294 "div", 36295 { className: "or_container" }, 36296 React.createElement( 36297 _reactTransitionGroup.TransitionGroup, 36298 null, 36299 orArgs 36300 ) 36301 ), 36302 React.createElement( 36303 "div", 36304 { className: "arg_footer" }, 36305 React.createElement( 36306 "span", 36307 { className: "link", onClick: this.addADVOr }, 36308 "or" 36309 ), 36310 React.createElement("div", { style: { clear: "both" } }) 36311 ) 36312 ); 36313 } 24696 36314 }); 24697 36315 24698 36316 var ORArg = (0, _createReactClass2.default)({ 24699 displayName: "ORArg", 24700 24701 propTypes: { 24702 data: PT.object.isRequired, 24703 handleRemoveADVOr: PT.func.isRequired, 24704 handleSetADVInputDefault: PT.func.isRequired, 24705 handleSetADVTokenOp: PT.func.isRequired, 24706 handleValidateADV: PT.func.isRequired 24707 }, 24708 24709 render: function render() { 24710 return React.createElement( 24711 "div", 24712 { className: "or or_arg" }, 24713 React.createElement( 24714 "div", 24715 { className: "left_col" }, 24716 React.createElement( 24717 "button", 24718 { className: "btn btn-xs btn-default image_button remove_arg", onClick: this.props.handleRemoveADVOr.bind(null, this.props.data.id), ref: 'removeADVOr_' + this.props.data.id }, 24719 React.createElement("i", { className: "glyphicon glyphicon-minus" }) 24720 ) 24721 ), 24722 React.createElement( 24723 "div", 24724 { className: "right_col inline_block", style: { display: "inline-block" } }, 24725 " ", 24726 React.createElement( 24727 "div", 24728 { className: "arg_selects lemma" }, 24729 React.createElement( 24730 "select", 24731 { className: "arg_type", onChange: this.props.handleSetADVInputDefault("or"), defaultValue: this.props.data.layerType, ref: 'ANDLayerType_' + this.props.data.id }, 24732 React.createElement( 24733 "optgroup", 24734 { label: "word" }, 24735 React.createElement( 24736 "option", 24737 { value: "string:word", label: "word" }, 24738 "word" 24739 ) 24740 ), 24741 React.createElement( 24742 "optgroup", 24743 { label: "wordAttribute" }, 24744 React.createElement( 24745 "option", 24746 { value: "string:pos" }, 24747 "part-of-speech" 24748 ), 24749 React.createElement( 24750 "option", 24751 { value: "string:lemma" }, 24752 "lemma" 24753 ) 24754 ), 24755 React.createElement( 24756 "optgroup", 24757 { label: "textAttribute" }, 24758 React.createElement( 24759 "option", 24760 { value: "string:_.text_language", label: "language" }, 24761 "language" 24762 ) 24763 ) 24764 ), 24765 React.createElement( 24766 "select", 24767 { className: "arg_opts", defaultValue: "string:contains", onChange: this.props.handleSetADVTokenOp("op") }, 24768 React.createElement( 24769 "option", 24770 { value: "string:contains", label: "is" }, 24771 "is" 24772 ), 24773 React.createElement( 24774 "option", 24775 { value: "string:not contains", label: "is not" }, 24776 "is not" 24777 ) 24778 ) 24779 ), 24780 React.createElement( 24781 "div", 24782 { className: "arg_val_container" }, 24783 React.createElement("input", { id: 'inputADV_' + this.props.data.id, type: "text", defaultValue: this.props.data.placeholder, onChange: this.props.handleValidateADV, ref: 'textEntry_' + this.props.data.id }) 24784 ), 24785 React.createElement( 24786 "select", 24787 null, 24788 React.createElement( 24789 "option", 24790 { label: "PROPN", value: "string:PROPN" }, 24791 "Proper Noun" 24792 ) 24793 ) 24794 ) 24795 ); 24796 } 36317 displayName: "ORArg", 36318 36319 mixins: [_reactAddonsPureRenderMixin2.default], 36320 36321 propTypes: { 36322 query: PT.string, 36323 handleValidateADV: PT.func.isRequired, 36324 handleRemoveADVOr: PT.func.isRequired, 36325 onQueryChange: PT.func.isRequired 36326 }, 36327 36328 getInitialState: function getInitialState() { 36329 console.log('ORArg:', this.props.query); 36330 var qp = queryParse(this.props.query); 36331 console.log('ORArg 2:', qp); 36332 36333 if (qp !== null) { 36334 var layer = qp.layer; 36335 var op = qp.op; 36336 var val = qp.val; 36337 } 36338 return { 36339 layer: layer || 'word', 36340 argOpt: op || 'is', 36341 argValue: val || '', 36342 36343 editingText: false 36344 }; 36345 }, 36346 fireQueryChange: function fireQueryChange() { 36347 var queryString = layerToQueryString(this.state.layer, this.state.argOpt, this.state.argValue); 36348 this.props.onQueryChange(queryString); 36349 }, 36350 onlayerChange: function onlayerChange(evt) { 36351 var layer = evt.target.value; 36352 this.setState(function (st) { 36353 var argOpt = getLayerArgOpts(layer)[0].value; 36354 var lvo = getLayerValueOptions(layer, argOpt, st.argValue); 36355 var argValue = ''; 36356 if (lvo === undefined) argValue = '';else argValue = lvo[0].value; 36357 36358 return { 36359 layer: layer, 36360 argOpt: argOpt, 36361 argValue: argValue 36362 }; 36363 }); 36364 }, 36365 onArgOptChange: function onArgOptChange(evt) { 36366 var argOpt = evt.target.value; 36367 this.setState({ argOpt: argOpt }); 36368 }, 36369 onArgValueChange: function onArgValueChange(evt) { 36370 var value = evt.target.value; 36371 //console.log("picked arg value", value); 36372 36373 this.setState({ argValue: value }); 36374 }, 36375 componentDidMount: function componentDidMount() { 36376 this.fireQueryChange(); 36377 }, 36378 componentDidUpdate: function componentDidUpdate(prevProps, prevState) { 36379 // after state update. 36380 if (prevState.layer !== this.state.layer || prevState.argOpt !== this.state.argOpt || prevState.argValue !== this.state.argValue 36381 /*|| (!this.state.editingText && prevState.argValue !== this.state.argValue) // only update text-value input on field blur 36382 || (prevState.editingText !== this.state.editingText && prevState.editingText) // stopped editing text field. 36383 */ 36384 ) { 36385 this.fireQueryChange(); 36386 } 36387 }, 36388 renderInput: function renderInput() { 36389 var _this19 = this; 36390 36391 var valueOptions = getLayerValueOptions(this.state.layer, this.state.argOpt, this.state.argValue); 36392 36393 if (valueOptions === undefined) { 36394 return React.createElement("input", { type: "text", className: "form-control", 36395 value: this.state.argValue, 36396 onChange: this.onArgValueChange, 36397 onFocus: function onFocus() { 36398 return _this19.setState({ editingText: true }); 36399 }, 36400 onBlur: function onBlur() { 36401 return _this19.setState({ editingText: false }); 36402 } 36403 }); 36404 } else { 36405 return React.createElement( 36406 "select", 36407 { className: "form-control", value: this.state.argValue, onChange: this.onArgValueChange, onFocus: function onFocus() { 36408 return _this19.setState({ editingText: true }); 36409 }, onBlur: function onBlur() { 36410 return _this19.setState({ editingText: false }); 36411 } }, 36412 valueOptions.map(function (valOpt) { 36413 return React.createElement( 36414 "option", 36415 { value: valOpt.value }, 36416 valOpt.label 36417 ); 36418 }) 36419 ); 36420 } 36421 }, 36422 36423 36424 render: function render() { 36425 return React.createElement( 36426 "div", 36427 { className: "or or_arg" }, 36428 React.createElement( 36429 "div", 36430 { className: "left_col" }, 36431 React.createElement( 36432 "button", 36433 { className: "btn btn-xs btn-default image_button remove_arg", onClick: this.props.handleRemoveADVOr }, 36434 React.createElement("i", { className: "glyphicon glyphicon-minus" }) 36435 ) 36436 ), 36437 React.createElement( 36438 "div", 36439 { className: "right_col inline_block", style: { display: "inline-block" } }, 36440 " ", 36441 React.createElement( 36442 "div", 36443 { className: "arg_selects form-inline" }, 36444 React.createElement( 36445 "select", 36446 { className: "arg_type form-control", value: this.state.layer, onChange: this.onlayerChange }, 36447 layerCategories.map(function (cat) { 36448 return React.createElement( 36449 "optgroup", 36450 { label: cat.label }, 36451 cat.layers.map(function (layer) { 36452 return React.createElement( 36453 "option", 36454 { value: layer }, 36455 getLayerLabel(layer) 36456 ); 36457 }) 36458 ); 36459 }) 36460 ), 36461 React.createElement( 36462 "select", 36463 { className: "arg_opts form-control", value: this.state.argOpt, onChange: this.onArgOptChange }, 36464 getLayerArgOpts(this.state.layer).map(function (argOpt) { 36465 return React.createElement( 36466 "option", 36467 { value: argOpt.value }, 36468 argOpt.label 36469 ); 36470 }) 36471 ) 36472 ), 36473 React.createElement( 36474 "div", 36475 { className: "arg_val_container" }, 36476 this.renderInput() 36477 ) 36478 ) 36479 ); 36480 } 24797 36481 }); 24798 36482 36483 function getLayers() { 36484 var layers_arr = []; 36485 for (var l in layers) { 36486 layers_arr.push(l); 36487 } 36488 return layers_arr; 36489 } 36490 36491 function getLayerArgOpts(layer) { 36492 return layers[layer].argOpts; 36493 } 36494 36495 function isValidLayerOperator(layer, operator) { 36496 return !!layers[layer].argOpts.find(function (e) { 36497 return e.value === operator; 36498 }); 36499 } 36500 function isValidLayerValue(layer, operator, value) { 36501 var valopts = getLayerValueOptions(layer); 36502 if (!valopts) { 36503 return true; 36504 } 36505 return valopts.indexOf(value) !== -1; 36506 } 36507 36508 function layerToQueryString(layer, operator, value) { 36509 var toStr = layers[layer].toQueryString; 36510 if (!toStr) { 36511 toStr = getLayerArgOpts(layer).defaultToStr; 36512 } 36513 if (!toStr) { 36514 toStr = wordOptions.defaultToStr; 36515 console.warn("layerToQueryString: couldnt find a toQueryString method!"); 36516 } 36517 var qstr = toStr(layer, operator, value); 36518 if (qstr === undefined) { 36519 console.warn("layerToQueryString: qstr undefined!"); 36520 return 'undefined'; 36521 } 36522 return qstr; 36523 } 36524 36525 function getLayerLabel(layer) { 36526 return layers[layer].label; 36527 } 36528 36529 function getOperatorLabel(layer, operator) { 36530 return layers[layer].argOpts[operator].label; 36531 } 36532 36533 function getLayerValueOptions(layer, operator, value) { 36534 var valopts = layers[layer].valueOptions; 36535 if (!valopts) { 36536 return; 36537 } 36538 if (typeof valopts === 'function') { 36539 return valopts(layer, operator, value); 36540 } else if (valopts.length) { 36541 return valopts; // array 36542 } 36543 } 36544 36545 // a RE string matching a "double-quote"d string 36546 var quotedStringRE = /(?:"(?:\\"|[^"])*")/.source; 36547 36548 // in: 'word = "zebra" ' 36549 // out: ['word', '=', 'zebra'] 36550 function queryParse(q) { 36551 if (!q) return null; 36552 var match = q.match(/^\s*(\w+) *(=|!=) *"((?:\\"|.)*?)"/); 36553 if (match === null) { 36554 return null; 36555 } 36556 36557 var layer = match[1]; 36558 var op = match[2]; 36559 var value = match[3]; 36560 36561 var fromStr = getLayerArgOpts(layer).fromQueryString; 36562 if (!fromStr) { 36563 fromStr = getLayerArgOpts(layer).defaultFromString; 36564 } 36565 if (!fromStr) { 36566 fromStr = wordOptions.defaultFromStr; 36567 log.error("queryParse: couldnt find a fromQueryString method!"); 36568 } 36569 36570 return fromStr(layer, op, value); 36571 } 36572 36573 // in: '(word = "zebra" | word = "zoo" ...)' 36574 // out: ['word = "zebra" ', ' (word = "zoo" ...)'] 36575 function queryToORArgs(q) { 36576 if (!q) return null; 36577 var match = q.trim().match(queryToORArgs.re); 36578 return match; 36579 } 36580 queryToORArgs.re = RegExp('(?:' + quotedStringRE + '|[^()|])+', 'g'); 36581 36582 // in: '[word = "zebra" & (word = "zoo" ...)]' 36583 // out: ['word = "zebra" ', ' (word = "zoo" ...)'] 36584 function queryToANDArgs(q) { 36585 if (!q) return null; 36586 36587 var match = q.trim().match(queryToANDArgs.re); 36588 return match; 36589 } 36590 queryToANDArgs.re = RegExp('(?:' + quotedStringRE + '|[^&])+', 'g'); 36591 36592 // in: '[word = "zebra"] [word = "zoo"]' 36593 // out: ['[word = "zebra"]', '[word = "zoo"]'] 36594 function queryToTokens(q) { 36595 if (!q) return null; 36596 var match = q.match(queryToTokens.re); 36597 return match; 36598 } 36599 queryToTokens.re = RegExp('\\[(?:' + quotedStringRE + '|.)*?\\] *(?:\\{.*?\\})?', 'g'); 36600 36601 /*To simplify matching regex filter out words within "quotemarks". This help to not stumble on any special characters that can occur there. */ 36602 function filterWords(s, f) { 36603 var filteredString = s.replace(/("(?:\\"|[^"])*")/g, function (m) { 36604 filteredWords.push(m); 36605 return '""'; 36606 }); 36607 var ret = f(filteredString); 36608 // restore words 36609 36610 // return return value 36611 return ret; 36612 } 36613 36614 var wordOptions = [{ value: 'is', label: 'is' }, { value: 'is_not', label: 'is not' }, { value: 'contains', label: 'contains' }, { value: 'starts_with', label: 'starts with' }, { value: 'ends_with', label: 'ends with' }, { value: 'regex', label: 'regex' }, { value: 'not_regex', label: 'not regex' }]; 36615 var liteOptions = [{ value: "is", label: "is" }, { value: "is_not", label: "is not" }]; 36616 var setOptions = [{ value: "is", label: "is" }, { value: "is_not", label: "is not" }]; 36617 var probabilitySetOptions = [{ value: "is", label: "highest_rank" }, { value: "is_not", label: "not_highest_rank" }, { value: "contains", label: "rank_contains" }, { value: "contains_not", label: "not_rank_contains" }]; 36618 36619 setOptions.defaultToStr = function (layer, op, val) { 36620 switch (op) { 36621 case 'is': 36622 return layer + " = \"" + val + "\""; 36623 case 'is_not': 36624 return layer + " != \"" + val + "\""; 36625 } 36626 }; 36627 setOptions.defaultFromString = function (layer, op, val) { 36628 return { layer: layer, op: op === '!=' ? 'is_not' : 'is', val: val }; 36629 }; 36630 36631 wordOptions.defaultToStr = function (layer, op, val) { 36632 var unescVal = val; 36633 var val = escapeRegExp(val); 36634 switch (op) { 36635 case 'is': 36636 return layer + " = \"" + val + "\""; 36637 case 'is_not': 36638 return layer + " != \"" + val + "\""; 36639 case 'contains': 36640 return layer + " = \".*" + val + ".*\""; 36641 case 'starts_with': 36642 return layer + " = \"" + val + ".*\""; 36643 case 'ends_with': 36644 return layer + " = \".*" + val + "\""; 36645 case 'regex': 36646 return layer + " = \"" + unescVal + "\""; 36647 case 'not_regex': 36648 return layer + " != \"" + unescVal + "\""; 36649 } 36650 }; 36651 wordOptions.defaultFromString = function (layer, op, val) { 36652 // layer should be good. Now figure out op, and if val is escaped or not 36653 if (op === '=') { 36654 var strippedOfSemiRE = val.replace(/^\.\*/, '').replace(/\.\*$/, ''); 36655 if (strippedOfSemiRE.length !== val.length) { 36656 // could be one of: startswith, contains, endswith. 36657 if (!guessIfRegexp(strippedOfSemiRE)) { 36658 // Ok, it is one of: startswith, contains, endswith. 36659 if (val.startsWith('.*') && val.endsWith('.*')) { 36660 var op2 = 'contains'; 36661 } else if (val.startsWith('.*')) { 36662 op2 = 'starts_with'; 36663 } else if (val.endsWith('.*')) { 36664 op2 = 'ends_with'; 36665 } else { 36666 console.error("parsing query failed due to coding error"); 36667 return null; 36668 } 36669 return { 36670 layer: layer, 36671 op: op2, 36672 val: unescapeRegExp(strippedOfSemiRE) 36673 }; 36674 } 36675 // its regexp. 36676 } 36677 } 36678 36679 if (guessIfRegexp(val)) { 36680 // its regexp 36681 return { layer: layer, op: op === '=' ? 'regex' : 'not_regex', val: val }; 36682 } 36683 36684 // its not regexp 36685 return { layer: layer, op: op === '=' ? 'is' : 'is_not', val: unescapeRegExp(val) }; 36686 }; 36687 function guessIfRegexp(s) { 36688 return !!s.match(/[^\\][-[\]{}()*+\\?.,^$|#]/); // find if it contains any unescaped regex characters 36689 } 36690 function unescapeRegExp(text) { 36691 return text.replace(/\\([-[\]{}()*+?.,\\^$|#])/g, '$1'); 36692 } 36693 function escapeRegExp(text) { 36694 return text.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&'); 36695 } 36696 36697 var layers = { 36698 'word': { 36699 label: 'word', 36700 argOpts: wordOptions 36701 }, 36702 'pos': { 36703 label: 'part-of-speech UD v2.0 tagset', 36704 argOpts: setOptions, 36705 valueOptions: [{ value: "ADJ", label: "Adjective" }, { value: "ADV", label: "Adverb" }, { value: "INTJ", label: "Interjection" }, { value: "NOUN", label: "Noun" }, { value: "PROPN", label: "Proper noun" }, { value: "VERB", label: "Verb" }, { value: "ADP", label: "Adposition" }, { value: "AUX", label: "Auxiliary" }, { value: "CCONJ", label: "Coordinating conjunction" }, { value: "DET", label: "Determiner" }, { value: "NUM", label: "Numeral" }, { value: "PART", label: "Particle" }, { value: "PRON", label: "Pronoun" }, { value: "SCONJ", label: "Subordinating conjunction" }, { value: "PUNCT", label: "Punctuation" }, { value: "SYM", label: "Symbol" }, { value: "X", label: "Other" }] 36706 }, 36707 'lemma': { 36708 label: 'lemmatization of tokens', 36709 argOpts: wordOptions 36710 }, 36711 'orth': { 36712 label: 'orthographic transcription', 36713 argOpts: wordOptions 36714 }, 36715 'norm': { 36716 label: 'orthographic normalization', 36717 argOpts: wordOptions 36718 }, 36719 'phonetic': { 36720 label: 'phonetic transcription SAMPA', 36721 argOpts: wordOptions }, 36722 'text': { 36723 label: 'Layer only for Basic Search', 36724 argOpts: wordOptions 36725 }, 36726 '_.text_language': { 36727 label: 'language', 36728 argOpts: wordOptions 36729 } 36730 }; 36731 36732 var layerCategories = [{ cat: 'word', label: 'Word', layers: ['word'] }, { cat: 'wordAttribute', label: 'Word attribute', layers: ['pos', 'lemma', 'orth', 'norm', 'phonetic', 'text'] }, { cat: 'textAttribute', label: 'Text attribute', layers: ['_.text_language'] }]; 36733 24799 36734 module.exports = QueryInput; 24800 36735 24801 },{"classnames":1,"c reate-react-class":3,"prop-types":30,"react-transition-group":39}],54:[function(require,module,exports){36736 },{"classnames":1,"codemirror/mode/fcs-ql/fcs-ql":3,"codemirror/mode/javascript/javascript":4,"create-react-class":6,"prop-types":33,"react-addons-pure-render-mixin":36,"react-codemirror2":37,"react-transition-group":44}],59:[function(require,module,exports){ 24802 36737 "use strict"; 24803 36738 … … 25166 37101 module.exports = ResultMixin; 25167 37102 25168 },{"classnames":1,"prop-types":3 0}],55:[function(require,module,exports){37103 },{"classnames":1,"prop-types":33}],60:[function(require,module,exports){ 25169 37104 "use strict"; 25170 37105 … … 25367 37302 module.exports = Results; 25368 37303 25369 },{"./panel.jsx":5 2,"./resultmixin.jsx":54,"classnames":1,"create-react-class":3,"prop-types":30,"react-transition-group":39}],56:[function(require,module,exports){37304 },{"./panel.jsx":57,"./resultmixin.jsx":59,"classnames":1,"create-react-class":6,"prop-types":33,"react-transition-group":44}],61:[function(require,module,exports){ 25370 37305 "use strict"; 25371 37306 … … 25429 37364 module.exports = SearchCorpusBox; 25430 37365 25431 },{"classnames":1,"create-react-class": 3,"prop-types":30}],57:[function(require,module,exports){37366 },{"classnames":1,"create-react-class":6,"prop-types":33}],62:[function(require,module,exports){ 25432 37367 "use strict"; 25433 37368 … … 25629 37564 module.exports = ZoomedResult; 25630 37565 25631 },{"./resultmixin.jsx":5 4,"classnames":1,"create-react-class":3,"prop-types":30,"react-transition-group":39}],58:[function(require,module,exports){37566 },{"./resultmixin.jsx":59,"classnames":1,"create-react-class":6,"prop-types":33,"react-transition-group":44}],63:[function(require,module,exports){ 25632 37567 "use strict"; 25633 37568 … … 25677 37612 window.MyAggregator = window.MyAggregator || {}; 25678 37613 25679 var VERSION = window.MyAggregator.VERSION = "v. 2.9.91-57";25680 25681 var URLROOT = window.MyAggregator.URLROOT = 25682 //window.location.pathname .substring(0, window.location.pathname.indexOf("/",2))||25683 window.location.pathname ||"/Aggregator";37614 var VERSION = window.MyAggregator.VERSION = "v.3.0.0-64"; 37615 37616 var URLROOT = window.MyAggregator.URLROOT = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)) || 37617 //window.location.pathname || 37618 "/Aggregator"; 25684 37619 25685 37620 var PT = _propTypes2.default; … … 26001 37936 })(); 26002 37937 26003 },{"./components/embeddedfooter.jsx": 46,"./components/errorpane.jsx":47,"./components/footer.jsx":48,"./pages/aboutpage.jsx":59,"./pages/aggregatorpage.jsx":60,"./pages/helppage.jsx":61,"./pages/statisticspage.jsx":62,"create-react-class":3,"prop-types":30}],59:[function(require,module,exports){37938 },{"./components/embeddedfooter.jsx":51,"./components/errorpane.jsx":52,"./components/footer.jsx":53,"./pages/aboutpage.jsx":64,"./pages/aggregatorpage.jsx":65,"./pages/helppage.jsx":66,"./pages/statisticspage.jsx":67,"create-react-class":6,"prop-types":33}],64:[function(require,module,exports){ 26004 37939 "use strict"; 26005 37940 … … 26026 37961 propTypes: { 26027 37962 toStatistics: PT.func.isRequired 37963 }, 37964 37965 toStatistics: function toStatistics(e) { 37966 this.props.toStatistics(true); 37967 e.preventDefault(); 37968 e.stopPropagation(); 26028 37969 }, 26029 37970 … … 26084 38025 React.createElement( 26085 38026 "button", 26086 { type: "button", className: "btn btn-default btn-lg", onClick: function () { 26087 this.props.toStatistics(true); 26088 }.bind(this) }, 38027 { type: "button", className: "btn btn-default btn-lg", onClick: this.toStatistics }, 26089 38028 React.createElement( 26090 38029 "span", … … 26247 38186 "a", 26248 38187 { href: "https://github.com/facebook/react/blob/master/LICENSE" }, 26249 " BSDlicense"38188 "MIT license" 26250 38189 ), 26251 38190 ")" … … 26356 38295 module.exports = AboutPage; 26357 38296 26358 },{"classnames":1,"create-react-class": 3,"prop-types":30}],60:[function(require,module,exports){38297 },{"classnames":1,"create-react-class":6,"prop-types":33}],65:[function(require,module,exports){ 26359 38298 "use strict"; 26360 38299 … … 26418 38357 26419 38358 getInitialState: function getInitialState() { 38359 var aggrContext = getQueryVariable('x-aggregation-context'); 38360 aggrContext = aggrContext && JSON.parse(aggrContext); 38361 26420 38362 return { 26421 38363 corpora: new Corpora([], this.updateCorpora), … … 26423 38365 weblichtLanguages: [], 26424 38366 queryTypeId: getQueryVariable('queryType') || 'cql', 26425 query: getQueryVariable('query') || '', 26426 aggregationContext: getQueryVariable('x-aggregation-context') || '', 38367 cqlQuery: (getQueryVariable('queryType') || 'cql') === 'cql' && getQueryVariable('query') || '', 38368 fcsQuery: (getQueryVariable('queryType') || 'cql') === 'fcs' && getQueryVariable('query') || '', 38369 aggregationContext: aggrContext || null, 26427 38370 language: this.anyLanguage, 26428 38371 languageFilter: 'byMeta', … … 26433 38376 hits: this.nohits, 26434 38377 26435 zoomedCorpusHit: null, 26436 _isMounted: false 38378 zoomedCorpusHit: null 26437 38379 }; 26438 38380 }, 26439 38381 26440 38382 componentDidMount: function componentDidMount() { 26441 this. setState({ _isMounted: true });38383 this._isMounted = true; 26442 38384 26443 38385 this.props.ajax({ 26444 38386 url: 'rest/init', 26445 38387 success: function (json, textStatus, jqXHR) { 26446 if (this. state._isMounted) {38388 if (this._isMounted) { 26447 38389 var corpora = new Corpora(json.corpora, this.updateCorpora); 38390 38391 // // for testing aggregation context 38392 // json['x-aggregation-context'] = { 38393 // 'EKUT': ["http://hdl.handle.net/11858/00-1778-0000-0001-DDAF-D"] 38394 // }; 38395 38396 var aggregationContext = json['x-aggregation-context'] || this.state.aggregationContext; 38397 38398 window.MyAggregator.mode = getQueryVariable('mode') || json.mode; 26448 38399 window.MyAggregator.corpora = json.corpora; 38400 window.MyAggregator.xAggregationContext = aggregationContext; 38401 38402 // Setting visibility, e.g. only corpora 38403 // from v2.0 endpoints for fcs v2.0 38404 corpora.setVisibility(this.state.queryTypeId, this.state.language[0]); 38405 38406 if (aggregationContext) { 38407 var contextCorporaInfo = corpora.setAggregationContext(aggregationContext); 38408 var unavailableCorporaHandles = contextCorporaInfo.unavailable; // list of unavailable aggregationContext 38409 if (unavailableCorporaHandles.length > 0) { 38410 this.props.error("Could not find requested collection handles:\n" + unavailableCorporaHandles.join('\n')); 38411 } 38412 38413 var actuallySelectedCorpora = corpora.getSelectedIds(); 38414 38415 if (contextCorporaInfo.selected.length !== actuallySelectedCorpora.length) { 38416 if (actuallySelectedCorpora.length === 0) { 38417 this.props.error("This search does not support the required collection(s), will search all collections instead"); // TODO give detailed reason its not supported. 38418 corpora.recurse(function (corpus) { 38419 corpus.selected = true; 38420 }); 38421 } else { 38422 var err = "Some required context collections are not supported for this search:\n"; 38423 err = err + contextCorpora.filter(function (c) { 38424 if (actuallySelectedCorpora.indexOf(c) === -1) { 38425 console.warn("Requested corpus but not available for selection", c); 38426 return true; 38427 } 38428 return false; 38429 }).map(function (c) { 38430 return c.title; 38431 }).join('\n'); 38432 this.props.error(err); 38433 } 38434 } 38435 } else { 38436 // no context set all visibl to selected as default. 38437 console.log("no context set, selecting all available"); 38438 corpora.recurse(function (c) { 38439 c.visible ? c.selected = true : null; 38440 }); 38441 } 38442 26449 38443 this.setState({ 26450 38444 corpora: corpora, 26451 38445 languageMap: json.languages, 26452 38446 weblichtLanguages: json.weblichtLanguages, 26453 query: this.state.query || json.query || '' 26454 }); 26455 // // for testing aggregation context 26456 // json['x-aggregation-context'] = { 26457 // 'EKUT': ["http://hdl.handle.net/11858/00-1778-0000-0001-DDAF-D"] 26458 // }; 26459 26460 if (this.state.aggregationContext && !json['x-aggregation-context']) { 26461 json['x-aggregation-context'] = JSON.parse(this.state.aggregationContext); 26462 console.log(json['x-aggregation-context']); 26463 } 26464 if (json['x-aggregation-context']) { 26465 window.MyAggregator.xAggregationContext = json["x-aggregation-context"]; 26466 corpora.setAggregationContext(json["x-aggregation-context"]); 26467 if (!corpora.getSelectedIds().length) { 26468 this.props.error("Cannot find the required collection, will search all collections instead"); 26469 corpora.recurse(function (corpus) { 26470 corpus.selected = true; 26471 }); 26472 } 26473 corpora.update(); 26474 } 26475 // Setting visibility, e.g. only corpora 26476 // from v2.0 endpoints for fcs v2.0 26477 this.state.corpora.setVisibility(this.state.queryTypeId, this.state.language[0]); 26478 corpora.update(); 26479 26480 if (getQueryVariable('mode') === 'search' || json.mode === 'search') { 26481 window.MyAggregator.mode = 'search'; 26482 this.search(); 26483 } 38447 aggregationContext: aggregationContext 38448 }, this.postInit); 38449 } else { 38450 console.warn("Got Aggregator init response, but not mounted!"); 26484 38451 } 26485 38452 }.bind(this) … … 26487 38454 }, 26488 38455 38456 postInit: function postInit() { 38457 if (window.MyAggregator.mode === 'search') { 38458 this.search(); 38459 } 38460 }, 38461 38462 26489 38463 updateCorpora: function updateCorpora(corpora) { 26490 38464 this.setState({ corpora: corpora }); 26491 38465 }, 26492 38466 38467 getCurrentQuery: function getCurrentQuery() { 38468 return this.state.queryTypeId === 'fcs' ? this.state.fcsQuery : this.state.cqlQuery; 38469 }, 26493 38470 search: function search() { 26494 var query = this. state.query;38471 var query = this.getCurrentQuery(); 26495 38472 var queryTypeId = this.state.queryTypeId; 26496 if (!query || this.props.embedded ) {38473 if (!query || this.props.embedded && window.MyAggregator.mode !== 'search') { 26497 38474 this.setState({ hits: this.nohits, searchId: null }); 26498 38475 return; … … 26532 38509 }); 26533 38510 }, 38511 38512 26534 38513 nextResults: function nextResults(corpusId) { 26535 38514 // console.log("searching next results in corpus:", corpusId); … … 26551 38530 26552 38531 refreshSearchResults: function refreshSearchResults() { 26553 if (!this.state.searchId || !this. state._isMounted) {38532 if (!this.state.searchId || !this._isMounted) { 26554 38533 return; 26555 38534 } … … 26611 38590 setQueryType: function setQueryType(queryTypeId) { 26612 38591 this.state.corpora.setVisibility(queryTypeId, this.state.language[0]); 38592 setQueryVariable('queryType', queryTypeId); 38593 setQueryVariable('query', queryTypeId === 'cql' ? this.state.cqlQuery : this.state.fcsQuery); 26613 38594 this.setState({ 26614 38595 queryTypeId: queryTypeId, 26615 38596 hits: this.nohits, 26616 searchId: null, 26617 displayADV: queryTypeId == "fcs" ? true : false, 26618 corpora: this.state.corpora }); 38597 searchId: null 38598 }); 26619 38599 }, 26620 38600 … … 26689 38669 }, 26690 38670 26691 onQuery: function onQuery(event) { 26692 this.setState({ query: event.target.value }); 26693 }, 26694 26695 onADVQuery: function onADVQuery(fcsql) { 26696 this.setState({ query: fcsql.target.value }); 38671 onQueryChange: function onQueryChange(queryStr) { 38672 if (this.state.queryTypeId === 'cql') { 38673 this.setState({ 38674 cqlQuery: queryStr || '' 38675 }); 38676 } else { 38677 this.setState({ 38678 fcsQuery: queryStr || '' 38679 }); 38680 } 38681 setQueryVariable('query', queryStr); 26697 38682 }, 26698 38683 … … 26700 38685 if (event.keyCode == 13) { 26701 38686 this.search(); 26702 }26703 },26704 26705 handleADVKey: function handleADVKey(event) {26706 if (event.keyCode == 13) {26707 this.addADVToken();26708 38687 } 26709 38688 }, … … 26731 38710 renderSearchButtonOrLink: function renderSearchButtonOrLink() { 26732 38711 if (this.props.embedded) { 26733 var query = this. state.query;38712 var query = this.getCurrentQuery(); 26734 38713 var queryTypeId = this.state.queryTypeId; 26735 38714 var btnClass = (0, _classnames2.default)({ 26736 38715 'btn': true, 26737 38716 'btn-default': queryTypeId === 'cql', 38717 'btn-primary': true, 26738 38718 'input-lg': true 26739 38719 }); … … 26753 38733 }, 26754 38734 38735 renderQueryInput: function renderQueryInput() { 38736 var queryType = queryTypeMap[this.state.queryTypeId]; 38737 return React.createElement(_queryinput2.default, { 38738 searchedLanguages: this.state.searchedLanguages || [multipleLanguageCode], 38739 corpora: this.props.corpora, 38740 queryTypeId: this.state.queryTypeId, 38741 query: this.getCurrentQuery() === undefined ? queryType.searchPlaceholder : this.getCurrentQuery(), 38742 embedded: this.props.embedded, 38743 placeholder: queryType.searchPlaceholder, 38744 onQueryChange: this.onQueryChange, 38745 onKeyDown: this.handleKey }); 38746 }, 38747 renderEmbed: function renderEmbed() { 38748 var queryType = queryTypeMap[this.state.queryTypeId]; 38749 38750 return React.createElement( 38751 "div", 38752 { className: "aligncenter", style: { marginLeft: 16, marginRight: 16 } }, 38753 React.createElement( 38754 "div", 38755 { className: "input-group" }, 38756 React.createElement( 38757 "span", 38758 { className: "input-group-addon", style: { backgroundColor: queryType.searchLabelBkColor } }, 38759 queryType.searchLabel 38760 ), 38761 this.renderQueryInput(), 38762 React.createElement( 38763 "div", 38764 { className: "input-group-btn" }, 38765 this.renderSearchButtonOrLink() 38766 ) 38767 ) 38768 ); 38769 }, 38770 renderGQB: function renderGQB() { 38771 var queryType = queryTypeMap[this.state.queryTypeId]; 38772 38773 return React.createElement( 38774 "div", 38775 { style: { marginLeft: 16, marginRight: 16 } }, 38776 React.createElement( 38777 "div", 38778 { className: "panel panel-default" }, 38779 React.createElement( 38780 "div", 38781 { className: "panel-heading", style: { backgroundColor: queryType.searchLabelBkColor, fontSize: "120%" } }, 38782 queryType.searchLabel 38783 ), 38784 React.createElement( 38785 "div", 38786 { className: "panel-body" }, 38787 this.renderQueryInput() 38788 ), 38789 React.createElement( 38790 "div", 38791 { className: "panel-footer" }, 38792 React.createElement( 38793 "div", 38794 { className: "input-group" }, 38795 React.createElement( 38796 "pre", 38797 { className: "adv-query-preview aligncenter input-control input-lg" }, 38798 this.getCurrentQuery() 38799 ), 38800 React.createElement( 38801 "div", 38802 { className: "input-group-btn" }, 38803 this.renderSearchButtonOrLink() 38804 ) 38805 ) 38806 ) 38807 ) 38808 ); 38809 }, 38810 renderUnavailableCorporaMessage: function renderUnavailableCorporaMessage() { 38811 if (!this.state.corpora) { 38812 return; 38813 } 38814 var unavailable = []; 38815 this.state.corpora.recurse(function (c) { 38816 if (c.selected && !c.visible) { 38817 unavailable.push(c); 38818 } 38819 if (c.selected) { 38820 // apparently a selected corpus 38821 } 38822 }); 38823 38824 if (unavailable.length) { 38825 return React.createElement( 38826 "div", 38827 { id: "unavailable-corpora-message", className: "text-muted" }, 38828 React.createElement( 38829 "div", 38830 { id: "unavailable-corpora-message-message" }, 38831 React.createElement( 38832 "a", 38833 { role: "button", "data-toggle": "dropdown" }, 38834 unavailable.length, 38835 " selected collection", 38836 unavailable.length > 1 ? 's are' : ' is', 38837 " disabled in this search mode." 38838 ) 38839 ), 38840 React.createElement( 38841 "ul", 38842 { id: "unavailable-corpora-message-list", className: "dropdown-menu" }, 38843 unavailable.map(function (c) { 38844 return React.createElement( 38845 "li", 38846 { className: "unavailable-corpora-message-item" }, 38847 c.name 38848 ); 38849 }) 38850 ) 38851 ); 38852 } 38853 }, 38854 38855 26755 38856 render: function render() { 38857 26756 38858 var queryType = queryTypeMap[this.state.queryTypeId]; 26757 38859 return React.createElement( … … 26761 38863 "div", 26762 38864 { className: "row" }, 26763 React.createElement( 26764 "div", 26765 { className: "aligncenter", style: { marginLeft: 16, marginRight: 16 } }, 26766 React.createElement( 26767 "div", 26768 { className: "input-group" }, 26769 React.createElement( 26770 "span", 26771 { className: "input-group-addon", style: { backgroundColor: queryType.searchLabelBkColor } }, 26772 queryType.searchLabel 26773 ), 26774 React.createElement(_queryinput2.default, { 26775 searchedLanguages: this.state.searchedLanguages || [multipleLanguageCode], 26776 queryTypeId: this.state.queryTypeId, 26777 query: this.state.query, 26778 embedded: this.props.embedded, 26779 placeholder: queryType.searchPlaceholder, 26780 onChange: this.onADVQuery, 26781 onQuery: this.onQuery, 26782 onKeyDown: this.handleKey }), 26783 React.createElement( 26784 "div", 26785 { className: "input-group-btn" }, 26786 this.renderSearchButtonOrLink() 26787 ) 26788 ) 26789 ) 38865 !this.props.embedded && this.state.queryTypeId == "fcs" ? this.renderGQB() : this.renderEmbed() 26790 38866 ), 26791 38867 React.createElement( 26792 38868 "div", 26793 { className: "wel ", style: { marginTop: 20 } },38869 { className: "well", style: { marginTop: 20 } }, 26794 38870 React.createElement( 26795 38871 "div", … … 26901 38977 "span", 26902 38978 null, 26903 "Collections" 38979 "Collections ", 38980 React.createElement( 38981 "small", 38982 { className: "text-muted" }, 38983 this.props.corpora && this.props.corpora.getSelectedMessage() 38984 ) 26904 38985 ) }, 26905 38986 React.createElement(_corpusview2.default, { corpora: this.state.corpora, languageMap: this.state.languageMap }) … … 26966 39047 this.recurse(function (corpus, index) { 26967 39048 corpus.visible = true; // visible in the corpus view 26968 corpus.selected = true; // selected in the corpus view39049 corpus.selected = false; // not selected in the corpus view, assign later 26969 39050 corpus.expanded = false; // not expanded in the corpus view 26970 39051 corpus.priority = 1; // used for ordering search results in corpus view … … 27043 39124 27044 39125 Corpora.prototype.setAggregationContext = function (endpoints2handles) { 39126 var _this = this; 39127 27045 39128 var selectSubTree = function selectSubTree(select, corpus) { 27046 39129 corpus.selected = select; … … 27052 39135 this.corpora.forEach(selectSubTree.bind(this, false)); 27053 39136 39137 var handlesNotFound = []; 27054 39138 var corporaToSelect = []; 27055 39139 _.pairs(endpoints2handles).forEach(function (endp) { 27056 39140 var endpoint = endp[0]; 27057 39141 var handles = endp[1]; 27058 console.log( endp);27059 console.log( handles);39142 console.log('setAggregationContext: endpoint', endpoint); 39143 console.log('setAggregationContext: handles', handles); 27060 39144 handles.forEach(function (handle) { 27061 this.recurse(function (corpus) { 39145 var found = false; 39146 _this.recurse(function (corpus) { 27062 39147 if (corpus.handle === handle) { 39148 found = true; 27063 39149 corporaToSelect.push(corpus); 27064 39150 } 27065 }.bind(this)); 27066 }.bind(this)); 27067 }.bind(this)); 39151 }); 39152 if (!found) { 39153 console.warn("Handle not found in corpora", handle); 39154 handlesNotFound.push(handle); 39155 } 39156 }); 39157 }); 27068 39158 27069 39159 corporaToSelect.forEach(selectSubTree.bind(this, true)); 39160 return { 'selected': corporaToSelect, 'unavailable': handlesNotFound }; 27070 39161 }; 27071 39162 … … 27075 39166 if (corpus.visible && corpus.selected) { 27076 39167 ids.push(corpus.id); 27077 return false; // top-most collection in tree, don't delve deeper 39168 //eturn false; // top-most collection in tree, don't delve deeper 39169 // But subcollections are also selectable on their own?... 27078 39170 } 27079 39171 return true; … … 27094 39186 }; 27095 39187 27096 function Corpora(corpora, updateFn) {27097 var that = this;27098 this.corpora = corpora;27099 this.update = function () {27100 updateFn(that);27101 };27102 27103 var sortFn = function sortFn(x, y) {27104 var r = x.institution.name.localeCompare(y.institution.name);27105 if (r !== 0) {27106 return r;27107 }27108 return x.title.toLowerCase().localeCompare(y.title.toLowerCase());27109 };27110 27111 this.recurse(function (corpus) {27112 corpus.subCorpora.sort(sortFn);27113 });27114 this.corpora.sort(sortFn);27115 27116 this.recurse(function (corpus, index) {27117 corpus.visible = true; // visible in the corpus view27118 corpus.selected = true; // selected in the corpus view27119 corpus.expanded = false; // not expanded in the corpus view27120 corpus.priority = 1; // used for ordering search results in corpus view27121 corpus.index = index; // original order, used for stable sort27122 });27123 }27124 27125 39188 function getQueryVariable(variable) { 27126 39189 var query = window.location.search.substring(1); 27127 39190 var vars = query.split('&'); 27128 console.log("vars: ", vars);27129 39191 for (var i = 0; i < vars.length; i++) { 27130 39192 var pair = vars[i].split('='); … … 27137 39199 } 27138 39200 27139 function Corpora(corpora, updateFn) { 27140 var that = this; 27141 this.corpora = corpora; 27142 this.update = function () { 27143 updateFn(that); 27144 }; 27145 27146 var sortFn = function sortFn(x, y) { 27147 var r = x.institution.name.localeCompare(y.institution.name); 27148 if (r !== 0) { 27149 return r; 39201 /* setter opposite of getQueryVariable*/ 39202 function setQueryVariable(qvar, value) { 39203 var query = window.location.search.substring(1); 39204 var vars = query.split('&'); 39205 var d = {}; 39206 d[qvar] = value; 39207 var found = false; 39208 for (var i = 0; i < vars.length; i++) { 39209 var pair = vars[i].split('='); 39210 if (decodeURIComponent(pair[0]) === qvar) { 39211 39212 vars[i] = encodeQueryData(d); 39213 found = true; 39214 break; 27150 39215 } 27151 return x.title.toLowerCase().localeCompare(y.title.toLowerCase()); 27152 }; 27153 27154 this.recurse(function (corpus) { 27155 corpus.subCorpora.sort(sortFn); 27156 }); 27157 this.corpora.sort(sortFn); 27158 27159 this.recurse(function (corpus, index) { 27160 corpus.visible = true; // visible in the corpus view 27161 corpus.selected = true; // selected in the corpus view 27162 corpus.expanded = false; // not expanded in the corpus view 27163 corpus.priority = 1; // used for ordering search results in corpus view 27164 corpus.index = index; // original order, used for stable sort 27165 }); 39216 } 39217 39218 if (!found) { 39219 // add to end of url 39220 vars.push(encodeQueryData(d)); 39221 } 39222 39223 var searchPart = vars.join('&'); 39224 var newUrl = window.location.origin + window.location.pathname + '?' + searchPart; 39225 console.log("set url", newUrl); 39226 window.history.replaceState(window.history.state, null, newUrl); 27166 39227 } 27167 39228 … … 27197 39258 module.exports = AggregatorPage; 27198 39259 27199 },{"../components/corpusview.jsx": 45,"../components/languageselector.jsx":50,"../components/modal.jsx":51,"../components/queryinput.jsx":53,"../components/results.jsx":55,"../components/zoomedresult.jsx":57,"classnames":1,"create-react-class":3,"prop-types":30}],61:[function(require,module,exports){39260 },{"../components/corpusview.jsx":50,"../components/languageselector.jsx":55,"../components/modal.jsx":56,"../components/queryinput.jsx":58,"../components/results.jsx":60,"../components/zoomedresult.jsx":62,"classnames":1,"create-react-class":6,"prop-types":33}],66:[function(require,module,exports){ 27200 39261 "use strict"; 27201 39262 … … 27300 39361 module.exports = HelpPage; 27301 39362 27302 },{"classnames":1,"create-react-class": 3,"prop-types":30}],62:[function(require,module,exports){39363 },{"classnames":1,"create-react-class":6,"prop-types":33}],67:[function(require,module,exports){ 27303 39364 "use strict"; 27304 39365 … … 27669 39730 module.exports = StatisticsPage; 27670 39731 27671 },{"classnames":1,"create-react-class": 3,"prop-types":30}]},{},[58]);39732 },{"classnames":1,"create-react-class":6,"prop-types":33}]},{},[63]); -
SRUAggregator/trunk/src/main/resources/assets/js/main.jsx
r7157 r7223 14 14 window.MyAggregator = window.MyAggregator || {}; 15 15 16 var VERSION = window.MyAggregator.VERSION = "v. 2.9.91-57";16 var VERSION = window.MyAggregator.VERSION = "v.3.0.0-64"; 17 17 18 18 var URLROOT = window.MyAggregator.URLROOT = 19 //window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)) ||20 window.location.pathname ||19 window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2)) || 20 //window.location.pathname || 21 21 "/Aggregator"; 22 22
Note: See TracChangeset
for help on using the changeset viewer.